# File: matplotlib-main/ci/check_version_number.py """""" import sys import matplotlib print(f'Version {matplotlib.__version__} installed') if matplotlib.__version__[0] == '0': sys.exit('Version incorrectly starts with 0') # File: matplotlib-main/ci/check_wheel_licenses.py """""" from pathlib import Path import sys import zipfile if len(sys.argv) <= 1: sys.exit('At least one wheel must be specified in command-line arguments.') project_dir = Path(__file__).parent.resolve().parent license_dir = project_dir / 'LICENSE' license_file_names = {path.name for path in sorted(license_dir.glob('*'))} for wheel in sys.argv[1:]: print(f'Checking LICENSE files in: {wheel}') with zipfile.ZipFile(wheel) as f: wheel_license_file_names = {Path(path).name for path in sorted(f.namelist()) if '.dist-info/LICENSE' in path} if not (len(wheel_license_file_names) and wheel_license_file_names.issuperset(license_file_names)): sys.exit(f'LICENSE file(s) missing:\n{wheel_license_file_names} !=\n{license_file_names}') # File: matplotlib-main/ci/export_sdist_name.py """""" import os from pathlib import Path import sys paths = [p.name for p in Path('dist').glob('*.tar.gz')] if len(paths) != 1: sys.exit(f'Only a single sdist is supported, but found: {paths}') print(paths[0]) with open(os.environ['GITHUB_OUTPUT'], 'a') as f: f.write(f'SDIST_NAME={paths[0]}\n') # File: matplotlib-main/ci/schemas/vendor_schemas.py """""" import os import pathlib import urllib.request HERE = pathlib.Path(__file__).parent SCHEMAS = ['https://json.schemastore.org/appveyor.json', 'https://json.schemastore.org/circleciconfig.json', 'https://json.schemastore.org/github-funding.json', 'https://json.schemastore.org/github-issue-config.json', 'https://json.schemastore.org/github-issue-forms.json', 'https://json.schemastore.org/codecov.json', 'https://json.schemastore.org/pull-request-labeler-5.json', 'https://github.com/microsoft/vscode-python/raw/main/schemas/conda-environment.json'] def print_progress(block_count, block_size, total_size): size = block_count * block_size if total_size != -1: size = min(size, total_size) width = 50 percent = size / total_size * 100 filled = int(percent // (100 // width)) percent_str = '█' * filled + '░' * (width - filled) print(f'{percent_str} {size:6d} / {total_size:6d}', end='\r') for json in HERE.glob('*.json'): os.remove(json) for schema in SCHEMAS: path = HERE / schema.rsplit('/', 1)[-1] print(f'Downloading {schema} to {path}') urllib.request.urlretrieve(schema, filename=path, reporthook=print_progress) print() path.write_text(path.read_text()) # File: matplotlib-main/doc/_embedded_plots/axes_margins.py import numpy as np import matplotlib.pyplot as plt (fig, ax) = plt.subplots(figsize=(6.5, 4)) x = np.linspace(0, 1, 33) y = -np.sin(x * 2 * np.pi) ax.plot(x, y, 'o') ax.margins(0.5, 0.2) ax.set_title('margins(x=0.5, y=0.2)') ax.set(xlim=ax.get_xlim(), ylim=ax.get_ylim()) def arrow(p1, p2, **props): ax.annotate('', p1, p2, arrowprops=dict(arrowstyle='<->', shrinkA=0, shrinkB=0, **props)) (axmin, axmax) = ax.get_xlim() (aymin, aymax) = ax.get_ylim() (xmin, xmax) = (x.min(), x.max()) (ymin, ymax) = (y.min(), y.max()) y0 = -0.8 ax.axvspan(axmin, xmin, color=('orange', 0.1)) ax.axvspan(xmax, axmax, color=('orange', 0.1)) arrow((xmin, y0), (xmax, y0), color='sienna') arrow((xmax, y0), (axmax, y0), color='orange') ax.text((xmax + axmax) / 2, y0 + 0.05, 'x margin\n* x data range', ha='center', va='bottom', color='orange') ax.text(0.55, y0 + 0.1, 'x data range', va='bottom', color='sienna') x0 = 0.1 ax.axhspan(aymin, ymin, color=('tab:green', 0.1)) ax.axhspan(ymax, aymax, color=('tab:green', 0.1)) arrow((x0, ymin), (x0, ymax), color='darkgreen') arrow((x0, ymax), (x0, aymax), color='tab:green') ax.text(x0, (ymax + aymax) / 2, ' y margin * y data range', va='center', color='tab:green') ax.text(x0, 0.5, ' y data range', color='darkgreen') # File: matplotlib-main/doc/conf.py from datetime import datetime, timezone import logging import os from pathlib import Path import re import shutil import subprocess import sys import time from urllib.parse import urlsplit, urlunsplit import warnings from packaging.version import parse as parse_version import sphinx import yaml import matplotlib print(f'Building Documentation for Matplotlib: {matplotlib.__version__}') is_release_build = tags.has('release') CIRCLECI = 'CIRCLECI' in os.environ DEVDOCS = CIRCLECI and os.environ.get('CIRCLE_PROJECT_USERNAME') == 'matplotlib' and (os.environ.get('CIRCLE_BRANCH') == 'main') and (not os.environ.get('CIRCLE_PULL_REQUEST', '').startswith('https://github.com/matplotlib/matplotlib/pull')) def _parse_skip_subdirs_file(): default_skip_subdirs = ['users/prev_whats_new/*', 'users/explain/*', 'api/*', 'gallery/*', 'tutorials/*', 'plot_types/*', 'devel/*'] try: with open('.mpl_skip_subdirs.yaml', 'r') as fin: print('Reading subdirectories to skip from', '.mpl_skip_subdirs.yaml') out = yaml.full_load(fin) return out['skip_subdirs'] except FileNotFoundError: with open('.mpl_skip_subdirs.yaml', 'w') as fout: yamldict = {'skip_subdirs': default_skip_subdirs, 'comment': 'For use with make html-skip-subdirs'} yaml.dump(yamldict, fout) print('Skipping subdirectories, but .mpl_skip_subdirs.yaml', 'not found so creating a default one. Edit this file', 'to customize which directories are included in build.') return default_skip_subdirs skip_subdirs = [] if 'skip_sub_dirs=1' in sys.argv: skip_subdirs = _parse_skip_subdirs_file() sourceyear = datetime.fromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())), timezone.utc).year sys.path.append(os.path.abspath('.')) sys.path.append('.') warnings.filterwarnings('error', append=True) extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', 'IPython.sphinxext.ipython_console_highlighting', 'IPython.sphinxext.ipython_directive', 'numpydoc', 'sphinx_gallery.gen_gallery', 'matplotlib.sphinxext.mathmpl', 'matplotlib.sphinxext.plot_directive', 'matplotlib.sphinxext.roles', 'matplotlib.sphinxext.figmpl_directive', 'sphinxcontrib.inkscapeconverter', 'sphinxext.github', 'sphinxext.math_symbol_table', 'sphinxext.missing_references', 'sphinxext.mock_gui_toolkits', 'sphinxext.skip_deprecated', 'sphinxext.redirect_from', 'sphinx_copybutton', 'sphinx_design', 'sphinx_tags'] exclude_patterns = ['api/prev_api_changes/api_changes_*/*', '**/*inc.rst', 'users/explain/index.rst'] exclude_patterns += skip_subdirs def _check_dependencies(): names = {**{ext: ext.split('.')[0] for ext in extensions}, 'colorspacious': 'colorspacious', 'mpl_sphinx_theme': 'mpl_sphinx_theme', 'sphinxcontrib.inkscapeconverter': 'sphinxcontrib-svg2pdfconverter'} missing = [] for name in names: try: __import__(name) except ImportError: missing.append(names[name]) if missing: raise ImportError(f"The following dependencies are missing to build the documentation: {', '.join(missing)}") if 'mpl_sphinx_theme' not in missing: import pydata_sphinx_theme import mpl_sphinx_theme print(f'pydata sphinx theme: {pydata_sphinx_theme.__version__}') print(f'mpl sphinx theme: {mpl_sphinx_theme.__version__}') if shutil.which('dot') is None: raise OSError('No binary named dot - graphviz must be installed to build the documentation') if shutil.which('latex') is None: raise OSError('No binary named latex - a LaTeX distribution must be installed to build the documentation') _check_dependencies() import sphinx_gallery if parse_version(sphinx_gallery.__version__) >= parse_version('0.16.0'): gallery_order_sectionorder = 'sphinxext.gallery_order.sectionorder' gallery_order_subsectionorder = 'sphinxext.gallery_order.subsectionorder' clear_basic_units = 'sphinxext.util.clear_basic_units' matplotlib_reduced_latex_scraper = 'sphinxext.util.matplotlib_reduced_latex_scraper' else: from sphinxext.gallery_order import sectionorder as gallery_order_sectionorder, subsectionorder as gallery_order_subsectionorder from sphinxext.util import clear_basic_units, matplotlib_reduced_latex_scraper if parse_version(sphinx_gallery.__version__) >= parse_version('0.17.0'): sg_matplotlib_animations = (True, 'mp4') else: sg_matplotlib_animations = True from sphinx_gallery import gen_rst warnings.filterwarnings('ignore', category=UserWarning, message='(\\n|.)*is non-interactive, and thus cannot be shown') def tutorials_download_error(record): if re.match('download file not readable: .*tutorials_(python|jupyter).zip', record.msg): return False logger = logging.getLogger('sphinx') logger.addFilter(tutorials_download_error) autosummary_generate = True autodoc_typehints = 'none' warnings.filterwarnings('ignore', category=DeprecationWarning, module='importlib', message='(\\n|.)*module was deprecated.*') autodoc_docstring_signature = True autodoc_default_options = {'members': None, 'undoc-members': None} warnings.filterwarnings('ignore', category=DeprecationWarning, module='sphinx.util.inspect') nitpicky = True missing_references_write_json = False missing_references_warn_unused_ignores = False intersphinx_mapping = {'Pillow': ('https://pillow.readthedocs.io/en/stable/', None), 'cycler': ('https://matplotlib.org/cycler/', None), 'dateutil': ('https://dateutil.readthedocs.io/en/stable/', None), 'ipykernel': ('https://ipykernel.readthedocs.io/en/latest/', None), 'numpy': ('https://numpy.org/doc/stable/', None), 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), 'pytest': ('https://pytest.org/en/stable/', None), 'python': ('https://docs.python.org/3/', None), 'scipy': ('https://docs.scipy.org/doc/scipy/', None), 'tornado': ('https://www.tornadoweb.org/en/stable/', None), 'xarray': ('https://docs.xarray.dev/en/stable/', None), 'meson-python': ('https://meson-python.readthedocs.io/en/stable/', None), 'pip': ('https://pip.pypa.io/en/stable/', None)} gallery_dirs = [f'{ed}' for ed in ['gallery', 'tutorials', 'plot_types', 'users/explain'] if f'{ed}/*' not in skip_subdirs] example_dirs = [] for gd in gallery_dirs: gd = gd.replace('gallery', 'examples').replace('users/explain', 'users_explain') example_dirs += [f'../galleries/{gd}'] sphinx_gallery_conf = {'backreferences_dir': Path('api', '_as_gen'), 'compress_images': ('thumbnails', 'images') if is_release_build else (), 'doc_module': ('matplotlib', 'mpl_toolkits'), 'examples_dirs': example_dirs, 'filename_pattern': '^((?!sgskip).)*$', 'gallery_dirs': gallery_dirs, 'image_scrapers': (matplotlib_reduced_latex_scraper,), 'image_srcset': ['2x'], 'junit': '../test-results/sphinx-gallery/junit.xml' if CIRCLECI else '', 'matplotlib_animations': sg_matplotlib_animations, 'min_reported_time': 1, 'plot_gallery': 'True', 'reference_url': {'matplotlib': None, 'mpl_toolkits': None}, 'prefer_full_module': {'mpl_toolkits\\.'}, 'remove_config_comments': True, 'reset_modules': ('matplotlib', clear_basic_units), 'subsection_order': gallery_order_sectionorder, 'thumbnail_size': (320, 224), 'within_subsection_order': gallery_order_subsectionorder, 'capture_repr': (), 'copyfile_regex': '.*\\.rst'} if parse_version(sphinx_gallery.__version__) >= parse_version('0.17.0'): sphinx_gallery_conf['parallel'] = True warnings.filterwarnings('default', category=UserWarning, module='joblib') if 'plot_gallery=0' in sys.argv: def gallery_image_warning_filter(record): msg = record.msg for pattern in sphinx_gallery_conf['gallery_dirs'] + ['_static/constrained_layout']: if msg.startswith(f'image file not readable: {pattern}'): return False if msg == 'Could not obtain image size. :scale: option is ignored.': return False return True logger = logging.getLogger('sphinx') logger.addFilter(gallery_image_warning_filter) tags_create_tags = True tags_page_title = 'All tags' tags_create_badges = True tags_badge_colors = {'animation': 'primary', 'component:*': 'secondary', 'event-handling': 'success', 'interactivity:*': 'dark', 'plot-type:*': 'danger', '*': 'light'} mathmpl_fontsize = 11.0 mathmpl_srcset = ['2x'] gen_rst.EXAMPLE_HEADER = '\n.. DO NOT EDIT.\n.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.\n.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:\n.. "{0}"\n.. LINE NUMBERS ARE GIVEN BELOW.\n\n.. only:: html\n\n .. meta::\n :keywords: codex\n\n .. note::\n :class: sphx-glr-download-link-note\n\n :ref:`Go to the end `\n to download the full example code.{2}\n\n.. rst-class:: sphx-glr-example-title\n\n.. _sphx_glr_{1}:\n\n' templates_path = ['_templates'] source_suffix = '.rst' source_encoding = 'utf-8' root_doc = 'index' try: SHA = subprocess.check_output(['git', 'describe', '--dirty']).decode('utf-8').strip() except (subprocess.CalledProcessError, FileNotFoundError): SHA = matplotlib.__version__ html_context = {'doc_version': SHA} project = 'Matplotlib' copyright = f'2002–2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012–{sourceyear} The Matplotlib development team' version = matplotlib.__version__ release = version today_fmt = '%B %d, %Y' unused_docs = [] pygments_style = 'sphinx' default_role = 'obj' formats = {'html': ('png', 100), 'latex': ('pdf', 100)} plot_formats = [formats[target] for target in ['html', 'latex'] if target in sys.argv] or list(formats.values()) plot_srcset = ['2x'] github_project_url = 'https://github.com/matplotlib/matplotlib/' def add_html_cache_busting(app, pagename, templatename, context, doctree): from sphinx.builders.html import Stylesheet, JavaScript css_tag = context['css_tag'] js_tag = context['js_tag'] def css_tag_with_cache_busting(css): if isinstance(css, Stylesheet) and css.filename is not None: url = urlsplit(css.filename) if not url.netloc and (not url.query): url = url._replace(query=SHA) css = Stylesheet(urlunsplit(url), priority=css.priority, **css.attributes) return css_tag(css) def js_tag_with_cache_busting(js): if isinstance(js, JavaScript) and js.filename is not None: url = urlsplit(js.filename) if not url.netloc and (not url.query): url = url._replace(query=SHA) js = JavaScript(urlunsplit(url), priority=js.priority, **js.attributes) return js_tag(js) context['css_tag'] = css_tag_with_cache_busting context['js_tag'] = js_tag_with_cache_busting html_css_files = ['mpl.css'] html_theme = 'mpl_sphinx_theme' html_theme_options = {'navbar_links': 'internal', 'collapse_navigation': not is_release_build, 'show_prev_next': False, 'switcher': {'json_url': f"https://output.circle-artifacts.com/output/job/{os.environ['CIRCLE_WORKFLOW_JOB_ID']}/artifacts/{os.environ['CIRCLE_NODE_INDEX']}/doc/build/html/_static/switcher.json" if CIRCLECI and (not DEVDOCS) else f'https://matplotlib.org/devdocs/_static/switcher.json?{SHA}', 'version_match': matplotlib.__version__ if matplotlib.__version_info__.releaselevel == 'final' else 'dev'}, 'navbar_end': ['theme-switcher', 'version-switcher', 'mpl_icon_links'], 'navbar_persistent': ['search-button'], 'footer_start': ['copyright', 'sphinx-version', 'doc_version'], 'announcement': 'unreleased' if not is_release_build else '', 'show_version_warning_banner': True} include_analytics = is_release_build if include_analytics: html_theme_options['analytics'] = {'plausible_analytics_domain': 'matplotlib.org', 'plausible_analytics_url': 'https://views.scientific-python.org/js/script.js'} html_static_path = ['_static'] html_file_suffix = '.html' html_baseurl = 'https://matplotlib.org/stable/' html_last_updated_fmt = '%b %d, %Y' html_index = 'index.html' html_sidebars = {'index': ['cheatsheet_sidebar.html', 'donate_sidebar.html'], 'users/release_notes': ['empty_sidebar.html']} html_show_sourcelink = False copybutton_prompt_text = '>>> |\\.\\.\\. ' copybutton_prompt_is_regexp = True html_use_index = False html_domain_index = False html_use_opensearch = 'https://matplotlib.org/stable' htmlhelp_basename = 'Matplotlibdoc' smartquotes = False html_favicon = '_static/favicon.ico' latex_paper_size = 'letter' latex_documents = [(root_doc, 'Matplotlib.tex', 'Matplotlib', 'John Hunter\\and Darren Dale\\and Eric Firing\\and Michael Droettboom\\and and the matplotlib development team', 'manual')] latex_logo = None latex_engine = 'xelatex' latex_elements = {} latex_elements['babel'] = '\\usepackage{babel}' latex_elements['fontenc'] = '\n\\usepackage{fontspec}\n\\defaultfontfeatures[\\rmfamily,\\sffamily,\\ttfamily]{}\n' latex_elements['fontpkg'] = '\n\\IfFontExistsTF{XITS}{\n \\setmainfont{XITS}\n}{\n \\setmainfont{XITS}[\n Extension = .otf,\n UprightFont = *-Regular,\n ItalicFont = *-Italic,\n BoldFont = *-Bold,\n BoldItalicFont = *-BoldItalic,\n]}\n\\IfFontExistsTF{FreeSans}{\n \\setsansfont{FreeSans}\n}{\n \\setsansfont{FreeSans}[\n Extension = .otf,\n UprightFont = *,\n ItalicFont = *Oblique,\n BoldFont = *Bold,\n BoldItalicFont = *BoldOblique,\n]}\n\\IfFontExistsTF{FreeMono}{\n \\setmonofont{FreeMono}\n}{\n \\setmonofont{FreeMono}[\n Extension = .otf,\n UprightFont = *,\n ItalicFont = *Oblique,\n BoldFont = *Bold,\n BoldItalicFont = *BoldOblique,\n]}\n% needed for \\mathbb (blackboard alphabet) to actually work\n\\usepackage{unicode-math}\n\\IfFontExistsTF{XITS Math}{\n \\setmathfont{XITS Math}\n}{\n \\setmathfont{XITSMath-Regular}[\n Extension = .otf,\n]}\n' latex_elements['passoptionstopackages'] = '\n \\PassOptionsToPackage{headheight=14pt}{geometry}\n' latex_elements['preamble'] = "\n % Show Parts and Chapters in Table of Contents\n \\setcounter{tocdepth}{0}\n % One line per author on title page\n \\DeclareRobustCommand{\\and}%\n {\\end{tabular}\\kern-\\tabcolsep\\\\\\begin{tabular}[t]{c}}%\n \\usepackage{etoolbox}\n \\AtBeginEnvironment{sphinxthebibliography}{\\appendix\\part{Appendices}}\n \\usepackage{expdlist}\n \\let\\latexdescription=\\description\n \\def\\description{\\latexdescription{}{} \\breaklabel}\n % But expdlist old LaTeX package requires fixes:\n % 1) remove extra space\n \\makeatletter\n \\patchcmd\\@item{{\\@breaklabel} }{{\\@breaklabel}}{}{}\n \\makeatother\n % 2) fix bug in expdlist's way of breaking the line after long item label\n \\makeatletter\n \\def\\breaklabel{%\n \\def\\@breaklabel{%\n \\leavevmode\\par\n % now a hack because Sphinx inserts \\leavevmode after term node\n \\def\\leavevmode{\\def\\leavevmode{\\unhbox\\voidb@x}}%\n }%\n }\n \\makeatother\n" latex_elements['maxlistdepth'] = '10' latex_elements['pointsize'] = '11pt' latex_elements['printindex'] = '\\footnotesize\\raggedright\\printindex' latex_appendices = [] latex_use_modindex = True latex_toplevel_sectioning = 'part' autoclass_content = 'both' texinfo_documents = [(root_doc, 'matplotlib', 'Matplotlib Documentation', 'John Hunter@*Darren Dale@*Eric Firing@*Michael Droettboom@*The matplotlib development team', 'Matplotlib', 'Python plotting package', 'Programming', 1)] numpydoc_show_class_members = False inheritance_graph_attrs = dict(size='1000.0', splines='polyline') inheritance_node_attrs = dict(height=0.02, margin=0.055, penwidth=1, width=0.01) inheritance_edge_attrs = dict(penwidth=1) graphviz_dot = shutil.which('dot') graphviz_output_format = 'svg' link_github = True if link_github: import inspect extensions.append('sphinx.ext.linkcode') def linkcode_resolve(domain, info): if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except AttributeError: return None if inspect.isfunction(obj): obj = inspect.unwrap(obj) try: fn = inspect.getsourcefile(obj) except TypeError: fn = None if not fn or fn.endswith('__init__.py'): try: fn = inspect.getsourcefile(sys.modules[obj.__module__]) except (TypeError, AttributeError, KeyError): fn = None if not fn: return None try: (source, lineno) = inspect.getsourcelines(obj) except (OSError, TypeError): lineno = None linespec = f'#L{lineno:d}-L{lineno + len(source) - 1:d}' if lineno else '' startdir = Path(matplotlib.__file__).parent.parent try: fn = os.path.relpath(fn, start=startdir).replace(os.path.sep, '/') except ValueError: return None if not fn.startswith(('matplotlib/', 'mpl_toolkits/')): return None version = parse_version(matplotlib.__version__) tag = 'main' if version.is_devrelease else f'v{version.public}' return f'https://github.com/matplotlib/matplotlib/blob/{tag}/lib/{fn}{linespec}' else: extensions.append('sphinx.ext.viewcode') def setup(app): if any((st in version for st in ('post', 'dev', 'alpha', 'beta'))): bld_type = 'dev' else: bld_type = 'rel' app.add_config_value('skip_sub_dirs', 0, '') app.add_config_value('releaselevel', bld_type, 'env') if sphinx.version_info[:2] < (7, 1): app.connect('html-page-context', add_html_cache_busting, priority=1000) # File: matplotlib-main/doc/sphinxext/gallery_order.py """""" from sphinx_gallery.sorting import ExplicitOrder UNSORTED = 'unsorted' examples_order = ['../galleries/examples/lines_bars_and_markers', '../galleries/examples/images_contours_and_fields', '../galleries/examples/subplots_axes_and_figures', '../galleries/examples/statistics', '../galleries/examples/pie_and_polar_charts', '../galleries/examples/text_labels_and_annotations', '../galleries/examples/color', '../galleries/examples/shapes_and_collections', '../galleries/examples/style_sheets', '../galleries/examples/pyplots', '../galleries/examples/axes_grid1', '../galleries/examples/axisartist', '../galleries/examples/showcase', UNSORTED, '../galleries/examples/userdemo'] tutorials_order = ['../galleries/tutorials/introductory', '../galleries/tutorials/intermediate', '../galleries/tutorials/advanced', UNSORTED, '../galleries/tutorials/provisional'] plot_types_order = ['../galleries/plot_types/basic', '../galleries/plot_types/stats', '../galleries/plot_types/arrays', '../galleries/plot_types/unstructured', '../galleries/plot_types/3D', UNSORTED] folder_lists = [examples_order, tutorials_order, plot_types_order] explicit_order_folders = [fd for folders in folder_lists for fd in folders[:folders.index(UNSORTED)]] explicit_order_folders.append(UNSORTED) explicit_order_folders.extend([fd for folders in folder_lists for fd in folders[folders.index(UNSORTED):]]) class MplExplicitOrder(ExplicitOrder): def __call__(self, item): if item in self.ordered_list: return f'{self.ordered_list.index(item):04d}' else: return f'{self.ordered_list.index(UNSORTED):04d}{item}' list_all = ['quick_start', 'pyplot', 'images', 'lifecycle', 'customizing', 'artists', 'legend_guide', 'color_cycle', 'constrainedlayout_guide', 'tight_layout_guide', 'text_intro', 'text_props', 'colors', 'color_demo', 'pie_features', 'pie_demo2', 'plot', 'scatter_plot', 'bar', 'stem', 'step', 'fill_between', 'imshow', 'pcolormesh', 'contour', 'contourf', 'barbs', 'quiver', 'streamplot', 'hist_plot', 'boxplot_plot', 'errorbar_plot', 'violin', 'eventplot', 'hist2d', 'hexbin', 'pie', 'tricontour', 'tricontourf', 'tripcolor', 'triplot', 'spines', 'spine_placement_demo', 'spines_dropped', 'multiple_yaxis_with_spines', 'centered_spines_with_arrows'] explicit_subsection_order = [item + '.py' for item in list_all] class MplExplicitSubOrder(ExplicitOrder): def __init__(self, src_dir): self.src_dir = src_dir self.ordered_list = explicit_subsection_order def __call__(self, item): if item in self.ordered_list: return f'{self.ordered_list.index(item):04d}' else: return 'zzz' + item sectionorder = MplExplicitOrder(explicit_order_folders) subsectionorder = MplExplicitSubOrder # File: matplotlib-main/doc/sphinxext/github.py """""" from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes def make_link_node(rawtext, app, type, slug, options): try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError(f'github_project_url configuration value is not set ({err})') from err ref = base + type + '/' + slug + '/' set_classes(options) prefix = '#' if type == 'pull': prefix = 'PR ' + prefix node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref, **options) return node def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]): try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error('GitHub issue number must be a number greater than or equal to 1; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return ([prb], [msg]) app = inliner.document.settings.env.app if 'pull' in name.lower(): category = 'pull' elif 'issue' in name.lower(): category = 'issues' else: msg = inliner.reporter.error('GitHub roles include "ghpull" and "ghissue", "%s" is invalid.' % name, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return ([prb], [msg]) node = make_link_node(rawtext, app, category, str(issue_num), options) return ([node], []) def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): ref = 'https://www.github.com/' + text node = nodes.reference(rawtext, text, refuri=ref, **options) return ([node], []) def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]): app = inliner.document.settings.env.app try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError(f'github_project_url configuration value is not set ({err})') from err ref = base + text node = nodes.reference(rawtext, text[:6], refuri=ref, **options) return ([node], []) def setup(app): app.add_role('ghissue', ghissue_role) app.add_role('ghpull', ghissue_role) app.add_role('ghuser', ghuser_role) app.add_role('ghcommit', ghcommit_role) app.add_config_value('github_project_url', None, 'env') metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata # File: matplotlib-main/doc/sphinxext/math_symbol_table.py import re from docutils.parsers.rst import Directive from matplotlib import _mathtext, _mathtext_data bb_pattern = re.compile('Bbb[A-Z]') scr_pattern = re.compile('scr[a-zA-Z]') frak_pattern = re.compile('frak[A-Z]') symbols = [['Lower-case Greek', 4, ('\\alpha', '\\beta', '\\gamma', '\\chi', '\\delta', '\\epsilon', '\\eta', '\\iota', '\\kappa', '\\lambda', '\\mu', '\\nu', '\\omega', '\\phi', '\\pi', '\\psi', '\\rho', '\\sigma', '\\tau', '\\theta', '\\upsilon', '\\xi', '\\zeta', '\\digamma', '\\varepsilon', '\\varkappa', '\\varphi', '\\varpi', '\\varrho', '\\varsigma', '\\vartheta')], ['Upper-case Greek', 4, ('\\Delta', '\\Gamma', '\\Lambda', '\\Omega', '\\Phi', '\\Pi', '\\Psi', '\\Sigma', '\\Theta', '\\Upsilon', '\\Xi')], ['Hebrew', 6, ('\\aleph', '\\beth', '\\gimel', '\\daleth')], ['Latin named characters', 6, '\\aa \\AA \\ae \\AE \\oe \\OE \\O \\o \\thorn \\Thorn \\ss \\eth \\dh \\DH'.split()], ['Delimiters', 5, _mathtext.Parser._delims], ['Big symbols', 5, _mathtext.Parser._overunder_symbols | _mathtext.Parser._dropsub_symbols], ['Standard function names', 5, {f'\\{fn}' for fn in _mathtext.Parser._function_names}], ['Binary operation symbols', 4, _mathtext.Parser._binary_operators], ['Relation symbols', 4, _mathtext.Parser._relation_symbols], ['Arrow symbols', 4, _mathtext.Parser._arrow_symbols], ['Dot symbols', 4, '\\cdots \\vdots \\ldots \\ddots \\adots \\Colon \\therefore \\because'.split()], ['Black-board characters', 6, [f'\\{symbol}' for symbol in _mathtext_data.tex2uni if re.match(bb_pattern, symbol)]], ['Script characters', 6, [f'\\{symbol}' for symbol in _mathtext_data.tex2uni if re.match(scr_pattern, symbol)]], ['Fraktur characters', 6, [f'\\{symbol}' for symbol in _mathtext_data.tex2uni if re.match(frak_pattern, symbol)]], ['Miscellaneous symbols', 4, '\\neg \\infty \\forall \\wp \\exists \\bigstar \\angle \\partial\n \\nexists \\measuredangle \\emptyset \\sphericalangle \\clubsuit\n \\varnothing \\complement \\diamondsuit \\imath \\Finv \\triangledown\n \\heartsuit \\jmath \\Game \\spadesuit \\ell \\hbar \\vartriangle\n \\hslash \\blacksquare \\blacktriangle \\sharp \\increment\n \\prime \\blacktriangledown \\Im \\flat \\backprime \\Re \\natural\n \\circledS \\P \\copyright \\circledR \\S \\yen \\checkmark \\$\n \\cent \\triangle \\QED \\sinewave \\dag \\ddag \\perthousand \\ac\n \\lambdabar \\L \\l \\degree \\danger \\maltese \\clubsuitopen\n \\i \\hermitmatrix \\sterling \\nabla \\mho'.split()]] def run(state_machine): def render_symbol(sym, ignore_variant=False): if ignore_variant and sym not in ('\\varnothing', '\\varlrtriangle'): sym = sym.replace('\\var', '\\') if sym.startswith('\\'): sym = sym.lstrip('\\') if sym not in _mathtext.Parser._overunder_functions | _mathtext.Parser._function_names: sym = chr(_mathtext_data.tex2uni[sym]) return f'\\{sym}' if sym in ('\\', '|', '+', '-', '*') else sym lines = [] for (category, columns, syms) in symbols: syms = sorted(syms, key=lambda sym: (render_symbol(sym, ignore_variant=True), sym.startswith('\\var')), reverse=category == 'Hebrew') rendered_syms = [f'{render_symbol(sym)} ``{sym}``' for sym in syms] columns = min(columns, len(syms)) lines.append('**%s**' % category) lines.append('') max_width = max(map(len, rendered_syms)) header = ('=' * max_width + ' ') * columns lines.append(header.rstrip()) for part in range(0, len(rendered_syms), columns): row = ' '.join((sym.rjust(max_width) for sym in rendered_syms[part:part + columns])) lines.append(row) lines.append(header.rstrip()) lines.append('') state_machine.insert_input(lines, 'Symbol table') return [] class MathSymbolTableDirective(Directive): has_content = False required_arguments = 0 optional_arguments = 0 final_argument_whitespace = False option_spec = {} def run(self): return run(self.state_machine) def setup(app): app.add_directive('math_symbol_table', MathSymbolTableDirective) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata if __name__ == '__main__': print('SYMBOLS NOT IN STIX:') all_symbols = {} for (category, columns, syms) in symbols: if category == 'Standard Function Names': continue for sym in syms: if len(sym) > 1: all_symbols[sym[1:]] = None if sym[1:] not in _mathtext_data.tex2uni: print(sym) all_symbols.update({v[1:]: k for (k, v) in _mathtext.Parser._accent_map.items()}) all_symbols.update({v: v for v in _mathtext.Parser._wide_accents}) print('SYMBOLS NOT IN TABLE:') for (sym, val) in _mathtext_data.tex2uni.items(): if sym not in all_symbols: print(f'{sym} = {chr(val)}') # File: matplotlib-main/doc/sphinxext/missing_references.py """""" from collections import defaultdict import json from pathlib import Path from docutils.utils import get_source_line from sphinx.util import logging as sphinx_logging import matplotlib logger = sphinx_logging.getLogger(__name__) def get_location(node, app): (source, line) = get_source_line(node) if source: if ':docstring of' in source: (path, *post) = source.rpartition(':docstring of') post = ''.join(post) else: path = source post = '' basepath = Path(app.srcdir).parent.resolve() fullpath = Path(path).resolve() try: path = fullpath.relative_to(basepath) except ValueError: path = Path('') / fullpath.name path = path.as_posix() else: path = '' post = '' if not line: line = '' return f'{path}{post}:{line}' def _truncate_location(location): return location.split(':', 1)[0] def handle_missing_reference(app, domain, node): refdomain = node['refdomain'] reftype = node['reftype'] target = node['reftarget'] location = get_location(node, app) domain_type = f'{refdomain}:{reftype}' app.env.missing_references_events[domain_type, target].add(location) if location in app.env.missing_references_ignored_references.get((domain_type, target), []): return True def warn_unused_missing_references(app, exc): basepath = Path(matplotlib.__file__).parent.parent.parent.resolve() srcpath = Path(app.srcdir).parent.resolve() if basepath != srcpath: return references_ignored = app.env.missing_references_ignored_references references_events = app.env.missing_references_events for ((domain_type, target), locations) in references_ignored.items(): missing_reference_locations = [_truncate_location(location) for location in references_events.get((domain_type, target), [])] for ignored_reference_location in locations: short_location = _truncate_location(ignored_reference_location) if short_location not in missing_reference_locations: msg = f'Reference {domain_type} {target} for {ignored_reference_location} can be removed from {app.config.missing_references_filename}. It is no longer a missing reference in the docs.' logger.warning(msg, location=ignored_reference_location, type='ref', subtype=domain_type) def save_missing_references(app, exc): json_path = Path(app.confdir) / app.config.missing_references_filename references_warnings = app.env.missing_references_events _write_missing_references_json(references_warnings, json_path) def _write_missing_references_json(records, json_path): transformed_records = defaultdict(dict) for ((domain_type, target), paths) in records.items(): transformed_records[domain_type][target] = sorted(paths) with json_path.open('w') as stream: json.dump(transformed_records, stream, sort_keys=True, indent=2) stream.write('\n') def _read_missing_references_json(json_path): with json_path.open('r') as stream: data = json.load(stream) ignored_references = {} for (domain_type, targets) in data.items(): for (target, locations) in targets.items(): ignored_references[domain_type, target] = locations return ignored_references def prepare_missing_references_setup(app): if not app.config.missing_references_enabled: return app.connect('warn-missing-reference', handle_missing_reference) if app.config.missing_references_warn_unused_ignores: app.connect('build-finished', warn_unused_missing_references) if app.config.missing_references_write_json: app.connect('build-finished', save_missing_references) json_path = Path(app.confdir) / app.config.missing_references_filename app.env.missing_references_ignored_references = _read_missing_references_json(json_path) if json_path.exists() else {} app.env.missing_references_events = defaultdict(set) def setup(app): app.add_config_value('missing_references_enabled', True, 'env') app.add_config_value('missing_references_write_json', False, 'env') app.add_config_value('missing_references_warn_unused_ignores', True, 'env') app.add_config_value('missing_references_filename', 'missing-references.json', 'env') app.connect('builder-inited', prepare_missing_references_setup) return {'parallel_read_safe': True} # File: matplotlib-main/doc/sphinxext/redirect_from.py """""" from pathlib import Path from sphinx.util.docutils import SphinxDirective from sphinx.domains import Domain from sphinx.util import logging logger = logging.getLogger(__name__) HTML_TEMPLATE = '\n\n \n \n \n \n\n' def setup(app): app.add_directive('redirect-from', RedirectFrom) app.add_domain(RedirectFromDomain) app.connect('builder-inited', _clear_redirects) app.connect('build-finished', _generate_redirects) metadata = {'parallel_read_safe': True} return metadata class RedirectFromDomain(Domain): name = 'redirect_from' label = 'redirect_from' @property def redirects(self): return self.data.setdefault('redirects', {}) def clear_doc(self, docname): self.redirects.pop(docname, None) def merge_domaindata(self, docnames, otherdata): for (src, dst) in otherdata['redirects'].items(): if src not in self.redirects: self.redirects[src] = dst elif self.redirects[src] != dst: raise ValueError(f"Inconsistent redirections from {src} to {self.redirects[src]} and {otherdata['redirects'][src]}") class RedirectFrom(SphinxDirective): required_arguments = 1 def run(self): (redirected_doc,) = self.arguments domain = self.env.get_domain('redirect_from') current_doc = self.env.path2doc(self.state.document.current_source) (redirected_reldoc, _) = self.env.relfn2path(redirected_doc, current_doc) if redirected_reldoc in domain.redirects: raise ValueError(f'{redirected_reldoc} is already noted as redirecting to {domain.redirects[redirected_reldoc]}') domain.redirects[redirected_reldoc] = current_doc return [] def _generate_redirects(app, exception): builder = app.builder if builder.name != 'html' or exception: return for (k, v) in app.env.get_domain('redirect_from').redirects.items(): p = Path(app.outdir, k + builder.out_suffix) html = HTML_TEMPLATE.format(v=builder.get_relative_uri(k, v)) if p.is_file(): if p.read_text() != html: logger.warning('A redirect-from directive is trying to create %s, but that file already exists (perhaps you need to run "make clean")', p) else: logger.info('making refresh html file: %s redirect to %s', k, v) p.parent.mkdir(parents=True, exist_ok=True) p.write_text(html, encoding='utf-8') def _clear_redirects(app): domain = app.env.get_domain('redirect_from') if domain.redirects: logger.info('clearing cached redirects') domain.redirects.clear() # File: matplotlib-main/doc/sphinxext/skip_deprecated.py def skip_deprecated(app, what, name, obj, skip, options): if skip: return skip skipped = {'matplotlib.colors': ['ColorConverter', 'hex2color', 'rgb2hex']} skip_list = skipped.get(getattr(obj, '__module__', None)) if skip_list is not None: return getattr(obj, '__name__', None) in skip_list def setup(app): app.connect('autodoc-skip-member', skip_deprecated) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata # File: matplotlib-main/doc/sphinxext/util.py import sys def matplotlib_reduced_latex_scraper(block, block_vars, gallery_conf, **kwargs): from sphinx_gallery.scrapers import matplotlib_scraper if gallery_conf['builder_name'] == 'latex': gallery_conf['image_srcset'] = [] return matplotlib_scraper(block, block_vars, gallery_conf, **kwargs) def clear_basic_units(gallery_conf, fname): return sys.modules.pop('basic_units', None) # File: matplotlib-main/doc/users/generate_credits.py from collections import Counter import locale import re import subprocess TEMPLATE = ".. Note: This file is auto-generated using generate_credits.py\n\n.. _credits:\n\n*******\nCredits\n*******\n\n\nMatplotlib was written by John D. Hunter, with contributions from an\never-increasing number of users and developers. The current lead developer is\nThomas A. Caswell, who is assisted by many `active developers\n`_.\nPlease also see our instructions on :doc:`/citing`.\n\nThe following is a list of contributors extracted from the\ngit revision control history of the project:\n\n{contributors}\n\nSome earlier contributors not included above are (with apologies\nto any we have missed):\n\nCharles Twardy,\nGary Ruben,\nJohn Gill,\nDavid Moore,\nPaul Barrett,\nJared Wahlstrand,\nJim Benson,\nPaul Mcguire,\nAndrew Dalke,\nNadia Dencheva,\nBaptiste Carvello,\nSigve Tjoraand,\nTed Drain,\nJames Amundson,\nDaishi Harada,\nNicolas Young,\nPaul Kienzle,\nJohn Porter,\nand Jonathon Taylor.\n\nThanks to Tony Yu for the original logo design.\n\nWe also thank all who have reported bugs, commented on\nproposed changes, or otherwise contributed to Matplotlib's\ndevelopment and usefulness.\n" def check_duplicates(): text = subprocess.check_output(['git', 'shortlog', '--summary', '--email']) lines = text.decode('utf8').split('\n') contributors = [line.split('\t', 1)[1].strip() for line in lines if line] emails = [re.match('.*<(.*)>', line).group(1) for line in contributors] email_counter = Counter(emails) if email_counter.most_common(1)[0][1] > 1: print('DUPLICATE CHECK: The following email addresses are used with more than one name.\nConsider adding them to .mailmap.\n') for (email, count) in email_counter.items(): if count > 1: print('{}\n{}'.format(email, '\n'.join((l for l in lines if email in l)))) def generate_credits(): text = subprocess.check_output(['git', 'shortlog', '--summary']) lines = text.decode('utf8').split('\n') contributors = [line.split('\t', 1)[1].strip() for line in lines if line] contributors.sort(key=locale.strxfrm) with open('credits.rst', 'w') as f: f.write(TEMPLATE.format(contributors=',\n'.join(contributors))) if __name__ == '__main__': check_duplicates() generate_credits() # File: matplotlib-main/galleries/plot_types/3D/bar3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = [1, 1, 2, 2] y = [1, 2, 1, 2] z = [0, 0, 0, 0] dx = np.ones_like(x) * 0.5 dy = np.ones_like(x) * 0.5 dz = [2, 3, 1, 4] (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.bar3d(x, y, z, dx, dy, dz) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/fill_between3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') n = 50 theta = np.linspace(0, 2 * np.pi, n) x1 = np.cos(theta) y1 = np.sin(theta) z1 = np.linspace(0, 1, n) x2 = np.cos(theta + np.pi) y2 = np.sin(theta + np.pi) z2 = z1 (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.fill_between(x1, y1, z1, x2, y2, z2, alpha=0.5) ax.plot(x1, y1, z1, linewidth=2, color='C0') ax.plot(x2, y2, z2, linewidth=2, color='C0') ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/plot3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') n = 100 xs = np.linspace(0, 1, n) ys = np.sin(xs * 6 * np.pi) zs = np.cos(xs * 6 * np.pi) (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.plot(xs, ys, zs) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/quiver3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') n = 4 x = np.linspace(-1, 1, n) y = np.linspace(-1, 1, n) z = np.linspace(-1, 1, n) (X, Y, Z) = np.meshgrid(x, y, z) U = (X + Y) / 5 V = (Y - X) / 5 W = Z * 0 (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.quiver(X, Y, Z, U, V, W) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/scatter3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(19680801) n = 100 rng = np.random.default_rng() xs = rng.uniform(23, 32, n) ys = rng.uniform(0, 100, n) zs = rng.uniform(-50, -25, n) (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.scatter(xs, ys, zs) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/stem3d.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') n = 20 x = np.sin(np.linspace(0, 2 * np.pi, n)) y = np.cos(np.linspace(0, 2 * np.pi, n)) z = np.linspace(0, 1, n) (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.stem(x, y, z) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/surface3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np from matplotlib import cm plt.style.use('_mpl-gallery') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) (X, Y) = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.plot_surface(X, Y, Z, vmin=Z.min() * 2, cmap=cm.Blues) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/trisurf3d_simple.py """""" import matplotlib.pyplot as plt import numpy as np from matplotlib import cm plt.style.use('_mpl-gallery') n_radii = 8 n_angles = 36 radii = np.linspace(0.125, 1.0, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)[..., np.newaxis] x = np.append(0, (radii * np.cos(angles)).flatten()) y = np.append(0, (radii * np.sin(angles)).flatten()) z = np.sin(-x * y) (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.plot_trisurf(x, y, z, vmin=z.min() * 2, cmap=cm.Blues) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/voxels_simple.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') (x, y, z) = np.indices((8, 8, 8)) cube1 = (x < 3) & (y < 3) & (z < 3) cube2 = (x >= 5) & (y >= 5) & (z >= 5) voxelarray = cube1 | cube2 (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.voxels(voxelarray, edgecolor='k') ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/3D/wire3d_simple.py """""" import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d plt.style.use('_mpl-gallery') (X, Y, Z) = axes3d.get_test_data(0.05) (fig, ax) = plt.subplots(subplot_kw={'projection': '3d'}) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) ax.set(xticklabels=[], yticklabels=[], zticklabels=[]) plt.show() # File: matplotlib-main/galleries/plot_types/arrays/barbs.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') (X, Y) = np.meshgrid([1, 2, 3, 4], [1, 2, 3, 4]) angle = np.pi / 180 * np.array([[15.0, 30, 35, 45], [25.0, 40, 55, 60], [35.0, 50, 65, 75], [45.0, 60, 75, 90]]) amplitude = np.array([[5, 10, 25, 50], [10, 15, 30, 60], [15, 26, 50, 70], [20, 45, 80, 100]]) U = amplitude * np.sin(angle) V = amplitude * np.cos(angle) (fig, ax) = plt.subplots() ax.barbs(X, Y, U, V, barbcolor='C0', flagcolor='C0', length=7, linewidth=1.5) ax.set(xlim=(0, 4.5), ylim=(0, 4.5)) plt.show() # File: matplotlib-main/galleries/plot_types/arrays/contour.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') (X, Y) = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256)) Z = (1 - X / 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) levels = np.linspace(np.min(Z), np.max(Z), 7) (fig, ax) = plt.subplots() ax.contour(X, Y, Z, levels=levels) plt.show() # File: matplotlib-main/galleries/plot_types/arrays/contourf.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') (X, Y) = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256)) Z = (1 - X / 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) levels = np.linspace(Z.min(), Z.max(), 7) (fig, ax) = plt.subplots() ax.contourf(X, Y, Z, levels=levels) plt.show() # File: matplotlib-main/galleries/plot_types/arrays/imshow.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') (X, Y) = np.meshgrid(np.linspace(-3, 3, 16), np.linspace(-3, 3, 16)) Z = (1 - X / 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) (fig, ax) = plt.subplots() ax.imshow(Z, origin='lower') plt.show() # File: matplotlib-main/galleries/plot_types/arrays/pcolormesh.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') x = [-3, -2, -1.6, -1.2, -0.8, -0.5, -0.2, 0.1, 0.3, 0.5, 0.8, 1.1, 1.5, 1.9, 2.3, 3] (X, Y) = np.meshgrid(x, np.linspace(-3, 3, 128)) Z = (1 - X / 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) (fig, ax) = plt.subplots() ax.pcolormesh(X, Y, Z, vmin=-0.5, vmax=1.0) plt.show() # File: matplotlib-main/galleries/plot_types/arrays/quiver.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') x = np.linspace(-4, 4, 6) y = np.linspace(-4, 4, 6) (X, Y) = np.meshgrid(x, y) U = X + Y V = Y - X (fig, ax) = plt.subplots() ax.quiver(X, Y, U, V, color='C0', angles='xy', scale_units='xy', scale=5, width=0.015) ax.set(xlim=(-5, 5), ylim=(-5, 5)) plt.show() # File: matplotlib-main/galleries/plot_types/arrays/streamplot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') (X, Y) = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256)) Z = (1 - X / 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) V = np.diff(Z[1:, :], axis=1) U = -np.diff(Z[:, 1:], axis=0) (fig, ax) = plt.subplots() ax.streamplot(X[1:, 1:], Y[1:, 1:], U, V) plt.show() # File: matplotlib-main/galleries/plot_types/basic/bar.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = 0.5 + np.arange(8) y = [4.8, 5.5, 3.5, 4.6, 6.5, 6.6, 2.6, 3.0] (fig, ax) = plt.subplots() ax.bar(x, y, width=1, edgecolor='white', linewidth=0.7) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/basic/fill_between.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(1) x = np.linspace(0, 8, 16) y1 = 3 + 4 * x / 8 + np.random.uniform(0.0, 0.5, len(x)) y2 = 1 + 2 * x / 8 + np.random.uniform(0.0, 0.5, len(x)) (fig, ax) = plt.subplots() ax.fill_between(x, y1, y2, alpha=0.5, linewidth=0) ax.plot(x, (y1 + y2) / 2, linewidth=2) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/basic/plot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = np.linspace(0, 10, 100) y = 4 + 1 * np.sin(2 * x) x2 = np.linspace(0, 10, 25) y2 = 4 + 1 * np.sin(2 * x2) (fig, ax) = plt.subplots() ax.plot(x2, y2 + 2.5, 'x', markeredgewidth=2) ax.plot(x, y, linewidth=2.0) ax.plot(x2, y2 - 2.5, 'o-', linewidth=2) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/basic/scatter_plot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(3) x = 4 + np.random.normal(0, 2, 24) y = 4 + np.random.normal(0, 2, len(x)) sizes = np.random.uniform(15, 80, len(x)) colors = np.random.uniform(15, 80, len(x)) (fig, ax) = plt.subplots() ax.scatter(x, y, s=sizes, c=colors, vmin=0, vmax=100) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/basic/stackplot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = np.arange(0, 10, 2) ay = [1, 1.25, 2, 2.75, 3] by = [1, 1, 1, 1, 1] cy = [2, 1, 2, 1, 2] y = np.vstack([ay, by, cy]) (fig, ax) = plt.subplots() ax.stackplot(x, y) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/basic/stairs.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') y = [4.8, 5.5, 3.5, 4.6, 6.5, 6.6, 2.6, 3.0] (fig, ax) = plt.subplots() ax.stairs(y, linewidth=2.5) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/basic/stem.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = 0.5 + np.arange(8) y = [4.8, 5.5, 3.5, 4.6, 6.5, 6.6, 2.6, 3.0] (fig, ax) = plt.subplots() ax.stem(x, y) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/boxplot_plot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(10) D = np.random.normal((3, 5, 4), (1.25, 1.0, 1.25), (100, 3)) (fig, ax) = plt.subplots() VP = ax.boxplot(D, positions=[2, 4, 6], widths=1.5, patch_artist=True, showmeans=False, showfliers=False, medianprops={'color': 'white', 'linewidth': 0.5}, boxprops={'facecolor': 'C0', 'edgecolor': 'white', 'linewidth': 0.5}, whiskerprops={'color': 'C0', 'linewidth': 1.5}, capprops={'color': 'C0', 'linewidth': 1.5}) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/ecdf.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(1) x = 4 + np.random.normal(0, 1.5, 200) (fig, ax) = plt.subplots() ax.ecdf(x) plt.show() # File: matplotlib-main/galleries/plot_types/stats/errorbar_plot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(1) x = [2, 4, 6] y = [3.6, 5, 4.2] yerr = [0.9, 1.2, 0.5] (fig, ax) = plt.subplots() ax.errorbar(x, y, yerr, fmt='o', linewidth=2, capsize=6) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/eventplot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(1) x = [2, 4, 6] D = np.random.gamma(4, size=(3, 50)) (fig, ax) = plt.subplots() ax.eventplot(D, orientation='vertical', lineoffsets=x, linewidth=0.75) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/hexbin.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') np.random.seed(1) x = np.random.randn(5000) y = 1.2 * x + np.random.randn(5000) / 3 (fig, ax) = plt.subplots() ax.hexbin(x, y, gridsize=20) ax.set(xlim=(-2, 2), ylim=(-3, 3)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/hist2d.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') np.random.seed(1) x = np.random.randn(5000) y = 1.2 * x + np.random.randn(5000) / 3 (fig, ax) = plt.subplots() ax.hist2d(x, y, bins=(np.arange(-3, 3, 0.1), np.arange(-3, 3, 0.1))) ax.set(xlim=(-2, 2), ylim=(-3, 3)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/hist_plot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(1) x = 4 + np.random.normal(0, 1.5, 200) (fig, ax) = plt.subplots() ax.hist(x, bins=8, linewidth=0.5, edgecolor='white') ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 56), yticks=np.linspace(0, 56, 9)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/pie.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') x = [1, 2, 3, 4] colors = plt.get_cmap('Blues')(np.linspace(0.2, 0.7, len(x))) (fig, ax) = plt.subplots() ax.pie(x, colors=colors, radius=3, center=(4, 4), wedgeprops={'linewidth': 1, 'edgecolor': 'white'}, frame=True) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/stats/violin.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(10) D = np.random.normal((3, 5, 4), (0.75, 1.0, 0.75), (200, 3)) (fig, ax) = plt.subplots() vp = ax.violinplot(D, [2, 4, 6], widths=2, showmeans=False, showmedians=False, showextrema=False) for body in vp['bodies']: body.set_alpha(0.9) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() # File: matplotlib-main/galleries/plot_types/unstructured/tricontour.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') np.random.seed(1) x = np.random.uniform(-3, 3, 256) y = np.random.uniform(-3, 3, 256) z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) levels = np.linspace(z.min(), z.max(), 7) (fig, ax) = plt.subplots() ax.plot(x, y, 'o', markersize=2, color='lightgrey') ax.tricontour(x, y, z, levels=levels) ax.set(xlim=(-3, 3), ylim=(-3, 3)) plt.show() # File: matplotlib-main/galleries/plot_types/unstructured/tricontourf.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') np.random.seed(1) x = np.random.uniform(-3, 3, 256) y = np.random.uniform(-3, 3, 256) z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) levels = np.linspace(z.min(), z.max(), 7) (fig, ax) = plt.subplots() ax.plot(x, y, 'o', markersize=2, color='grey') ax.tricontourf(x, y, z, levels=levels) ax.set(xlim=(-3, 3), ylim=(-3, 3)) plt.show() # File: matplotlib-main/galleries/plot_types/unstructured/tripcolor.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') np.random.seed(1) x = np.random.uniform(-3, 3, 256) y = np.random.uniform(-3, 3, 256) z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) (fig, ax) = plt.subplots() ax.plot(x, y, 'o', markersize=2, color='grey') ax.tripcolor(x, y, z) ax.set(xlim=(-3, 3), ylim=(-3, 3)) plt.show() # File: matplotlib-main/galleries/plot_types/unstructured/triplot.py """""" import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery-nogrid') np.random.seed(1) x = np.random.uniform(-3, 3, 256) y = np.random.uniform(-3, 3, 256) z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) (fig, ax) = plt.subplots() ax.triplot(x, y) ax.set(xlim=(-3, 3), ylim=(-3, 3)) plt.show() # File: matplotlib-main/galleries/tutorials/artists.py """""" import matplotlib.pyplot as plt import numpy as np fig = plt.figure() fig.subplots_adjust(top=0.8) ax1 = fig.add_subplot(211) ax1.set_ylabel('Voltage [V]') ax1.set_title('A sine wave') t = np.arange(0.0, 1.0, 0.01) s = np.sin(2 * np.pi * t) (line,) = ax1.plot(t, s, color='blue', lw=2) np.random.seed(19680801) ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3]) (n, bins, patches) = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='yellow') ax2.set_xlabel('Time [s]') plt.show() import matplotlib.lines as lines fig = plt.figure() l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig) l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig) fig.lines.extend([l1, l2]) plt.show() (fig, ax) = plt.subplots() axis = ax.xaxis axis.get_ticklocs() axis.get_ticklabels() axis.get_ticklines() axis.get_ticklabels(minor=True) axis.get_ticklines(minor=True) fig = plt.figure() rect = fig.patch rect.set_facecolor('lightgoldenrodyellow') ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) rect = ax1.patch rect.set_facecolor('lightslategray') for label in ax1.xaxis.get_ticklabels(): label.set_color('red') label.set_rotation(45) label.set_fontsize(16) for line in ax1.yaxis.get_ticklines(): line.set_color('green') line.set_markersize(25) line.set_markeredgewidth(3) plt.show() # File: matplotlib-main/galleries/tutorials/images.py """""" from PIL import Image import matplotlib.pyplot as plt import numpy as np img = np.asarray(Image.open('../../doc/_static/stinkbug.png')) print(repr(img)) imgplot = plt.imshow(img) lum_img = img[:, :, 0] plt.imshow(lum_img) plt.imshow(lum_img, cmap='hot') imgplot = plt.imshow(lum_img) imgplot.set_cmap('nipy_spectral') imgplot = plt.imshow(lum_img) plt.colorbar() plt.hist(lum_img.ravel(), bins=range(256), fc='k', ec='k') plt.imshow(lum_img, clim=(0, 175)) imgplot = plt.imshow(lum_img) imgplot.set_clim(0, 175) img = Image.open('../../doc/_static/stinkbug.png') img.thumbnail((64, 64)) imgplot = plt.imshow(img) imgplot = plt.imshow(img, interpolation='bilinear') imgplot = plt.imshow(img, interpolation='bicubic') # File: matplotlib-main/galleries/tutorials/lifecycle.py """""" import matplotlib.pyplot as plt import numpy as np data = {'Barton LLC': 109438.5, 'Frami, Hills and Schmidt': 103569.59, 'Fritsch, Russel and Anderson': 112214.71, 'Jerde-Hilpert': 112591.43, 'Keeling LLC': 100934.3, 'Koepp Ltd': 103660.54, 'Kulas Inc': 137351.96, 'Trantow-Barrows': 123381.38, 'White-Trantow': 135841.99, 'Will LLC': 104437.6} group_data = list(data.values()) group_names = list(data.keys()) group_mean = np.mean(group_data) (fig, ax) = plt.subplots() (fig, ax) = plt.subplots() ax.barh(group_names, group_data) print(plt.style.available) plt.style.use('fivethirtyeight') (fig, ax) = plt.subplots() ax.barh(group_names, group_data) (fig, ax) = plt.subplots() ax.barh(group_names, group_data) labels = ax.get_xticklabels() (fig, ax) = plt.subplots() ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') plt.rcParams.update({'figure.autolayout': True}) (fig, ax) = plt.subplots() ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') (fig, ax) = plt.subplots() ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue') (fig, ax) = plt.subplots(figsize=(8, 4)) ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue') def currency(x, pos): if x >= 1000000.0: s = f'${x * 1e-06:1.1f}M' else: s = f'${x * 0.001:1.0f}K' return s (fig, ax) = plt.subplots(figsize=(6, 8)) ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue') ax.xaxis.set_major_formatter(currency) (fig, ax) = plt.subplots(figsize=(8, 8)) ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') ax.axvline(group_mean, ls='--', color='r') for group in [3, 5, 8]: ax.text(145000, group, 'New Company', fontsize=10, verticalalignment='center') ax.title.set(y=1.05) ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue') ax.xaxis.set_major_formatter(currency) ax.set_xticks([0, 25000.0, 50000.0, 75000.0, 100000.0, 125000.0]) fig.subplots_adjust(right=0.1) plt.show() print(fig.canvas.get_supported_filetypes()) # File: matplotlib-main/galleries/tutorials/pyplot.py """""" import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show() plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') plt.axis((0, 6, 0, 20)) plt.show() import numpy as np t = np.arange(0.0, 5.0, 0.2) plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^') plt.show() data = {'a': np.arange(50), 'c': np.random.randint(0, 50, 50), 'd': np.random.randn(50)} data['b'] = data['a'] + 10 * np.random.randn(50) data['d'] = np.abs(data['d']) * 100 plt.scatter('a', 'b', c='c', s='d', data=data) plt.xlabel('entry a') plt.ylabel('entry b') plt.show() names = ['group_a', 'group_b', 'group_c'] values = [1, 10, 100] plt.figure(figsize=(9, 3)) plt.subplot(131) plt.bar(names, values) plt.subplot(132) plt.scatter(names, values) plt.subplot(133) plt.plot(names, values) plt.suptitle('Categorical Plotting') plt.show() def f(t): return np.exp(-t) * np.cos(2 * np.pi * t) t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) plt.figure() plt.subplot(211) plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') plt.subplot(212) plt.plot(t2, np.cos(2 * np.pi * t2), 'r--') plt.show() (mu, sigma) = (100, 15) x = mu + sigma * np.random.randn(10000) (n, bins, patches) = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, 0.025, '$\\mu=100,\\ \\sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() ax = plt.subplot() t = np.arange(0.0, 5.0, 0.01) s = np.cos(2 * np.pi * t) (line,) = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05)) plt.ylim(-2, 2) plt.show() np.random.seed(19680801) y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) plt.figure() plt.subplot(221) plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True) plt.subplot(222) plt.plot(x, y) plt.yscale('log') plt.title('log') plt.grid(True) plt.subplot(223) plt.plot(x, y - y.mean()) plt.yscale('symlog', linthresh=0.01) plt.title('symlog') plt.grid(True) plt.subplot(224) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) plt.subplots_adjust(top=0.92, bottom=0.08, left=0.1, right=0.95, hspace=0.25, wspace=0.35) plt.show() # File: matplotlib-main/galleries/users_explain/animations/animations.py """""" import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation (fig, ax) = plt.subplots() t = np.linspace(0, 3, 40) g = -9.81 v0 = 12 z = g * t ** 2 / 2 + v0 * t v02 = 5 z2 = g * t ** 2 / 2 + v02 * t scat = ax.scatter(t[0], z[0], c='b', s=5, label=f'v0 = {v0} m/s') line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0] ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time [s]', ylabel='Z [m]') ax.legend() def update(frame): x = t[:frame] y = z[:frame] data = np.stack([x, y]).T scat.set_offsets(data) line2.set_xdata(t[:frame]) line2.set_ydata(z2[:frame]) return (scat, line2) ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30) plt.show() (fig, ax) = plt.subplots() rng = np.random.default_rng(19680801) data = np.array([20, 20, 20, 20]) x = np.array([1, 2, 3, 4]) artists = [] colors = ['tab:blue', 'tab:red', 'tab:green', 'tab:purple'] for i in range(20): data += rng.integers(low=0, high=10, size=data.shape) container = ax.barh(x, data, color=colors) artists.append(container) ani = animation.ArtistAnimation(fig=fig, artists=artists, interval=400) plt.show() # File: matplotlib-main/galleries/users_explain/animations/blitting.py """""" import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2 * np.pi, 100) (fig, ax) = plt.subplots() (ln,) = ax.plot(x, np.sin(x), animated=True) plt.show(block=False) plt.pause(0.1) bg = fig.canvas.copy_from_bbox(fig.bbox) ax.draw_artist(ln) fig.canvas.blit(fig.bbox) for j in range(100): fig.canvas.restore_region(bg) ln.set_ydata(np.sin(x + j / 100 * np.pi)) ax.draw_artist(ln) fig.canvas.blit(fig.bbox) fig.canvas.flush_events() class BlitManager: def __init__(self, canvas, animated_artists=()): self.canvas = canvas self._bg = None self._artists = [] for a in animated_artists: self.add_artist(a) self.cid = canvas.mpl_connect('draw_event', self.on_draw) def on_draw(self, event): cv = self.canvas if event is not None: if event.canvas != cv: raise RuntimeError self._bg = cv.copy_from_bbox(cv.figure.bbox) self._draw_animated() def add_artist(self, art): if art.figure != self.canvas.figure: raise RuntimeError art.set_animated(True) self._artists.append(art) def _draw_animated(self): fig = self.canvas.figure for a in self._artists: fig.draw_artist(a) def update(self): cv = self.canvas fig = cv.figure if self._bg is None: self.on_draw(None) else: cv.restore_region(self._bg) self._draw_animated() cv.blit(fig.bbox) cv.flush_events() (fig, ax) = plt.subplots() (ln,) = ax.plot(x, np.sin(x), animated=True) fr_number = ax.annotate('0', (0, 1), xycoords='axes fraction', xytext=(10, -10), textcoords='offset points', ha='left', va='top', animated=True) bm = BlitManager(fig.canvas, [ln, fr_number]) plt.show(block=False) plt.pause(0.1) for j in range(100): ln.set_ydata(np.sin(x + j / 100 * np.pi)) fr_number.set_text(f'frame: {j}') bm.update() # File: matplotlib-main/galleries/users_explain/artists/color_cycle.py """""" from cycler import cycler import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2 * np.pi, 50) offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False) yy = np.transpose([np.sin(x + phi) for phi in offsets]) print(yy.shape) default_cycler = cycler(color=['r', 'g', 'b', 'y']) + cycler(linestyle=['-', '--', ':', '-.']) plt.rc('lines', linewidth=4) plt.rc('axes', prop_cycle=default_cycler) custom_cycler = cycler(color=['c', 'm', 'y', 'k']) + cycler(lw=[1, 2, 3, 4]) (fig, (ax0, ax1)) = plt.subplots(nrows=2) ax0.plot(yy) ax0.set_title('Set default color cycle to rgby') ax1.set_prop_cycle(custom_cycler) ax1.plot(yy) ax1.set_title('Set axes color cycle to cmyk') fig.subplots_adjust(hspace=0.3) plt.show() # File: matplotlib-main/galleries/users_explain/artists/imshow_extent.py """""" import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec def index_to_coordinate(index, extent, origin): (left, right, bottom, top) = extent hshift = 0.5 * np.sign(right - left) (left, right) = (left + hshift, right - hshift) vshift = 0.5 * np.sign(top - bottom) (bottom, top) = (bottom + vshift, top - vshift) if origin == 'upper': (bottom, top) = (top, bottom) return {'[0, 0]': (left, bottom), "[M', 0]": (left, top), "[0, N']": (right, bottom), "[M', N']": (right, top)}[index] def get_index_label_pos(index, extent, origin, inverted_xindex): if extent is None: extent = lookup_extent(origin) (left, right, bottom, top) = extent (x, y) = index_to_coordinate(index, extent, origin) is_x0 = index[-2:] == '0]' halign = 'left' if is_x0 ^ inverted_xindex else 'right' hshift = 0.5 * np.sign(left - right) x += hshift * (1 if is_x0 else -1) return (x, y, halign) def get_color(index, data, cmap): val = {'[0, 0]': data[0, 0], "[0, N']": data[0, -1], "[M', 0]": data[-1, 0], "[M', N']": data[-1, -1]}[index] return cmap(val / data.max()) def lookup_extent(origin): if origin == 'lower': return (-0.5, 6.5, -0.5, 5.5) else: return (-0.5, 6.5, 5.5, -0.5) def set_extent_None_text(ax): ax.text(3, 2.5, 'equals\nextent=None', size='large', ha='center', va='center', color='w') def plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim): im = ax.imshow(data, origin=origin, extent=extent) (left, right, bottom, top) = im.get_extent() if xlim is None or top > bottom: (upper_string, lower_string) = ('top', 'bottom') else: (upper_string, lower_string) = ('bottom', 'top') if ylim is None or left < right: (port_string, starboard_string) = ('left', 'right') inverted_xindex = False else: (port_string, starboard_string) = ('right', 'left') inverted_xindex = True bbox_kwargs = {'fc': 'w', 'alpha': 0.75, 'boxstyle': 'round4'} ann_kwargs = {'xycoords': 'axes fraction', 'textcoords': 'offset points', 'bbox': bbox_kwargs} ax.annotate(upper_string, xy=(0.5, 1), xytext=(0, -1), ha='center', va='top', **ann_kwargs) ax.annotate(lower_string, xy=(0.5, 0), xytext=(0, 1), ha='center', va='bottom', **ann_kwargs) ax.annotate(port_string, xy=(0, 0.5), xytext=(1, 0), ha='left', va='center', rotation=90, **ann_kwargs) ax.annotate(starboard_string, xy=(1, 0.5), xytext=(-1, 0), ha='right', va='center', rotation=-90, **ann_kwargs) ax.set_title(f'origin: {origin}') for index in ['[0, 0]', "[0, N']", "[M', 0]", "[M', N']"]: (tx, ty, halign) = get_index_label_pos(index, extent, origin, inverted_xindex) facecolor = get_color(index, data, im.get_cmap()) ax.text(tx, ty, index, color='white', ha=halign, va='center', bbox={'boxstyle': 'square', 'facecolor': facecolor}) if xlim: ax.set_xlim(*xlim) if ylim: ax.set_ylim(*ylim) def generate_imshow_demo_grid(extents, xlim=None, ylim=None): N = len(extents) fig = plt.figure(tight_layout=True) fig.set_size_inches(6, N * 11.25 / 5) gs = GridSpec(N, 5, figure=fig) columns = {'label': [fig.add_subplot(gs[j, 0]) for j in range(N)], 'upper': [fig.add_subplot(gs[j, 1:3]) for j in range(N)], 'lower': [fig.add_subplot(gs[j, 3:5]) for j in range(N)]} (x, y) = np.ogrid[0:6, 0:7] data = x + y for origin in ['upper', 'lower']: for (ax, extent) in zip(columns[origin], extents): plot_imshow_with_labels(ax, data, extent, origin, xlim, ylim) columns['label'][0].set_title('extent=') for (ax, extent) in zip(columns['label'], extents): if extent is None: text = 'None' else: (left, right, bottom, top) = extent text = f'left: {left:0.1f}\nright: {right:0.1f}\nbottom: {bottom:0.1f}\ntop: {top:0.1f}\n' ax.text(1.0, 0.5, text, transform=ax.transAxes, ha='right', va='center') ax.axis('off') return columns generate_imshow_demo_grid(extents=[None]) extents = [(-0.5, 6.5, -0.5, 5.5), (-0.5, 6.5, 5.5, -0.5), (6.5, -0.5, -0.5, 5.5), (6.5, -0.5, 5.5, -0.5)] columns = generate_imshow_demo_grid(extents) set_extent_None_text(columns['upper'][1]) set_extent_None_text(columns['lower'][0]) generate_imshow_demo_grid(extents=[None] + extents, xlim=(-2, 8), ylim=(-1, 6)) plt.show() # File: matplotlib-main/galleries/users_explain/artists/patheffects_guide.py """""" import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects fig = plt.figure(figsize=(5, 1.5)) text = fig.text(0.5, 0.5, 'Hello path effects world!\nThis is the normal path effect.\nPretty dull, huh?', ha='center', va='center', size=20) text.set_path_effects([path_effects.Normal()]) plt.show() import matplotlib.patheffects as path_effects text = plt.text(0.5, 0.5, 'Hello path effects world!', path_effects=[path_effects.withSimplePatchShadow()]) plt.plot([0, 3, 2, 5], linewidth=5, color='blue', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.show() fig = plt.figure(figsize=(7, 1)) text = fig.text(0.5, 0.5, 'This text stands out because of\nits black border.', color='white', ha='center', va='center', size=30) text.set_path_effects([path_effects.Stroke(linewidth=3, foreground='black'), path_effects.Normal()]) plt.show() fig = plt.figure(figsize=(8.5, 1)) t = fig.text(0.02, 0.5, 'Hatch shadow', fontsize=75, weight=1000, va='center') t.set_path_effects([path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx', facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1, facecolor='black')]) plt.show() # File: matplotlib-main/galleries/users_explain/artists/paths.py """""" import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.path import Path verts = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] path = Path(verts, codes) (fig, ax) = plt.subplots() patch = patches.PathPatch(path, facecolor='orange', lw=2) ax.add_patch(patch) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) plt.show() verts = [(0.0, 0.0), (0.2, 1.0), (1.0, 0.8), (0.8, 0.0)] codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4] path = Path(verts, codes) (fig, ax) = plt.subplots() patch = patches.PathPatch(path, facecolor='none', lw=2) ax.add_patch(patch) (xs, ys) = zip(*verts) ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10) ax.text(-0.05, -0.05, 'P0') ax.text(0.15, 1.05, 'P1') ax.text(1.05, 0.85, 'P2') ax.text(0.85, -0.05, 'P3') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-0.1, 1.1) plt.show() (fig, ax) = plt.subplots() np.random.seed(19680801) data = np.random.randn(1000) (n, bins) = np.histogram(data, 100) left = np.array(bins[:-1]) right = np.array(bins[1:]) bottom = np.zeros(len(left)) top = bottom + n nrects = len(left) nverts = nrects * (1 + 3 + 1) verts = np.zeros((nverts, 2)) codes = np.full(nverts, Path.LINETO, dtype=int) codes[0::5] = Path.MOVETO codes[4::5] = Path.CLOSEPOLY verts[0::5, 0] = left verts[0::5, 1] = bottom verts[1::5, 0] = left verts[1::5, 1] = top verts[2::5, 0] = right verts[2::5, 1] = top verts[3::5, 0] = right verts[3::5, 1] = bottom barpath = Path(verts, codes) patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5) ax.add_patch(patch) ax.set_xlim(left[0], right[-1]) ax.set_ylim(bottom.min(), top.max()) plt.show() # File: matplotlib-main/galleries/users_explain/artists/transforms_tutorial.py """""" import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches x = np.arange(0, 10, 0.005) y = np.exp(-x / 2.0) * np.sin(2 * np.pi * x) (fig, ax) = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) plt.show() x = np.arange(0, 10, 0.005) y = np.exp(-x / 2.0) * np.sin(2 * np.pi * x) (fig, ax) = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) (xdata, ydata) = (5, 0) (xdisplay, ydisplay) = ax.transData.transform((xdata, ydata)) bbox = dict(boxstyle='round', fc='0.8') arrowprops = dict(arrowstyle='->', connectionstyle='angle,angleA=0,angleB=90,rad=10') offset = 72 ax.annotate(f'data = ({xdata:.1f}, {ydata:.1f})', (xdata, ydata), xytext=(-2 * offset, offset), textcoords='offset points', bbox=bbox, arrowprops=arrowprops) disp = ax.annotate(f'display = ({xdisplay:.1f}, {ydisplay:.1f})', (xdisplay, ydisplay), xytext=(0.5 * offset, -offset), xycoords='figure pixels', textcoords='offset points', bbox=bbox, arrowprops=arrowprops) plt.show() fig = plt.figure() for (i, label) in enumerate(('A', 'B', 'C', 'D')): ax = fig.add_subplot(2, 2, i + 1) ax.text(0.05, 0.95, label, transform=ax.transAxes, fontsize=16, fontweight='bold', va='top') plt.show() (fig, ax) = plt.subplots() (x, y) = 10 * np.random.rand(2, 1000) ax.plot(x, y, 'go', alpha=0.2) circ = mpatches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes, facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show() import matplotlib.transforms as transforms (fig, ax) = plt.subplots() x = np.random.randn(1000) ax.hist(x, 30) ax.set_title('$\\sigma=1 \\/ \\dots \\/ \\sigma=2$', fontsize=16) trans = transforms.blended_transform_factory(ax.transData, ax.transAxes) rect = mpatches.Rectangle((1, 0), width=1, height=1, transform=trans, color='yellow', alpha=0.5) ax.add_patch(rect) plt.show() (fig, ax) = plt.subplots(figsize=(5, 4)) (x, y) = 10 * np.random.rand(2, 1000) ax.plot(x, y * 10.0, 'go', alpha=0.2) circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans, facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show() (fig, ax) = plt.subplots(figsize=(7, 2)) (x, y) = 10 * np.random.rand(2, 1000) ax.plot(x, y * 10.0, 'go', alpha=0.2) circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans, facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show() (fig, ax) = plt.subplots() (xdata, ydata) = ((0.2, 0.7), (0.5, 0.5)) ax.plot(xdata, ydata, 'o') ax.set_xlim((0, 1)) trans = fig.dpi_scale_trans + transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData) circle = mpatches.Ellipse((0, 0), 150 / 72, 130 / 72, angle=40, fill=None, transform=trans) ax.add_patch(circle) plt.show() (fig, ax) = plt.subplots() x = np.arange(0.0, 2.0, 0.01) y = np.sin(2 * np.pi * x) (line,) = ax.plot(x, y, lw=3, color='blue') (dx, dy) = (2 / 72.0, -2 / 72.0) offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) shadow_transform = ax.transData + offset ax.plot(x, y, lw=3, color='gray', transform=shadow_transform, zorder=0.5 * line.get_zorder()) ax.set_title('creating a shadow effect with an offset transform') plt.show() # File: matplotlib-main/galleries/users_explain/axes/arranging_axes.py """""" import matplotlib.pyplot as plt import numpy as np (w, h) = (4, 3) margin = 0.5 fig = plt.figure(figsize=(w, h), facecolor='lightblue') ax = fig.add_axes([margin / w, margin / h, (w - 2 * margin) / w, (h - 2 * margin) / h]) (fig, axs) = plt.subplots(ncols=2, nrows=2, figsize=(5.5, 3.5), layout='constrained') for row in range(2): for col in range(2): axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5), transform=axs[row, col].transAxes, ha='center', va='center', fontsize=18, color='darkgrey') fig.suptitle('plt.subplots()') def annotate_axes(ax, text, fontsize=18): ax.text(0.5, 0.5, text, transform=ax.transAxes, ha='center', va='center', fontsize=fontsize, color='darkgrey') (fig, axd) = plt.subplot_mosaic([['upper left', 'upper right'], ['lower left', 'lower right']], figsize=(5.5, 3.5), layout='constrained') for (k, ax) in axd.items(): annotate_axes(ax, f'axd[{k!r}]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') (fig, axs) = plt.subplots(2, 2, layout='constrained', figsize=(5.5, 3.5), facecolor='lightblue') for ax in axs.flat: ax.set_aspect(1) fig.suptitle('Fixed aspect Axes') (fig, axs) = plt.subplots(2, 2, layout='compressed', figsize=(5.5, 3.5), facecolor='lightblue') for ax in axs.flat: ax.set_aspect(1) fig.suptitle('Fixed aspect Axes: compressed') (fig, axd) = plt.subplot_mosaic([['upper left', 'right'], ['lower left', 'right']], figsize=(5.5, 3.5), layout='constrained') for (k, ax) in axd.items(): annotate_axes(ax, f'axd[{k!r}]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') gs_kw = dict(width_ratios=[1.4, 1], height_ratios=[1, 2]) (fig, axd) = plt.subplot_mosaic([['upper left', 'right'], ['lower left', 'right']], gridspec_kw=gs_kw, figsize=(5.5, 3.5), layout='constrained') for (k, ax) in axd.items(): annotate_axes(ax, f'axd[{k!r}]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') fig = plt.figure(layout='constrained') subfigs = fig.subfigures(1, 2, wspace=0.07, width_ratios=[1.5, 1.0]) axs0 = subfigs[0].subplots(2, 2) subfigs[0].set_facecolor('lightblue') subfigs[0].suptitle('subfigs[0]\nLeft side') subfigs[0].supxlabel('xlabel for subfigs[0]') axs1 = subfigs[1].subplots(3, 1) subfigs[1].suptitle('subfigs[1]') subfigs[1].supylabel('ylabel for subfigs[1]') inner = [['innerA'], ['innerB']] outer = [['upper left', inner], ['lower left', 'lower right']] (fig, axd) = plt.subplot_mosaic(outer, layout='constrained') for (k, ax) in axd.items(): annotate_axes(ax, f'axd[{k!r}]') fig = plt.figure(figsize=(5.5, 3.5), layout='constrained') spec = fig.add_gridspec(ncols=2, nrows=2) ax0 = fig.add_subplot(spec[0, 0]) annotate_axes(ax0, 'ax0') ax1 = fig.add_subplot(spec[0, 1]) annotate_axes(ax1, 'ax1') ax2 = fig.add_subplot(spec[1, 0]) annotate_axes(ax2, 'ax2') ax3 = fig.add_subplot(spec[1, 1]) annotate_axes(ax3, 'ax3') fig.suptitle('Manually added subplots using add_gridspec') fig = plt.figure(figsize=(5.5, 3.5), layout='constrained') spec = fig.add_gridspec(2, 2) ax0 = fig.add_subplot(spec[0, :]) annotate_axes(ax0, 'ax0') ax10 = fig.add_subplot(spec[1, 0]) annotate_axes(ax10, 'ax10') ax11 = fig.add_subplot(spec[1, 1]) annotate_axes(ax11, 'ax11') fig.suptitle('Manually added subplots, spanning a column') fig = plt.figure(layout=None, facecolor='lightblue') gs = fig.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.75, hspace=0.1, wspace=0.05) ax0 = fig.add_subplot(gs[:-1, :]) annotate_axes(ax0, 'ax0') ax1 = fig.add_subplot(gs[-1, :-1]) annotate_axes(ax1, 'ax1') ax2 = fig.add_subplot(gs[-1, -1]) annotate_axes(ax2, 'ax2') fig.suptitle('Manual gridspec with right=0.75') fig = plt.figure(layout='constrained') gs0 = fig.add_gridspec(1, 2) gs00 = gs0[0].subgridspec(2, 2) gs01 = gs0[1].subgridspec(3, 1) for a in range(2): for b in range(2): ax = fig.add_subplot(gs00[a, b]) annotate_axes(ax, f'axLeft[{a}, {b}]', fontsize=10) if a == 1 and b == 1: ax.set_xlabel('xlabel') for a in range(3): ax = fig.add_subplot(gs01[a]) annotate_axes(ax, f'axRight[{a}, {b}]') if a == 2: ax.set_ylabel('ylabel') fig.suptitle('nested gridspecs') def squiggle_xy(a, b, c, d, i=np.arange(0.0, 2 * np.pi, 0.05)): return (np.sin(i * a) * np.cos(i * b), np.sin(i * c) * np.cos(i * d)) fig = plt.figure(figsize=(8, 8), layout='constrained') outer_grid = fig.add_gridspec(4, 4, wspace=0, hspace=0) for a in range(4): for b in range(4): inner_grid = outer_grid[a, b].subgridspec(3, 3, wspace=0, hspace=0) axs = inner_grid.subplots() for ((c, d), ax) in np.ndenumerate(axs): ax.plot(*squiggle_xy(a + 1, b + 1, c + 1, d + 1)) ax.set(xticks=[], yticks=[]) for ax in fig.get_axes(): ss = ax.get_subplotspec() ax.spines.top.set_visible(ss.is_first_row()) ax.spines.bottom.set_visible(ss.is_last_row()) ax.spines.left.set_visible(ss.is_first_col()) ax.spines.right.set_visible(ss.is_last_col()) plt.show() # File: matplotlib-main/galleries/users_explain/axes/autoscale.py """""" import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl x = np.linspace(-2 * np.pi, 2 * np.pi, 100) y = np.sinc(x) (fig, ax) = plt.subplots() ax.plot(x, y) print(ax.margins()) (fig, ax) = plt.subplots() ax.plot(x, y) ax.margins(0.2, 0.2) (fig, ax) = plt.subplots() ax.plot(x, y) ax.margins(y=-0.2) (xx, yy) = np.meshgrid(x, x) zz = np.sinc(np.sqrt((xx - 1) ** 2 + (yy - 1) ** 2)) (fig, ax) = plt.subplots(ncols=2, figsize=(12, 8)) ax[0].imshow(zz) ax[0].set_title('default margins') ax[1].imshow(zz) ax[1].margins(0.2) ax[1].set_title('margins(0.2)') (fig, ax) = plt.subplots(ncols=3, figsize=(16, 10)) ax[0].imshow(zz) ax[0].margins(0.2) ax[0].set_title('default use_sticky_edges\nmargins(0.2)') ax[1].imshow(zz) ax[1].margins(0.2) ax[1].use_sticky_edges = False ax[1].set_title('use_sticky_edges=False\nmargins(0.2)') ax[2].imshow(zz) ax[2].margins(-0.2) ax[2].set_title('default use_sticky_edges\nmargins(-0.2)') (fig, ax) = plt.subplots(ncols=2, figsize=(12, 8)) ax[0].plot(x, y) ax[0].set_title('Single curve') ax[1].plot(x, y) ax[1].plot(x * 2.0, y) ax[1].set_title('Two curves') (fig, ax) = plt.subplots(ncols=2, figsize=(12, 8)) ax[0].plot(x, y) ax[0].set_xlim(left=-1, right=1) ax[0].plot(x + np.pi * 0.5, y) ax[0].set_title('set_xlim(left=-1, right=1)\n') ax[1].plot(x, y) ax[1].set_xlim(left=-1, right=1) ax[1].plot(x + np.pi * 0.5, y) ax[1].autoscale() ax[1].set_title('set_xlim(left=-1, right=1)\nautoscale()') print(ax[0].get_autoscale_on()) print(ax[1].get_autoscale_on()) (fig, ax) = plt.subplots() ax.plot(x, y) ax.margins(0.2, 0.2) ax.autoscale(enable=None, axis='x', tight=True) print(ax.margins()) (fig, ax) = plt.subplots() collection = mpl.collections.StarPolygonCollection(5, rotation=0, sizes=(250,), offsets=np.column_stack([x, y]), offset_transform=ax.transData) ax.add_collection(collection) ax.autoscale_view() # File: matplotlib-main/galleries/users_explain/axes/axes_scales.py """""" import matplotlib.pyplot as plt import numpy as np import matplotlib.scale as mscale from matplotlib.ticker import FixedLocator, NullFormatter (fig, axs) = plt.subplot_mosaic([['linear', 'linear-log'], ['log-linear', 'log-log']], layout='constrained') x = np.arange(0, 3 * np.pi, 0.1) y = 2 * np.sin(x) + 3 ax = axs['linear'] ax.plot(x, y) ax.set_xlabel('linear') ax.set_ylabel('linear') ax = axs['linear-log'] ax.plot(x, y) ax.set_yscale('log') ax.set_xlabel('linear') ax.set_ylabel('log') ax = axs['log-linear'] ax.plot(x, y) ax.set_xscale('log') ax.set_xlabel('log') ax.set_ylabel('linear') ax = axs['log-log'] ax.plot(x, y) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('log') ax.set_ylabel('log') (fig, axs) = plt.subplot_mosaic([['linear', 'linear-log'], ['log-linear', 'log-log']], layout='constrained') x = np.arange(0, 3 * np.pi, 0.1) y = 2 * np.sin(x) + 3 ax = axs['linear'] ax.plot(x, y) ax.set_xlabel('linear') ax.set_ylabel('linear') ax.set_title('plot(x, y)') ax = axs['linear-log'] ax.semilogy(x, y) ax.set_xlabel('linear') ax.set_ylabel('log') ax.set_title('semilogy(x, y)') ax = axs['log-linear'] ax.semilogx(x, y) ax.set_xlabel('log') ax.set_ylabel('linear') ax.set_title('semilogx(x, y)') ax = axs['log-log'] ax.loglog(x, y) ax.set_xlabel('log') ax.set_ylabel('log') ax.set_title('loglog(x, y)') print(mscale.get_scale_names()) (fig, axs) = plt.subplot_mosaic([['asinh', 'symlog'], ['log', 'logit']], layout='constrained') x = np.arange(0, 1000) for (name, ax) in axs.items(): if name in ['asinh', 'symlog']: yy = x - np.mean(x) elif name in ['logit']: yy = x - np.min(x) yy = yy / np.max(np.abs(yy)) else: yy = x ax.plot(yy, yy) ax.set_yscale(name) ax.set_title(name) (fig, axs) = plt.subplot_mosaic([['log', 'symlog']], layout='constrained', figsize=(6.4, 3)) for (name, ax) in axs.items(): if name in ['log']: ax.plot(x, x) ax.set_yscale('log', base=2) ax.set_title('log base=2') else: ax.plot(x - np.mean(x), x - np.mean(x)) ax.set_yscale('symlog', linthresh=100) ax.set_title('symlog linthresh=100') def forward(a): a = np.deg2rad(a) return np.rad2deg(np.log(np.abs(np.tan(a) + 1.0 / np.cos(a)))) def inverse(a): a = np.deg2rad(a) return np.rad2deg(np.arctan(np.sinh(a))) t = np.arange(0, 170.0, 0.1) s = t / 2.0 (fig, ax) = plt.subplots(layout='constrained') ax.plot(t, s, '-', lw=2) ax.set_yscale('function', functions=(forward, inverse)) ax.set_title('function: Mercator') ax.grid(True) ax.set_xlim([0, 180]) ax.yaxis.set_minor_formatter(NullFormatter()) ax.yaxis.set_major_locator(FixedLocator(np.arange(0, 90, 10))) (fig, ax) = plt.subplots(layout='constrained', figsize=(3.2, 3)) ax.semilogy(x, x) print(ax.xaxis.get_scale()) print(ax.yaxis.get_scale()) print(ax.yaxis.get_transform()) print('X axis') print(ax.xaxis.get_major_locator()) print(ax.xaxis.get_major_formatter()) print('Y axis') print(ax.yaxis.get_major_locator()) print(ax.yaxis.get_major_formatter()) # File: matplotlib-main/galleries/users_explain/axes/axes_ticks.py """""" import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker (fig, axs) = plt.subplots(2, 1, figsize=(5.4, 5.4), layout='constrained') x = np.arange(100) for (nn, ax) in enumerate(axs): ax.plot(x, x) if nn == 1: ax.set_title('Manual ticks') ax.set_yticks(np.arange(0, 100.1, 100 / 3)) xticks = np.arange(0.5, 101, 20) xlabels = [f'\\${x:1.2f}' for x in xticks] ax.set_xticks(xticks, labels=xlabels) else: ax.set_title('Automatic ticks') (fig, axs) = plt.subplots(2, 1, figsize=(5.4, 5.4), layout='constrained') x = np.arange(100) for (nn, ax) in enumerate(axs): ax.plot(x, x) if nn == 1: ax.set_title('Manual ticks') ax.set_yticks(np.arange(0, 100.1, 100 / 3)) ax.set_yticks(np.arange(0, 100.1, 100 / 30), minor=True) else: ax.set_title('Automatic ticks') def setup(ax, title): ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[['left', 'right', 'top']].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.tick_params(which='major', width=1.0, length=5) ax.tick_params(which='minor', width=0.75, length=2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname='Monospace', color='tab:blue') (fig, axs) = plt.subplots(8, 1, layout='constrained') setup(axs[0], title='NullLocator()') axs[0].xaxis.set_major_locator(ticker.NullLocator()) axs[0].xaxis.set_minor_locator(ticker.NullLocator()) setup(axs[1], title='MultipleLocator(0.5)') axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5)) axs[1].xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) setup(axs[2], title='FixedLocator([0, 1, 5])') axs[2].xaxis.set_major_locator(ticker.FixedLocator([0, 1, 5])) axs[2].xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4))) setup(axs[3], title='LinearLocator(numticks=3)') axs[3].xaxis.set_major_locator(ticker.LinearLocator(3)) axs[3].xaxis.set_minor_locator(ticker.LinearLocator(31)) setup(axs[4], title='IndexLocator(base=0.5, offset=0.25)') axs[4].plot(range(0, 5), [0] * 5, color='white') axs[4].xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25)) setup(axs[5], title='AutoLocator()') axs[5].xaxis.set_major_locator(ticker.AutoLocator()) axs[5].xaxis.set_minor_locator(ticker.AutoMinorLocator()) setup(axs[6], title='MaxNLocator(n=4)') axs[6].xaxis.set_major_locator(ticker.MaxNLocator(4)) axs[6].xaxis.set_minor_locator(ticker.MaxNLocator(40)) setup(axs[7], title='LogLocator(base=10, numticks=15)') axs[7].set_xlim(10 ** 3, 10 ** 10) axs[7].set_xscale('log') axs[7].xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15)) plt.show() def setup(ax, title): ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[['left', 'right', 'top']].set_visible(False) ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25)) ax.xaxis.set_ticks_position('bottom') ax.tick_params(which='major', width=1.0, length=5) ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname='Monospace', color='tab:blue') fig = plt.figure(figsize=(8, 8), layout='constrained') (fig0, fig1, fig2) = fig.subfigures(3, height_ratios=[1.5, 1.5, 7.5]) fig0.suptitle('String Formatting', fontsize=16, x=0, ha='left') ax0 = fig0.subplots() setup(ax0, title="'{x} km'") ax0.xaxis.set_major_formatter('{x} km') fig1.suptitle('Function Formatting', fontsize=16, x=0, ha='left') ax1 = fig1.subplots() setup(ax1, title='def(x, pos): return str(x-5)') ax1.xaxis.set_major_formatter(lambda x, pos: str(x - 5)) fig2.suptitle('Formatter Object Formatting', fontsize=16, x=0, ha='left') axs2 = fig2.subplots(7, 1) setup(axs2[0], title='NullFormatter()') axs2[0].xaxis.set_major_formatter(ticker.NullFormatter()) setup(axs2[1], title="StrMethodFormatter('{x:.3f}')") axs2[1].xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:.3f}')) setup(axs2[2], title="FormatStrFormatter('#%d')") axs2[2].xaxis.set_major_formatter(ticker.FormatStrFormatter('#%d')) def fmt_two_digits(x, pos): return f'[{x:.2f}]' setup(axs2[3], title='FuncFormatter("[{:.2f}]".format)') axs2[3].xaxis.set_major_formatter(ticker.FuncFormatter(fmt_two_digits)) setup(axs2[4], title="FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])") positions = [0, 1, 2, 3, 4, 5] labels = ['A', 'B', 'C', 'D', 'E', 'F'] axs2[4].xaxis.set_major_locator(ticker.FixedLocator(positions)) axs2[4].xaxis.set_major_formatter(ticker.FixedFormatter(labels)) setup(axs2[5], title='ScalarFormatter()') axs2[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True)) setup(axs2[6], title='PercentFormatter(xmax=5)') axs2[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5)) (fig, axs) = plt.subplots(1, 2, figsize=(6.4, 3.2), layout='constrained') for (nn, ax) in enumerate(axs): ax.plot(np.arange(100)) if nn == 1: ax.grid('on') ax.tick_params(right=True, left=False, axis='y', color='r', length=16, grid_color='none') ax.tick_params(axis='x', color='m', length=4, direction='in', width=4, labelcolor='g', grid_color='b') # File: matplotlib-main/galleries/users_explain/axes/axes_units.py """""" import numpy as np import matplotlib.dates as mdates import matplotlib.units as munits import matplotlib.pyplot as plt (fig, ax) = plt.subplots(figsize=(5.4, 2), layout='constrained') time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]') x = np.arange(len(time)) ax.plot(time, x) (fig, ax) = plt.subplots(figsize=(5.4, 2), layout='constrained') time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]') x = np.arange(len(time)) ax.plot(time, x) ax.plot(0, 0, 'd') ax.text(0, 0, ' Float x=0', rotation=45) (fig, ax) = plt.subplots(figsize=(5.4, 2), layout='constrained') time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]') x = np.arange(len(time)) ax.plot(time, x) ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=np.arange(1, 13, 2))) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b')) ax.set_xlabel('1980') plt.rcParams['date.converter'] = 'concise' (fig, ax) = plt.subplots(figsize=(5.4, 2), layout='constrained') time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]') x = np.arange(len(time)) ax.plot(time, x) (fig, axs) = plt.subplots(2, 1, figsize=(5.4, 3), layout='constrained') for ax in axs.flat: time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]') x = np.arange(len(time)) ax.plot(time, x) axs[0].set_xlim(np.datetime64('1980-02-01'), np.datetime64('1980-04-01')) axs[1].set_xlim(3683, 3683 + 60) data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20} names = list(data.keys()) values = list(data.values()) (fig, axs) = plt.subplots(1, 3, figsize=(7, 3), sharey=True, layout='constrained') axs[0].bar(names, values) axs[1].scatter(names, values) axs[2].plot(names, values) fig.suptitle('Categorical Plotting') (fig, ax) = plt.subplots(figsize=(5, 3), layout='constrained') ax.bar(names, values) ax.scatter(['lemon', 'apple'], [7, 12]) ax.plot(['pear', 'orange', 'apple', 'lemon'], [13, 10, 7, 12], color='C1') (fig, ax) = plt.subplots(figsize=(5, 3), layout='constrained') ax.bar(names, values) args = {'rotation': 70, 'color': 'C1', 'bbox': {'color': 'white', 'alpha': 0.7, 'boxstyle': 'round'}} ax.plot(0, 2, 'd', color='C1') ax.text(0, 3, 'Float x=0', **args) ax.plot(2, 2, 'd', color='C1') ax.text(2, 3, 'Float x=2', **args) ax.plot(4, 2, 'd', color='C1') ax.text(4, 3, 'Float x=4', **args) ax.plot(2.5, 2, 'd', color='C1') ax.text(2.5, 3, 'Float x=2.5', **args) (fig, axs) = plt.subplots(2, 1, figsize=(5, 5), layout='constrained') ax = axs[0] ax.bar(names, values) ax.set_xlim('orange', 'lemon') ax.set_xlabel('limits set with categories') ax = axs[1] ax.bar(names, values) ax.set_xlim(0.5, 2.5) ax.set_xlabel('limits set with floats') (fig, ax) = plt.subplots(figsize=(5.4, 2.5), layout='constrained') x = [str(xx) for xx in np.arange(100)] ax.plot(x, np.arange(100)) ax.set_xlabel('x is list of strings') (fig, ax) = plt.subplots(figsize=(5.4, 2.5), layout='constrained') x = np.asarray(x, dtype='float') ax.plot(x, np.arange(100)) ax.set_xlabel('x is array of floats') (fig, axs) = plt.subplots(3, 1, figsize=(6.4, 7), layout='constrained') x = np.arange(100) ax = axs[0] ax.plot(x, x) label = f'Converter: {ax.xaxis.converter}\n ' label += f'Locator: {ax.xaxis.get_major_locator()}\n' label += f'Formatter: {ax.xaxis.get_major_formatter()}\n' ax.set_xlabel(label) ax = axs[1] time = np.arange('1980-01-01', '1980-06-25', dtype='datetime64[D]') x = np.arange(len(time)) ax.plot(time, x) label = f'Converter: {ax.xaxis.converter}\n ' label += f'Locator: {ax.xaxis.get_major_locator()}\n' label += f'Formatter: {ax.xaxis.get_major_formatter()}\n' ax.set_xlabel(label) ax = axs[2] data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20} names = list(data.keys()) values = list(data.values()) ax.plot(names, values) label = f'Converter: {ax.xaxis.converter}\n ' label += f'Locator: {ax.xaxis.get_major_locator()}\n' label += f'Formatter: {ax.xaxis.get_major_formatter()}\n' ax.set_xlabel(label) for (k, v) in munits.registry.items(): print(f'type: {k};\n converter: {type(v)}') # File: matplotlib-main/galleries/users_explain/axes/colorbar_placement.py """""" import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) (fig, axs) = plt.subplots(2, 2) cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) fig.colorbar(pcm, ax=ax) (fig, axs) = plt.subplots(2, 2) cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) fig.colorbar(pcm, ax=axs[:, col], shrink=0.6) (fig, axs) = plt.subplots(2, 1, figsize=(4, 5), sharex=True) X = np.random.randn(20, 20) axs[0].plot(np.sum(X, axis=0)) pcm = axs[1].pcolormesh(X) fig.colorbar(pcm, ax=axs[1], shrink=0.6) (fig, axs) = plt.subplots(2, 1, figsize=(4, 5), sharex=True, layout='constrained') axs[0].plot(np.sum(X, axis=0)) pcm = axs[1].pcolormesh(X) fig.colorbar(pcm, ax=axs[1], shrink=0.6) (fig, axs) = plt.subplots(3, 3, layout='constrained') for ax in axs.flat: pcm = ax.pcolormesh(np.random.random((20, 20))) fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom') fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom') fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6) fig.colorbar(pcm, ax=[axs[2, 1]], location='left') (fig, axs) = plt.subplots(3, 1, layout='constrained', figsize=(5, 5)) for (ax, pad) in zip(axs, [0.025, 0.05, 0.1]): pcm = ax.pcolormesh(np.random.randn(20, 20), cmap='viridis') fig.colorbar(pcm, ax=ax, pad=pad, label=f'pad: {pad}') fig.suptitle("layout='constrained'") (fig, axs) = plt.subplots(3, 1, figsize=(5, 5)) for (ax, pad) in zip(axs, [0.025, 0.05, 0.1]): pcm = ax.pcolormesh(np.random.randn(20, 20), cmap='viridis') fig.colorbar(pcm, ax=ax, pad=pad, label=f'pad: {pad}') fig.suptitle('No layout manager') (fig, ax) = plt.subplots(layout='constrained', figsize=(4, 4)) pcm = ax.pcolormesh(np.random.randn(20, 20), cmap='viridis') ax.set_ylim([-4, 20]) cax = ax.inset_axes([0.3, 0.07, 0.4, 0.04]) fig.colorbar(pcm, cax=cax, orientation='horizontal') (fig, ax) = plt.subplots(layout='constrained', figsize=(4, 4)) pcm = ax.pcolormesh(np.random.randn(20, 20), cmap='viridis') ax.set_ylim([-4, 20]) cax = ax.inset_axes([7.5, -1.7, 5, 1.2], transform=ax.transData) fig.colorbar(pcm, cax=cax, orientation='horizontal') (fig, axs) = plt.subplots(2, 2, layout='constrained') cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) if col == 0: ax.set_aspect(2) else: ax.set_aspect(1 / 2) if row == 1: fig.colorbar(pcm, ax=ax, shrink=0.6) (fig, axs) = plt.subplots(2, 2, layout='constrained') cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) if col == 0: ax.set_aspect(2) else: ax.set_aspect(1 / 2) if row == 1: cax = ax.inset_axes([1.04, 0.2, 0.05, 0.6]) fig.colorbar(pcm, cax=cax) # File: matplotlib-main/galleries/users_explain/axes/constrainedlayout_guide.py """""" import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors import matplotlib.gridspec as gridspec plt.rcParams['savefig.facecolor'] = '0.8' plt.rcParams['figure.figsize'] = (4.5, 4.0) plt.rcParams['figure.max_open_warning'] = 50 def example_plot(ax, fontsize=12, hide_labels=False): ax.plot([1, 2]) ax.locator_params(nbins=3) if hide_labels: ax.set_xticklabels([]) ax.set_yticklabels([]) else: ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) (fig, ax) = plt.subplots(layout=None) example_plot(ax, fontsize=24) (fig, ax) = plt.subplots(layout='constrained') example_plot(ax, fontsize=24) (fig, axs) = plt.subplots(2, 2, layout=None) for ax in axs.flat: example_plot(ax) (fig, axs) = plt.subplots(2, 2, layout='constrained') for ax in axs.flat: example_plot(ax) arr = np.arange(100).reshape((10, 10)) norm = mcolors.Normalize(vmin=0.0, vmax=100.0) pc_kwargs = {'rasterized': True, 'cmap': 'viridis', 'norm': norm} (fig, ax) = plt.subplots(figsize=(4, 4), layout='constrained') im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=ax, shrink=0.6) (fig, axs) = plt.subplots(2, 2, figsize=(4, 4), layout='constrained') for ax in axs.flat: im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=axs, shrink=0.6) (fig, axs) = plt.subplots(3, 3, figsize=(4, 4), layout='constrained') for ax in axs.flat: im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=axs[1:, 1], shrink=0.8) fig.colorbar(im, ax=axs[:, -1], shrink=0.6) (fig, axs) = plt.subplots(2, 2, figsize=(4, 4), layout='constrained') for ax in axs.flat: im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=axs, shrink=0.6) fig.suptitle('Big Suptitle') (fig, ax) = plt.subplots(layout='constrained') ax.plot(np.arange(10), label='This is a plot') ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) (fig, axs) = plt.subplots(1, 2, figsize=(4, 2), layout='constrained') axs[0].plot(np.arange(10)) axs[1].plot(np.arange(10), label='This is a plot') axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) (fig, axs) = plt.subplots(1, 2, figsize=(4, 2), layout='constrained') axs[0].plot(np.arange(10)) axs[1].plot(np.arange(10), label='This is a plot') leg = axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) leg.set_in_layout(False) fig.canvas.draw() leg.set_in_layout(True) fig.set_layout_engine('none') try: fig.savefig('../../../doc/_static/constrained_layout_1b.png', bbox_inches='tight', dpi=100) except FileNotFoundError: pass (fig, axs) = plt.subplots(1, 2, figsize=(4, 2), layout='constrained') axs[0].plot(np.arange(10)) lines = axs[1].plot(np.arange(10), label='This is a plot') labels = [l.get_label() for l in lines] leg = fig.legend(lines, labels, loc='center left', bbox_to_anchor=(0.8, 0.5), bbox_transform=axs[1].transAxes) try: fig.savefig('../../../doc/_static/constrained_layout_2b.png', bbox_inches='tight', dpi=100) except FileNotFoundError: pass (fig, axs) = plt.subplots(2, 2, layout='constrained') for ax in axs.flat: example_plot(ax, hide_labels=True) fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0, wspace=0) (fig, axs) = plt.subplots(2, 2, layout='constrained') for ax in axs.flat: example_plot(ax, hide_labels=True) fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2, wspace=0.2) (fig, axs) = plt.subplots(2, 3, layout='constrained') for ax in axs.flat: example_plot(ax, hide_labels=True) fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2, wspace=0.2) (fig, axs) = plt.subplots(2, 2, layout='constrained', gridspec_kw={'wspace': 0.3, 'hspace': 0.2}) for ax in axs.flat: example_plot(ax, hide_labels=True) fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.0, wspace=0.0) (fig, axs) = plt.subplots(2, 2, layout='constrained') pads = [0, 0.05, 0.1, 0.2] for (pad, ax) in zip(pads, axs.flat): pc = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(pc, ax=ax, shrink=0.6, pad=pad) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_title(f'pad: {pad}') fig.get_layout_engine().set(w_pad=2 / 72, h_pad=2 / 72, hspace=0.2, wspace=0.2) plt.rcParams['figure.constrained_layout.use'] = True (fig, axs) = plt.subplots(2, 2, figsize=(3, 3)) for ax in axs.flat: example_plot(ax) plt.rcParams['figure.constrained_layout.use'] = False fig = plt.figure(layout='constrained') gs1 = gridspec.GridSpec(2, 1, figure=fig) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) fig = plt.figure(layout='constrained') gs0 = fig.add_gridspec(1, 2) gs1 = gs0[0].subgridspec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs2 = gs0[1].subgridspec(3, 1) for ss in gs2: ax = fig.add_subplot(ss) example_plot(ax) ax.set_title('') ax.set_xlabel('') ax.set_xlabel('x-label', fontsize=12) fig = plt.figure(figsize=(4, 6), layout='constrained') gs0 = fig.add_gridspec(6, 2) ax1 = fig.add_subplot(gs0[:3, 0]) ax2 = fig.add_subplot(gs0[3:, 0]) example_plot(ax1) example_plot(ax2) ax = fig.add_subplot(gs0[0:2, 1]) example_plot(ax, hide_labels=True) ax = fig.add_subplot(gs0[2:4, 1]) example_plot(ax, hide_labels=True) ax = fig.add_subplot(gs0[4:, 1]) example_plot(ax, hide_labels=True) fig.suptitle('Overlapping Gridspecs') fig = plt.figure(layout='constrained') gs0 = fig.add_gridspec(1, 2, figure=fig, width_ratios=[1, 2]) gs_left = gs0[0].subgridspec(2, 1) gs_right = gs0[1].subgridspec(2, 2) for gs in gs_left: ax = fig.add_subplot(gs) example_plot(ax) axs = [] for gs in gs_right: ax = fig.add_subplot(gs) pcm = ax.pcolormesh(arr, **pc_kwargs) ax.set_xlabel('x-label') ax.set_ylabel('y-label') ax.set_title('title') axs += [ax] fig.suptitle('Nested plots using subgridspec') fig.colorbar(pcm, ax=axs) fig = plt.figure(layout='constrained') sfigs = fig.subfigures(1, 2, width_ratios=[1, 2]) axs_left = sfigs[0].subplots(2, 1) for ax in axs_left.flat: example_plot(ax) axs_right = sfigs[1].subplots(2, 2) for ax in axs_right.flat: pcm = ax.pcolormesh(arr, **pc_kwargs) ax.set_xlabel('x-label') ax.set_ylabel('y-label') ax.set_title('title') fig.colorbar(pcm, ax=axs_right) fig.suptitle('Nested plots using subfigures') (fig, axs) = plt.subplots(1, 2, layout='constrained') example_plot(axs[0], fontsize=12) axs[1].set_position([0.2, 0.2, 0.4, 0.4]) (fig, axs) = plt.subplots(2, 2, figsize=(5, 3), sharex=True, sharey=True, layout='constrained') for ax in axs.flat: ax.imshow(arr) fig.suptitle("fixed-aspect plots, layout='constrained'") (fig, axs) = plt.subplots(2, 2, figsize=(5, 3), sharex=True, sharey=True, layout='compressed') for ax in axs.flat: ax.imshow(arr) fig.suptitle("fixed-aspect plots, layout='compressed'") fig = plt.figure(layout='constrained') ax1 = plt.subplot(2, 2, 1) ax2 = plt.subplot(2, 2, 3) ax3 = plt.subplot(2, 2, (2, 4)) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.suptitle('Homogenous nrows, ncols') fig = plt.figure(layout='constrained') ax1 = plt.subplot(2, 2, 1) ax2 = plt.subplot(2, 2, 3) ax3 = plt.subplot(1, 2, 2) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.suptitle('Mixed nrows, ncols') fig = plt.figure(layout='constrained') ax1 = plt.subplot2grid((3, 3), (0, 0)) ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) fig.suptitle('subplot2grid') from matplotlib._layoutgrid import plot_children (fig, ax) = plt.subplots(layout='constrained') example_plot(ax, fontsize=24) plot_children(fig) (fig, ax) = plt.subplots(1, 2, layout='constrained') example_plot(ax[0], fontsize=32) example_plot(ax[1], fontsize=8) plot_children(fig) (fig, ax) = plt.subplots(1, 2, layout='constrained') im = ax[0].pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=ax[0], shrink=0.6) im = ax[1].pcolormesh(arr, **pc_kwargs) plot_children(fig) (fig, axs) = plt.subplots(2, 2, layout='constrained') for ax in axs.flat: im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=axs, shrink=0.6) plot_children(fig) fig = plt.figure(layout='constrained') gs = gridspec.GridSpec(2, 2, figure=fig) ax = fig.add_subplot(gs[:, 0]) im = ax.pcolormesh(arr, **pc_kwargs) ax = fig.add_subplot(gs[0, 1]) im = ax.pcolormesh(arr, **pc_kwargs) ax = fig.add_subplot(gs[1, 1]) im = ax.pcolormesh(arr, **pc_kwargs) plot_children(fig) fig = plt.figure(layout='constrained') gs = fig.add_gridspec(2, 4) ax00 = fig.add_subplot(gs[0, 0:2]) ax01 = fig.add_subplot(gs[0, 2:]) ax10 = fig.add_subplot(gs[1, 1:3]) example_plot(ax10, fontsize=14) plot_children(fig) plt.show() # File: matplotlib-main/galleries/users_explain/axes/legend_guide.py """""" import matplotlib.pyplot as plt import matplotlib.patches as mpatches (fig, ax) = plt.subplots() red_patch = mpatches.Patch(color='red', label='The red data') ax.legend(handles=[red_patch]) plt.show() import matplotlib.lines as mlines (fig, ax) = plt.subplots() blue_line = mlines.Line2D([], [], color='blue', marker='*', markersize=15, label='Blue stars') ax.legend(handles=[blue_line]) plt.show() (fig, ax_dict) = plt.subplot_mosaic([['top', 'top'], ['bottom', 'BLANK']], empty_sentinel='BLANK') ax_dict['top'].plot([1, 2, 3], label='test1') ax_dict['top'].plot([3, 2, 1], label='test2') ax_dict['top'].legend(bbox_to_anchor=(0.0, 1.02, 1.0, 0.102), loc='lower left', ncols=2, mode='expand', borderaxespad=0.0) ax_dict['bottom'].plot([1, 2, 3], label='test1') ax_dict['bottom'].plot([3, 2, 1], label='test2') ax_dict['bottom'].legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.0) (fig, axs) = plt.subplot_mosaic([['left', 'right']], layout='constrained') axs['left'].plot([1, 2, 3], label='test1') axs['left'].plot([3, 2, 1], label='test2') axs['right'].plot([1, 2, 3], 'C2', label='test3') axs['right'].plot([3, 2, 1], 'C3', label='test4') fig.legend(loc='outside upper right') ucl = ['upper', 'center', 'lower'] lcr = ['left', 'center', 'right'] (fig, ax) = plt.subplots(figsize=(6, 4), layout='constrained', facecolor='0.7') ax.plot([1, 2], [1, 2], label='TEST') for loc in ['outside upper left', 'outside upper center', 'outside upper right', 'outside lower left', 'outside lower center', 'outside lower right']: fig.legend(loc=loc, title=loc) (fig, ax) = plt.subplots(figsize=(6, 4), layout='constrained', facecolor='0.7') ax.plot([1, 2], [1, 2], label='test') for loc in ['outside left upper', 'outside right upper', 'outside left lower', 'outside right lower']: fig.legend(loc=loc, title=loc) (fig, ax) = plt.subplots() (line1,) = ax.plot([1, 2, 3], label='Line 1', linestyle='--') (line2,) = ax.plot([3, 2, 1], label='Line 2', linewidth=4) first_legend = ax.legend(handles=[line1], loc='upper right') ax.add_artist(first_legend) ax.legend(handles=[line2], loc='lower right') plt.show() from matplotlib.legend_handler import HandlerLine2D (fig, ax) = plt.subplots() (line1,) = ax.plot([3, 2, 1], marker='o', label='Line 1') (line2,) = ax.plot([1, 2, 3], marker='o', label='Line 2') ax.legend(handler_map={line1: HandlerLine2D(numpoints=4)}, handlelength=4) from numpy.random import randn z = randn(10) (fig, ax) = plt.subplots() (red_dot,) = ax.plot(z, 'ro', markersize=15) (white_cross,) = ax.plot(z[:5], 'w+', markeredgewidth=3, markersize=15) ax.legend([red_dot, (red_dot, white_cross)], ['Attr A', 'Attr A+B']) from matplotlib.legend_handler import HandlerLine2D, HandlerTuple (fig, ax) = plt.subplots() (p1,) = ax.plot([1, 2.5, 3], 'r-d') (p2,) = ax.plot([3, 2, 1], 'k-o') l = ax.legend([(p1, p2)], ['Two keys'], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}) import matplotlib.patches as mpatches class AnyObject: pass class AnyObjectHandler: def legend_artist(self, legend, orig_handle, fontsize, handlebox): (x0, y0) = (handlebox.xdescent, handlebox.ydescent) (width, height) = (handlebox.width, handlebox.height) patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red', edgecolor='black', hatch='xx', lw=3, transform=handlebox.get_transform()) handlebox.add_artist(patch) return patch (fig, ax) = plt.subplots() ax.legend([AnyObject()], ['My first handler'], handler_map={AnyObject: AnyObjectHandler()}) from matplotlib.legend_handler import HandlerPatch class HandlerEllipse(HandlerPatch): def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): center = (0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent) p = mpatches.Ellipse(xy=center, width=width + xdescent, height=height + ydescent) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p] c = mpatches.Circle((0.5, 0.5), 0.25, facecolor='green', edgecolor='red', linewidth=3) (fig, ax) = plt.subplots() ax.add_patch(c) ax.legend([c], ['An ellipse, not a rectangle'], handler_map={mpatches.Circle: HandlerEllipse()}) # File: matplotlib-main/galleries/users_explain/axes/mosaic.py """""" import matplotlib.pyplot as plt import numpy as np def identify_axes(ax_dict, fontsize=48): kw = dict(ha='center', va='center', fontsize=fontsize, color='darkgrey') for (k, ax) in ax_dict.items(): ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw) np.random.seed(19680801) hist_data = np.random.randn(1500) fig = plt.figure(layout='constrained') ax_array = fig.subplots(2, 2, squeeze=False) ax_array[0, 0].bar(['a', 'b', 'c'], [5, 7, 9]) ax_array[0, 1].plot([1, 2, 3]) ax_array[1, 0].hist(hist_data, bins='auto') ax_array[1, 1].imshow([[1, 2], [2, 1]]) identify_axes({(j, k): a for (j, r) in enumerate(ax_array) for (k, a) in enumerate(r)}) fig = plt.figure(layout='constrained') ax_dict = fig.subplot_mosaic([['bar', 'plot'], ['hist', 'image']]) ax_dict['bar'].bar(['a', 'b', 'c'], [5, 7, 9]) ax_dict['plot'].plot([1, 2, 3]) ax_dict['hist'].hist(hist_data) ax_dict['image'].imshow([[1, 2], [2, 1]]) identify_axes(ax_dict) print(ax_dict) mosaic = '\n AB\n CD\n ' fig = plt.figure(layout='constrained') ax_dict = fig.subplot_mosaic(mosaic) identify_axes(ax_dict) mosaic = 'AB;CD' fig = plt.figure(layout='constrained') ax_dict = fig.subplot_mosaic(mosaic) identify_axes(ax_dict) axd = plt.figure(layout='constrained').subplot_mosaic('\n ABD\n CCD\n ') identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic('\n A.C\n BBB\n .D.\n ') identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic('\n aX\n Xb\n ', empty_sentinel='X') identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic('αб\n ℝ☢') identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic('\n .a.\n bAc\n .d.\n ', height_ratios=[1, 3.5, 1], width_ratios=[1, 3.5, 1]) identify_axes(axd) mosaic = 'AA\n BC' fig = plt.figure() axd = fig.subplot_mosaic(mosaic, gridspec_kw={'bottom': 0.25, 'top': 0.95, 'left': 0.1, 'right': 0.5, 'wspace': 0.5, 'hspace': 0.5}) identify_axes(axd) axd = fig.subplot_mosaic(mosaic, gridspec_kw={'bottom': 0.05, 'top': 0.75, 'left': 0.6, 'right': 0.95, 'wspace': 0.5, 'hspace': 0.5}) identify_axes(axd) mosaic = 'AA\n BC' fig = plt.figure(layout='constrained') (left, right) = fig.subfigures(nrows=1, ncols=2) axd = left.subplot_mosaic(mosaic) identify_axes(axd) axd = right.subplot_mosaic(mosaic) identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic('AB', subplot_kw={'projection': 'polar'}) identify_axes(axd) (fig, axd) = plt.subplot_mosaic('AB;CD', per_subplot_kw={'A': {'projection': 'polar'}, ('C', 'D'): {'xscale': 'log'}}) identify_axes(axd) (fig, axd) = plt.subplot_mosaic('AB;CD', per_subplot_kw={'AD': {'projection': 'polar'}, 'BC': {'facecolor': '.9'}}) identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic('AB;CD', subplot_kw={'facecolor': 'xkcd:tangerine'}, per_subplot_kw={'B': {'facecolor': 'xkcd:water blue'}, 'D': {'projection': 'polar', 'facecolor': 'w'}}) identify_axes(axd) axd = plt.figure(layout='constrained').subplot_mosaic([['main', 'zoom'], ['main', 'BLANK']], empty_sentinel='BLANK', width_ratios=[2, 1]) identify_axes(axd) inner = [['inner A'], ['inner B']] outer_nested_mosaic = [['main', inner], ['bottom', 'bottom']] axd = plt.figure(layout='constrained').subplot_mosaic(outer_nested_mosaic, empty_sentinel=None) identify_axes(axd, fontsize=36) mosaic = np.zeros((4, 4), dtype=int) for j in range(4): mosaic[j, j] = j + 1 axd = plt.figure(layout='constrained').subplot_mosaic(mosaic, empty_sentinel=0) identify_axes(axd) # File: matplotlib-main/galleries/users_explain/axes/tight_layout_guide.py """""" import matplotlib.pyplot as plt import numpy as np plt.rcParams['savefig.facecolor'] = '0.8' def example_plot(ax, fontsize=12): ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) plt.close('all') (fig, ax) = plt.subplots() example_plot(ax, fontsize=24) (fig, ax) = plt.subplots() example_plot(ax, fontsize=24) plt.tight_layout() plt.close('all') (fig, ((ax1, ax2), (ax3, ax4))) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) (fig, ((ax1, ax2), (ax3, ax4))) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout() (fig, ((ax1, ax2), (ax3, ax4))) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) plt.close('all') fig = plt.figure() ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.tight_layout() plt.close('all') fig = plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0)) ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout() arr = np.arange(100).reshape((10, 10)) plt.close('all') fig = plt.figure(figsize=(5, 4)) ax = plt.subplot() im = ax.imshow(arr, interpolation='none') plt.tight_layout() import matplotlib.gridspec as gridspec plt.close('all') fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig) fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1.0]) (fig, ax) = plt.subplots(figsize=(4, 3)) lines = ax.plot(range(10), label='A simple plot') ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left') fig.tight_layout() plt.show() (fig, ax) = plt.subplots(figsize=(4, 3)) lines = ax.plot(range(10), label='B simple plot') leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left') leg.set_in_layout(False) fig.tight_layout() plt.show() from mpl_toolkits.axes_grid1 import Grid plt.close('all') fig = plt.figure() grid = Grid(fig, rect=111, nrows_ncols=(2, 2), axes_pad=0.25, label_mode='L') for ax in grid: example_plot(ax) ax.title.set_visible(False) plt.tight_layout() plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize=(4, 4)) im = plt.imshow(arr, interpolation='none') plt.colorbar(im) plt.tight_layout() from mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize=(4, 4)) im = plt.imshow(arr, interpolation='none') divider = make_axes_locatable(plt.gca()) cax = divider.append_axes('right', '5%', pad='3%') plt.colorbar(im, cax=cax) plt.tight_layout() # File: matplotlib-main/galleries/users_explain/colors/colorbar_only.py """""" import matplotlib.pyplot as plt import matplotlib as mpl (fig, ax) = plt.subplots(figsize=(6, 1), layout='constrained') cmap = mpl.cm.cool norm = mpl.colors.Normalize(vmin=5, vmax=10) fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation='horizontal', label='Some Units') (fig, ax) = plt.subplots(layout='constrained') fig.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.Normalize(0, 1), cmap='magma'), ax=ax, orientation='vertical', label='a colorbar label') (fig, ax) = plt.subplots(figsize=(6, 1), layout='constrained') cmap = mpl.cm.viridis bounds = [-1, 2, 5, 7, 12, 15] norm = mpl.colors.BoundaryNorm(bounds, cmap.N, extend='both') fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation='horizontal', label="Discrete intervals with extend='both' keyword") (fig, ax) = plt.subplots(figsize=(6, 1), layout='constrained') cmap = mpl.colors.ListedColormap(['red', 'green', 'blue', 'cyan']).with_extremes(under='yellow', over='magenta') bounds = [1, 2, 4, 7, 8] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm), cax=ax, orientation='horizontal', extend='both', spacing='proportional', label='Discrete intervals, some other units') (fig, ax) = plt.subplots(figsize=(6, 1), layout='constrained') cmap = mpl.colors.ListedColormap(['royalblue', 'cyan', 'yellow', 'orange']).with_extremes(over='red', under='blue') bounds = [-1.0, -0.5, 0.0, 0.5, 1.0] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm), cax=ax, orientation='horizontal', extend='both', extendfrac='auto', spacing='uniform', label='Custom extension lengths, some other units') plt.show() # File: matplotlib-main/galleries/users_explain/colors/colormap-manipulation.py """""" import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap, ListedColormap viridis = mpl.colormaps['viridis'].resampled(8) print(viridis(0.56)) print('viridis.colors', viridis.colors) print('viridis(range(8))', viridis(range(8))) print('viridis(np.linspace(0, 1, 8))', viridis(np.linspace(0, 1, 8))) print('viridis(np.linspace(0, 1, 12))', viridis(np.linspace(0, 1, 12))) copper = mpl.colormaps['copper'].resampled(8) print('copper(range(8))', copper(range(8))) print('copper(np.linspace(0, 1, 8))', copper(np.linspace(0, 1, 8))) def plot_examples(colormaps): np.random.seed(19680801) data = np.random.randn(30, 30) n = len(colormaps) (fig, axs) = plt.subplots(1, n, figsize=(n * 2 + 2, 3), layout='constrained', squeeze=False) for [ax, cmap] in zip(axs.flat, colormaps): psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4) fig.colorbar(psm, ax=ax) plt.show() cmap = ListedColormap(['darkorange', 'gold', 'lawngreen', 'lightseagreen']) plot_examples([cmap]) viridis = mpl.colormaps['viridis'].resampled(256) newcolors = viridis(np.linspace(0, 1, 256)) pink = np.array([248 / 256, 24 / 256, 148 / 256, 1]) newcolors[:25, :] = pink newcmp = ListedColormap(newcolors) plot_examples([viridis, newcmp]) viridis_big = mpl.colormaps['viridis'] newcmp = ListedColormap(viridis_big(np.linspace(0.25, 0.75, 128))) plot_examples([viridis, newcmp]) top = mpl.colormaps['Oranges_r'].resampled(128) bottom = mpl.colormaps['Blues'].resampled(128) newcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128)))) newcmp = ListedColormap(newcolors, name='OrangeBlue') plot_examples([viridis, newcmp]) N = 256 vals = np.ones((N, 4)) vals[:, 0] = np.linspace(90 / 256, 1, N) vals[:, 1] = np.linspace(40 / 256, 1, N) vals[:, 2] = np.linspace(40 / 256, 1, N) newcmp = ListedColormap(vals) plot_examples([viridis, newcmp]) cdict = {'red': [[0.0, 0.0, 0.0], [0.5, 1.0, 1.0], [1.0, 1.0, 1.0]], 'green': [[0.0, 0.0, 0.0], [0.25, 0.0, 0.0], [0.75, 1.0, 1.0], [1.0, 1.0, 1.0]], 'blue': [[0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [1.0, 1.0, 1.0]]} def plot_linearmap(cdict): newcmp = LinearSegmentedColormap('testCmap', segmentdata=cdict, N=256) rgba = newcmp(np.linspace(0, 1, 256)) (fig, ax) = plt.subplots(figsize=(4, 3), layout='constrained') col = ['r', 'g', 'b'] for xx in [0.25, 0.5, 0.75]: ax.axvline(xx, color='0.7', linestyle='--') for i in range(3): ax.plot(np.arange(256) / 256, rgba[:, i], color=col[i]) ax.set_xlabel('index') ax.set_ylabel('RGB') plt.show() plot_linearmap(cdict) cdict['red'] = [[0.0, 0.0, 0.3], [0.5, 1.0, 0.9], [1.0, 1.0, 1.0]] plot_linearmap(cdict) colors = ['darkorange', 'gold', 'lawngreen', 'lightseagreen'] cmap1 = LinearSegmentedColormap.from_list('mycmap', colors) nodes = [0.0, 0.4, 0.8, 1.0] cmap2 = LinearSegmentedColormap.from_list('mycmap', list(zip(nodes, colors))) plot_examples([cmap1, cmap2]) colors = ['#ffffcc', '#a1dab4', '#41b6c4', '#2c7fb8', '#253494'] my_cmap = ListedColormap(colors, name='my_cmap') my_cmap_r = my_cmap.reversed() plot_examples([my_cmap, my_cmap_r]) mpl.colormaps.register(cmap=my_cmap) mpl.colormaps.register(cmap=my_cmap_r) data = [[1, 2, 3, 4, 5]] (fig, (ax1, ax2)) = plt.subplots(nrows=2) ax1.imshow(data, cmap='my_cmap') ax2.imshow(data, cmap='my_cmap_r') plt.show() # File: matplotlib-main/galleries/users_explain/colors/colormapnorms.py """""" import matplotlib.pyplot as plt import numpy as np from matplotlib import cm import matplotlib.cbook as cbook import matplotlib.colors as colors N = 100 (X, Y) = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] Z1 = np.exp(-X ** 2 - Y ** 2) Z2 = np.exp(-(X * 10) ** 2 - (Y * 10) ** 2) Z = Z1 + 50 * Z2 (fig, ax) = plt.subplots(2, 1) pcm = ax[0].pcolor(X, Y, Z, norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r', shading='auto') fig.colorbar(pcm, ax=ax[0], extend='max') pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='auto') fig.colorbar(pcm, ax=ax[1], extend='max') plt.show() delta = 0.1 x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, delta) (X, Y) = np.meshgrid(x, y) Z1 = np.exp(-X ** 2 - Y ** 2) Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2) Z = (0.9 * Z1 - 0.5 * Z2) * 2 cmap = cm.coolwarm (fig, (ax1, ax2)) = plt.subplots(ncols=2) pc = ax1.pcolormesh(Z, cmap=cmap) fig.colorbar(pc, ax=ax1) ax1.set_title('Normalize()') pc = ax2.pcolormesh(Z, norm=colors.CenteredNorm(), cmap=cmap) fig.colorbar(pc, ax=ax2) ax2.set_title('CenteredNorm()') plt.show() N = 100 (X, Y) = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] Z1 = np.exp(-X ** 2 - Y ** 2) Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2) Z = (Z1 - Z2) * 2 (fig, ax) = plt.subplots(2, 1) pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03, vmin=-1.0, vmax=1.0, base=10), cmap='RdBu_r', shading='auto') fig.colorbar(pcm, ax=ax[0], extend='both') pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z), shading='auto') fig.colorbar(pcm, ax=ax[1], extend='both') plt.show() N = 100 (X, Y) = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)] Z1 = (1 + np.sin(Y * 10.0)) * X ** 2 (fig, ax) = plt.subplots(2, 1, layout='constrained') pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=0.5), cmap='PuBu_r', shading='auto') fig.colorbar(pcm, ax=ax[0], extend='max') ax[0].set_title('PowerNorm()') pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r', shading='auto') fig.colorbar(pcm, ax=ax[1], extend='max') ax[1].set_title('Normalize()') plt.show() N = 100 (X, Y) = np.meshgrid(np.linspace(-3, 3, N), np.linspace(-2, 2, N)) Z1 = np.exp(-X ** 2 - Y ** 2) Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2) Z = ((Z1 - Z2) * 2)[:-1, :-1] (fig, ax) = plt.subplots(2, 2, figsize=(8, 6), layout='constrained') ax = ax.flatten() pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[0], orientation='vertical') ax[0].set_title('Default norm') bounds = np.linspace(-1.5, 1.5, 7) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical') ax[1].set_title('BoundaryNorm: 7 boundaries') bounds = np.array([-0.2, -0.1, 0, 0.5, 1]) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256) pcm = ax[2].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical') ax[2].set_title('BoundaryNorm: nonuniform') bounds = np.linspace(-1.5, 1.5, 7) norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256, extend='both') pcm = ax[3].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r') fig.colorbar(pcm, ax=ax[3], orientation='vertical') ax[3].set_title('BoundaryNorm: extend="both"') plt.show() dem = cbook.get_sample_data('topobathy.npz') topo = dem['topo'] longitude = dem['longitude'] latitude = dem['latitude'] (fig, ax) = plt.subplots() colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 256)) colors_land = plt.cm.terrain(np.linspace(0.25, 1, 256)) all_colors = np.vstack((colors_undersea, colors_land)) terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map', all_colors) divnorm = colors.TwoSlopeNorm(vmin=-500.0, vcenter=0, vmax=4000) pcm = ax.pcolormesh(longitude, latitude, topo, rasterized=True, norm=divnorm, cmap=terrain_map, shading='auto') ax.set_aspect(1 / np.cos(np.deg2rad(49))) ax.set_title('TwoSlopeNorm(x)') cb = fig.colorbar(pcm, shrink=0.6) cb.set_ticks([-500, 0, 1000, 2000, 3000, 4000]) plt.show() def _forward(x): return np.sqrt(x) def _inverse(x): return x ** 2 N = 100 (X, Y) = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)] Z1 = (1 + np.sin(Y * 10.0)) * X ** 2 (fig, ax) = plt.subplots() norm = colors.FuncNorm((_forward, _inverse), vmin=0, vmax=20) pcm = ax.pcolormesh(X, Y, Z1, norm=norm, cmap='PuBu_r', shading='auto') ax.set_title('FuncNorm(x)') fig.colorbar(pcm, shrink=0.6) plt.show() class MidpointNormalize(colors.Normalize): def __init__(self, vmin=None, vmax=None, vcenter=None, clip=False): self.vcenter = vcenter super().__init__(vmin, vmax, clip) def __call__(self, value, clip=None): (x, y) = ([self.vmin, self.vcenter, self.vmax], [0, 0.5, 1.0]) return np.ma.masked_array(np.interp(value, x, y, left=-np.inf, right=np.inf)) def inverse(self, value): (y, x) = ([self.vmin, self.vcenter, self.vmax], [0, 0.5, 1]) return np.interp(value, x, y, left=-np.inf, right=np.inf) (fig, ax) = plt.subplots() midnorm = MidpointNormalize(vmin=-500.0, vcenter=0, vmax=4000) pcm = ax.pcolormesh(longitude, latitude, topo, rasterized=True, norm=midnorm, cmap=terrain_map, shading='auto') ax.set_aspect(1 / np.cos(np.deg2rad(49))) ax.set_title('Custom norm') cb = fig.colorbar(pcm, shrink=0.6, extend='both') cb.set_ticks([-500, 0, 1000, 2000, 3000, 4000]) plt.show() # File: matplotlib-main/galleries/users_explain/colors/colormaps.py """""" from colorspacious import cspace_converter import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl cmaps = {} gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(category, cmap_list): nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22 (fig, axs) = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh)) fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(f'{category} colormaps', fontsize=14) for (ax, name) in zip(axs, cmap_list): ax.imshow(gradient, aspect='auto', cmap=mpl.colormaps[name]) ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10, transform=ax.transAxes) for ax in axs: ax.set_axis_off() cmaps[category] = cmap_list plot_color_gradients('Perceptually Uniform Sequential', ['viridis', 'plasma', 'inferno', 'magma', 'cividis']) plot_color_gradients('Sequential', ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']) plot_color_gradients('Sequential (2)', ['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']) plot_color_gradients('Diverging', ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic', 'berlin', 'managua', 'vanimo']) plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv']) plot_color_gradients('Qualitative', ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']) plot_color_gradients('Miscellaneous', ['flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral', 'gist_ncar']) plt.show() mpl.rcParams.update({'font.size': 12}) _DSUBS = {'Perceptually Uniform Sequential': 5, 'Sequential': 6, 'Sequential (2)': 6, 'Diverging': 6, 'Cyclic': 3, 'Qualitative': 4, 'Miscellaneous': 6} _DC = {'Perceptually Uniform Sequential': 1.4, 'Sequential': 0.7, 'Sequential (2)': 1.4, 'Diverging': 1.4, 'Cyclic': 1.4, 'Qualitative': 1.4, 'Miscellaneous': 1.4} x = np.linspace(0.0, 1.0, 100) for (cmap_category, cmap_list) in cmaps.items(): dsub = _DSUBS.get(cmap_category, 6) nsubplots = int(np.ceil(len(cmap_list) / dsub)) (fig, axs) = plt.subplots(nrows=nsubplots, squeeze=False, figsize=(7, 2.6 * nsubplots)) for (i, ax) in enumerate(axs.flat): locs = [] for (j, cmap) in enumerate(cmap_list[i * dsub:(i + 1) * dsub]): rgb = mpl.colormaps[cmap](x)[np.newaxis, :, :3] lab = cspace_converter('sRGB1', 'CAM02-UCS')(rgb) if cmap_category == 'Sequential': y_ = lab[0, ::-1, 0] c_ = x[::-1] else: y_ = lab[0, :, 0] c_ = x dc = _DC.get(cmap_category, 1.4) ax.scatter(x + j * dc, y_, c=c_, cmap=cmap, s=300, linewidths=0.0) if cmap_category in ('Perceptually Uniform Sequential', 'Sequential'): locs.append(x[-1] + j * dc) elif cmap_category in ('Diverging', 'Qualitative', 'Cyclic', 'Miscellaneous', 'Sequential (2)'): locs.append(x[int(x.size / 2.0)] + j * dc) ax.set_xlim(axs[0, 0].get_xlim()) ax.set_ylim(0.0, 100.0) ax.xaxis.set_ticks_position('top') ticker = mpl.ticker.FixedLocator(locs) ax.xaxis.set_major_locator(ticker) formatter = mpl.ticker.FixedFormatter(cmap_list[i * dsub:(i + 1) * dsub]) ax.xaxis.set_major_formatter(formatter) ax.xaxis.set_tick_params(rotation=50) ax.set_ylabel('Lightness $L^*$', fontsize=12) ax.set_xlabel(cmap_category + ' colormaps', fontsize=14) fig.tight_layout(h_pad=0.0, pad=1.5) plt.show() mpl.rcParams.update({'font.size': 14}) x = np.linspace(0.0, 1.0, 100) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list): (fig, axs) = plt.subplots(nrows=len(cmap_list), ncols=2) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.05) fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6) for (ax, name) in zip(axs, cmap_list): rgb = mpl.colormaps[name](x)[np.newaxis, :, :3] lab = cspace_converter('sRGB1', 'CAM02-UCS')(rgb) L = lab[0, :, 0] L = np.float32(np.vstack((L, L, L))) ax[0].imshow(gradient, aspect='auto', cmap=mpl.colormaps[name]) ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0.0, vmax=100.0) pos = list(ax[0].get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3] / 2.0 fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10) for ax in axs.flat: ax.set_axis_off() plt.show() for (cmap_category, cmap_list) in cmaps.items(): plot_color_gradients(cmap_category, cmap_list) # File: matplotlib-main/galleries/users_explain/colors/colors.py """""" import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle (fig, ax) = plt.subplots(figsize=(6.5, 1.65), layout='constrained') ax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8)) for (i, alpha) in enumerate(np.linspace(0, 1, 11)): ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0)) ax.text(i + 0.4, 0.85, f'{alpha:.1f}', ha='center') ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2)) ax.set_xlim(-0.2, 13) ax.set_ylim(-1, 1) ax.set_title('alpha values') ax.text(11.3, 0.6, 'zorder=1', va='center', color='C0') ax.text(11.3, 0, 'zorder=2\nalpha=0.8', va='center', color='C1') ax.text(11.3, -0.6, 'zorder=3', va='center', color='C0') ax.axis('off') import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl th = np.linspace(0, 2 * np.pi, 128) def demo(sty): mpl.style.use(sty) (fig, ax) = plt.subplots(figsize=(3, 3)) ax.set_title(f'style: {sty!r}', color='C0') ax.plot(th, np.cos(th), 'C1', label='C1') ax.plot(th, np.sin(th), 'C2', label='C2') ax.legend() demo('default') demo('seaborn-v0_8') import matplotlib.colors as mcolors import matplotlib.patches as mpatch overlap = {name for name in mcolors.CSS4_COLORS if f'xkcd:{name}' in mcolors.XKCD_COLORS} fig = plt.figure(figsize=[9, 5]) ax = fig.add_axes([0, 0, 1, 1]) n_groups = 3 n_rows = len(overlap) // n_groups + 1 for (j, color_name) in enumerate(sorted(overlap)): css4 = mcolors.CSS4_COLORS[color_name] xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper() rgba = mcolors.to_rgba_array([css4, xkcd]) luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2] css4_text_color = 'k' if luma[0] > 0.5 else 'w' xkcd_text_color = 'k' if luma[1] > 0.5 else 'w' col_shift = j // n_rows * 3 y_pos = j % n_rows text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None) ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4)) ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd)) ax.text(0.5 + col_shift, y_pos + 0.7, css4, color=css4_text_color, ha='center', **text_args) ax.text(1.5 + col_shift, y_pos + 0.7, xkcd, color=xkcd_text_color, ha='center', **text_args) ax.text(2 + col_shift, y_pos + 0.7, f' {color_name}', **text_args) for g in range(n_groups): ax.hlines(range(n_rows), 3 * g, 3 * g + 2.8, color='0.7', linewidth=1) ax.text(0.5 + 3 * g, -0.3, 'X11/CSS4', ha='center') ax.text(1.5 + 3 * g, -0.3, 'xkcd', ha='center') ax.set_xlim(0, 3 * n_groups) ax.set_ylim(n_rows, -1) ax.axis('off') plt.show() # File: matplotlib-main/galleries/users_explain/customizing.py """""" from cycler import cycler import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl mpl.rcParams['lines.linewidth'] = 2 mpl.rcParams['lines.linestyle'] = '--' data = np.random.randn(50) plt.plot(data) mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y']) plt.plot(data) mpl.rc('lines', linewidth=4, linestyle='-.') plt.plot(data) with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}): plt.plot(data) @mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'}) def plotting_function(): plt.plot(data) plotting_function() plt.style.use('ggplot') print(plt.style.available) with plt.style.context('dark_background'): plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o') plt.show() # File: matplotlib-main/galleries/users_explain/quick_start.py """""" import matplotlib.pyplot as plt import numpy as np (fig, ax) = plt.subplots() ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) plt.show() np.random.seed(19680801) data = {'a': np.arange(50), 'c': np.random.randint(0, 50, 50), 'd': np.random.randn(50)} data['b'] = data['a'] + 10 * np.random.randn(50) data['d'] = np.abs(data['d']) * 100 (fig, ax) = plt.subplots(figsize=(5, 2.7), layout='constrained') ax.scatter('a', 'b', c='c', s='d', data=data) ax.set_xlabel('entry a') ax.set_ylabel('entry b') x = np.linspace(0, 2, 100) (fig, ax) = plt.subplots(figsize=(5, 2.7), layout='constrained') ax.plot(x, x, label='linear') ax.plot(x, x ** 2, label='quadratic') ax.plot(x, x ** 3, label='cubic') ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_title('Simple Plot') ax.legend() x = np.linspace(0, 2, 100) plt.figure(figsize=(5, 2.7), layout='constrained') plt.plot(x, x, label='linear') plt.plot(x, x ** 2, label='quadratic') plt.plot(x, x ** 3, label='cubic') plt.xlabel('x label') plt.ylabel('y label') plt.title('Simple Plot') plt.legend() def my_plotter(ax, data1, data2, param_dict): out = ax.plot(data1, data2, **param_dict) return out (data1, data2, data3, data4) = np.random.randn(4, 100) (fig, (ax1, ax2)) = plt.subplots(1, 2, figsize=(5, 2.7)) my_plotter(ax1, data1, data2, {'marker': 'x'}) my_plotter(ax2, data3, data4, {'marker': 'o'}) (fig, ax) = plt.subplots(figsize=(5, 2.7)) x = np.arange(len(data1)) ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--') (l,) = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2) l.set_linestyle(':') (fig, ax) = plt.subplots(figsize=(5, 2.7)) ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k') (fig, ax) = plt.subplots(figsize=(5, 2.7)) ax.plot(data1, 'o', label='data1') ax.plot(data2, 'd', label='data2') ax.plot(data3, 'v', label='data3') ax.plot(data4, 's', label='data4') ax.legend() (mu, sigma) = (115, 15) x = mu + sigma * np.random.randn(10000) (fig, ax) = plt.subplots(figsize=(5, 2.7), layout='constrained') (n, bins, patches) = ax.hist(x, 50, density=True, facecolor='C0', alpha=0.75) ax.set_xlabel('Length [cm]') ax.set_ylabel('Probability') ax.set_title('Aardvark lengths\n (not really)') ax.text(75, 0.025, '$\\mu=115,\\ \\sigma=15$') ax.axis([55, 175, 0, 0.03]) ax.grid(True) (fig, ax) = plt.subplots(figsize=(5, 2.7)) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2 * np.pi * t) (line,) = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05)) ax.set_ylim(-2, 2) (fig, ax) = plt.subplots(figsize=(5, 2.7)) ax.plot(np.arange(len(data1)), data1, label='data1') ax.plot(np.arange(len(data2)), data2, label='data2') ax.plot(np.arange(len(data3)), data3, 'd', label='data3') ax.legend() (fig, axs) = plt.subplots(1, 2, figsize=(5, 2.7), layout='constrained') xdata = np.arange(len(data1)) data = 10 ** data1 axs[0].plot(xdata, data) axs[1].set_yscale('log') axs[1].plot(xdata, data) (fig, axs) = plt.subplots(2, 1, layout='constrained') axs[0].plot(xdata, data1) axs[0].set_title('Automatic ticks') axs[1].plot(xdata, data1) axs[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90']) axs[1].set_yticks([-1.5, 0, 1.5]) axs[1].set_title('Manual ticks') from matplotlib.dates import ConciseDateFormatter (fig, ax) = plt.subplots(figsize=(5, 2.7), layout='constrained') dates = np.arange(np.datetime64('2021-11-15'), np.datetime64('2021-12-25'), np.timedelta64(1, 'h')) data = np.cumsum(np.random.randn(len(dates))) ax.plot(dates, data) ax.xaxis.set_major_formatter(ConciseDateFormatter(ax.xaxis.get_major_locator())) (fig, ax) = plt.subplots(figsize=(5, 2.7), layout='constrained') categories = ['turnips', 'rutabaga', 'cucumber', 'pumpkins'] ax.bar(categories, np.random.rand(len(categories))) (fig, (ax1, ax3)) = plt.subplots(1, 2, figsize=(7, 2.7), layout='constrained') (l1,) = ax1.plot(t, s) ax2 = ax1.twinx() (l2,) = ax2.plot(t, range(len(t)), 'C1') ax2.legend([l1, l2], ['Sine (left)', 'Straight (right)']) ax3.plot(t, s) ax3.set_xlabel('Angle [rad]') ax4 = ax3.secondary_xaxis('top', (np.rad2deg, np.deg2rad)) ax4.set_xlabel('Angle [°]') from matplotlib.colors import LogNorm (X, Y) = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128)) Z = (1 - X / 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) (fig, axs) = plt.subplots(2, 2, layout='constrained') pc = axs[0, 0].pcolormesh(X, Y, Z, vmin=-1, vmax=1, cmap='RdBu_r') fig.colorbar(pc, ax=axs[0, 0]) axs[0, 0].set_title('pcolormesh()') co = axs[0, 1].contourf(X, Y, Z, levels=np.linspace(-1.25, 1.25, 11)) fig.colorbar(co, ax=axs[0, 1]) axs[0, 1].set_title('contourf()') pc = axs[1, 0].imshow(Z ** 2 * 100, cmap='plasma', norm=LogNorm(vmin=0.01, vmax=100)) fig.colorbar(pc, ax=axs[1, 0], extend='both') axs[1, 0].set_title('imshow() with LogNorm()') pc = axs[1, 1].scatter(data1, data2, c=data3, cmap='RdBu_r') fig.colorbar(pc, ax=axs[1, 1], extend='both') axs[1, 1].set_title('scatter()') (fig, axd) = plt.subplot_mosaic([['upleft', 'right'], ['lowleft', 'right']], layout='constrained') axd['upleft'].set_title('upleft') axd['lowleft'].set_title('lowleft') axd['right'].set_title('right') # File: matplotlib-main/galleries/users_explain/text/annotations.py """""" import matplotlib.pyplot as plt import numpy as np (fig, ax) = plt.subplots(figsize=(3, 3)) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2 * np.pi * t) (line,) = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05)) ax.set_ylim(-2, 2) (fig, ax) = plt.subplots(figsize=(3, 3)) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2 * np.pi * t) (line,) = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xycoords='data', xytext=(0.01, 0.99), textcoords='axes fraction', va='top', ha='left', arrowprops=dict(facecolor='black', shrink=0.05)) ax.set_ylim(-2, 2) import matplotlib.patches as mpatches (fig, ax) = plt.subplots(figsize=(3, 3)) arr = mpatches.FancyArrowPatch((1.25, 1.5), (1.75, 1.5), arrowstyle='->,head_width=.15', mutation_scale=20) ax.add_patch(arr) ax.annotate('label', (0.5, 0.5), xycoords=arr, ha='center', va='bottom') ax.set(xlim=(1, 2), ylim=(1, 2)) fig = plt.figure() ax = fig.add_subplot(projection='polar') r = np.arange(0, 1, 0.001) theta = 2 * 2 * np.pi * r (line,) = ax.plot(theta, r, color='#ee8d18', lw=3) ind = 800 (thisr, thistheta) = (r[ind], theta[ind]) ax.plot([thistheta], [thisr], 'o') ax.annotate('a polar annotation', xy=(thistheta, thisr), xytext=(0.05, 0.05), textcoords='figure fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='bottom') (fig, ax) = plt.subplots(figsize=(3, 3)) x = [1, 3, 5, 7, 9] y = [2, 4, 6, 8, 10] annotations = ['A', 'B', 'C', 'D', 'E'] ax.scatter(x, y, s=20) for (xi, yi, text) in zip(x, y, annotations): ax.annotate(text, xy=(xi, yi), xycoords='data', xytext=(1.5, 1.5), textcoords='offset points') (fig, ax) = plt.subplots(figsize=(5, 5)) t = ax.text(0.5, 0.5, 'Direction', ha='center', va='center', rotation=45, size=15, bbox=dict(boxstyle='rarrow,pad=0.3', fc='lightblue', ec='steelblue', lw=2)) from matplotlib.path import Path def custom_box_style(x0, y0, width, height, mutation_size): mypad = 0.3 pad = mutation_size * mypad width = width + 2 * pad height = height + 2 * pad (x0, y0) = (x0 - pad, y0 - pad) (x1, y1) = (x0 + width, y0 + height) return Path([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0 - pad, (y0 + y1) / 2), (x0, y0), (x0, y0)], closed=True) (fig, ax) = plt.subplots(figsize=(3, 3)) ax.text(0.5, 0.5, 'Test', size=30, va='center', ha='center', rotation=30, bbox=dict(boxstyle=custom_box_style, alpha=0.2)) from matplotlib.patches import BoxStyle class MyStyle: def __init__(self, pad=0.3): self.pad = pad super().__init__() def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad width = width + 2 * pad height = height + 2 * pad (x0, y0) = (x0 - pad, y0 - pad) (x1, y1) = (x0 + width, y0 + height) return Path([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0 - pad, (y0 + y1) / 2), (x0, y0), (x0, y0)], closed=True) BoxStyle._style_list['angled'] = MyStyle (fig, ax) = plt.subplots(figsize=(3, 3)) ax.text(0.5, 0.5, 'Test', size=30, va='center', ha='center', rotation=30, bbox=dict(boxstyle='angled,pad=0.5', alpha=0.2)) del BoxStyle._style_list['angled'] (fig, ax) = plt.subplots(figsize=(3, 3)) ax.annotate('', xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', arrowprops=dict(arrowstyle='->', connectionstyle='arc3')) (fig, ax) = plt.subplots(figsize=(3, 3)) ax.annotate('Test', xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', size=20, va='center', ha='center', arrowprops=dict(arrowstyle='simple', connectionstyle='arc3,rad=-0.2')) (fig, ax) = plt.subplots(figsize=(3, 3)) ann = ax.annotate('Test', xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', size=20, va='center', ha='center', bbox=dict(boxstyle='round4', fc='w'), arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3,rad=-0.2', fc='w')) (fig, ax) = plt.subplots(figsize=(3, 3)) ann = ax.annotate('Test', xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', size=20, va='center', ha='center', bbox=dict(boxstyle='round4', fc='w'), arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3,rad=0.2', relpos=(0.0, 0.0), fc='w')) ann = ax.annotate('Test', xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', size=20, va='center', ha='center', bbox=dict(boxstyle='round4', fc='w'), arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3,rad=-0.2', relpos=(1.0, 0.0), fc='w')) from matplotlib.offsetbox import AnchoredText (fig, ax) = plt.subplots(figsize=(3, 3)) at = AnchoredText('Figure 1a', prop=dict(size=15), frameon=True, loc='upper left') at.patch.set_boxstyle('round,pad=0.,rounding_size=0.2') ax.add_artist(at) from matplotlib.patches import Circle from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea (fig, ax) = plt.subplots(figsize=(3, 3)) ada = AnchoredDrawingArea(40, 20, 0, 0, loc='upper right', pad=0.0, frameon=False) p1 = Circle((10, 10), 10) ada.drawing_area.add_artist(p1) p2 = Circle((30, 10), 5, fc='r') ada.drawing_area.add_artist(p2) ax.add_artist(ada) from matplotlib.patches import Ellipse from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox (fig, ax) = plt.subplots(figsize=(3, 3)) box = AnchoredAuxTransformBox(ax.transData, loc='upper left') el = Ellipse((0, 0), width=0.1, height=0.4, angle=30) box.drawing_area.add_artist(el) ax.add_artist(box) from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea, HPacker, TextArea (fig, ax) = plt.subplots(figsize=(3, 3)) box1 = TextArea(' Test: ', textprops=dict(color='k')) box2 = DrawingArea(60, 20, 0, 0) el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc='r') el2 = Ellipse((30, 10), width=16, height=5, angle=170, fc='g') el3 = Ellipse((50, 10), width=16, height=5, angle=230, fc='b') box2.add_artist(el1) box2.add_artist(el2) box2.add_artist(el3) box = HPacker(children=[box1, box2], align='center', pad=0, sep=5) anchored_box = AnchoredOffsetbox(loc='lower left', child=box, pad=0.0, frameon=True, bbox_to_anchor=(0.0, 1.02), bbox_transform=ax.transAxes, borderpad=0.0) ax.add_artist(anchored_box) fig.subplots_adjust(top=0.8) (fig, (ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) ax1.annotate('Test', xy=(0.2, 0.2), xycoords=ax1.transAxes) ax2.annotate('Test', xy=(0.2, 0.2), xycoords='axes fraction') x = np.linspace(-1, 1) (fig, (ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) ax1.plot(x, -x ** 3) ax2.plot(x, -3 * x ** 2) ax2.annotate('', xy=(0, 0), xycoords=ax1.transData, xytext=(0, 0), textcoords=ax2.transData, arrowprops=dict(arrowstyle='<->')) (fig, ax) = plt.subplots(nrows=1, ncols=1, figsize=(3, 3)) an1 = ax.annotate('Test 1', xy=(0.5, 0.5), xycoords='data', va='center', ha='center', bbox=dict(boxstyle='round', fc='w')) an2 = ax.annotate('Test 2', xy=(1, 0.5), xycoords=an1, xytext=(30, 0), textcoords='offset points', va='center', ha='left', bbox=dict(boxstyle='round', fc='w'), arrowprops=dict(arrowstyle='->')) (fig, ax) = plt.subplots(nrows=1, ncols=1, figsize=(3, 3)) an1 = ax.annotate('Test 1', xy=(0.5, 0.5), xycoords='data', va='center', ha='center', bbox=dict(boxstyle='round', fc='w')) an2 = ax.annotate('Test 2', xy=(1, 0.5), xycoords=an1.get_window_extent, xytext=(30, 0), textcoords='offset points', va='center', ha='left', bbox=dict(boxstyle='round', fc='w'), arrowprops=dict(arrowstyle='->')) (fig, (ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) an1 = ax1.annotate('Test1', xy=(0.5, 0.5), xycoords='axes fraction') an2 = ax2.annotate('Test 2', xy=(0.5, 0.5), xycoords=ax2.get_window_extent) (fig, ax) = plt.subplots(figsize=(3, 3)) ax.annotate('Test', xy=(0.5, 1), xycoords=('data', 'axes fraction')) ax.axvline(x=0.5, color='lightgray') ax.set(xlim=(0, 2), ylim=(1, 2)) (fig, ax) = plt.subplots(figsize=(3, 3)) t1 = ax.text(0.05, 0.05, 'Text 1', va='bottom', ha='left') t2 = ax.text(0.9, 0.9, 'Text 2', ha='right') t3 = ax.annotate('Anchored to 1 & 2', xy=(0, 0), xycoords=(t1, t2), va='bottom', color='tab:orange') from matplotlib.text import OffsetFrom (fig, ax) = plt.subplots(figsize=(3, 3)) an1 = ax.annotate('Test 1', xy=(0.5, 0.5), xycoords='data', va='center', ha='center', bbox=dict(boxstyle='round', fc='w')) offset_from = OffsetFrom(an1, (0.5, 0)) an2 = ax.annotate('Test 2', xy=(0.1, 0.1), xycoords='data', xytext=(0, -10), textcoords=offset_from, va='top', ha='center', bbox=dict(boxstyle='round', fc='w'), arrowprops=dict(arrowstyle='->')) from matplotlib.patches import ConnectionPatch (fig, (ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3)) xy = (0.3, 0.2) con = ConnectionPatch(xyA=xy, coordsA=ax1.transData, xyB=xy, coordsB=ax2.transData) fig.add_artist(con) # File: matplotlib-main/galleries/users_explain/text/fonts.py """""" # File: matplotlib-main/galleries/users_explain/text/mathtext.py """""" import matplotlib.pyplot as plt fig = plt.figure(figsize=(3, 3), linewidth=1, edgecolor='black') fig.text(0.2, 0.7, 'plain text: alpha > beta') fig.text(0.2, 0.5, 'Mathtext: $\\alpha > \\beta$') fig.text(0.2, 0.3, 'raw string Mathtext: $\\alpha > \\beta$') fig = plt.figure(figsize=(3, 3), linewidth=1, edgecolor='black') fig.suptitle('Number of unescaped $') fig.text(0.1, 0.7, 'odd: $ \\alpha $ = $1') fig.text(0.1, 0.5, 'even: $ \\beta $= $ 2 $') fig.text(0.1, 0.3, 'odd: $ \\gamma $= \\$3 $') fig.text(0.1, 0.1, 'even: $ \\delta $ = $ \\$4 $') # File: matplotlib-main/galleries/users_explain/text/pgf.py """""" # File: matplotlib-main/galleries/users_explain/text/text_intro.py """""" import matplotlib.pyplot as plt import matplotlib fig = plt.figure() ax = fig.add_subplot() fig.subplots_adjust(top=0.85) fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold') ax.set_title('axes title') ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') ax.axis([0, 10, 0, 10]) ax.text(3, 8, 'boxed italics text in data coords', style='italic', bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10}) ax.text(2, 6, 'an equation: $E=mc^2$', fontsize=15) ax.text(3, 2, 'Unicode: Institut für Festkörperphysik') ax.text(0.95, 0.01, 'colored text in axes coords', verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=15) ax.plot([2], [1], 'o') ax.annotate('annotate', xy=(2, 1), xytext=(3, 4), arrowprops=dict(facecolor='black', shrink=0.05)) plt.show() import matplotlib.pyplot as plt import numpy as np x1 = np.linspace(0.0, 5.0, 100) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('Time [s]') ax.set_ylabel('Damped oscillation [V]') plt.show() (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1 * 10000) ax.set_xlabel('Time [s]') ax.set_ylabel('Damped oscillation [V]') plt.show() (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1 * 10000) ax.set_xlabel('Time [s]') ax.set_ylabel('Damped oscillation [V]', labelpad=18) plt.show() (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('Time [s]', position=(0.0, 1000000.0), horizontalalignment='left') ax.set_ylabel('Damped oscillation [V]') plt.show() from matplotlib.font_manager import FontProperties font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_style('italic') (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('Time [s]', fontsize='large', fontweight='bold') ax.set_ylabel('Damped oscillation [V]', fontproperties=font) plt.show() (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.2, left=0.2) ax.plot(x1, np.cumsum(y1 ** 2)) ax.set_xlabel('Time [s] \n This was a long experiment') ax.set_ylabel('$\\int\\ Y^2\\ dt\\ \\ [V^2 s]$') plt.show() (fig, axs) = plt.subplots(3, 1, figsize=(5, 6), tight_layout=True) locs = ['center', 'left', 'right'] for (ax, loc) in zip(axs, locs): ax.plot(x1, y1) ax.set_title('Title with loc at ' + loc, loc=loc) plt.show() (fig, ax) = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(top=0.8) ax.plot(x1, y1) ax.set_title('Vertically offset title', pad=30) plt.show() (fig, axs) = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) axs[1].xaxis.set_ticks(np.arange(0.0, 8.1, 2.0)) plt.show() (fig, axs) = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) ticks = np.arange(0.0, 8.1, 2.0) tickla = [f'{tick:1.2f}' for tick in ticks] axs[1].xaxis.set_ticks(ticks) axs[1].xaxis.set_ticklabels(tickla) axs[1].set_xlim(axs[0].get_xlim()) plt.show() (fig, axs) = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) ticks = np.arange(0.0, 8.1, 2.0) axs[1].xaxis.set_ticks(ticks) axs[1].xaxis.set_major_formatter('{x:1.1f}') axs[1].set_xlim(axs[0].get_xlim()) plt.show() (fig, axs) = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) locator = matplotlib.ticker.FixedLocator(ticks) axs[1].xaxis.set_major_locator(locator) axs[1].xaxis.set_major_formatter('±{x}°') plt.show() (fig, axs) = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True) for (n, ax) in enumerate(axs.flat): ax.plot(x1 * 10.0, y1) formatter = matplotlib.ticker.FormatStrFormatter('%1.1f') locator = matplotlib.ticker.MaxNLocator(nbins='auto', steps=[1, 4, 10]) axs[0, 1].xaxis.set_major_locator(locator) axs[0, 1].xaxis.set_major_formatter(formatter) formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') locator = matplotlib.ticker.AutoLocator() axs[1, 0].xaxis.set_major_formatter(formatter) axs[1, 0].xaxis.set_major_locator(locator) formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') locator = matplotlib.ticker.MaxNLocator(nbins=4) axs[1, 1].xaxis.set_major_formatter(formatter) axs[1, 1].xaxis.set_major_locator(locator) plt.show() def formatoddticks(x, pos): if x % 2: return f'{x:1.2f}' else: return '' (fig, ax) = plt.subplots(figsize=(5, 3), tight_layout=True) ax.plot(x1, y1) locator = matplotlib.ticker.MaxNLocator(nbins=6) ax.xaxis.set_major_formatter(formatoddticks) ax.xaxis.set_major_locator(locator) plt.show() import datetime (fig, ax) = plt.subplots(figsize=(5, 3), tight_layout=True) base = datetime.datetime(2017, 1, 1, 0, 0, 1) time = [base + datetime.timedelta(days=x) for x in range(len(x1))] ax.plot(time, y1) ax.tick_params(axis='x', rotation=70) plt.show() import matplotlib.dates as mdates locator = mdates.DayLocator(bymonthday=[1, 15]) formatter = mdates.DateFormatter('%b %d') (fig, ax) = plt.subplots(figsize=(5, 3), tight_layout=True) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) ax.plot(time, y1) ax.tick_params(axis='x', rotation=70) plt.show() # File: matplotlib-main/galleries/users_explain/text/text_props.py """""" import matplotlib.pyplot as plt import matplotlib.patches as patches (left, width) = (0.25, 0.5) (bottom, height) = (0.25, 0.5) right = left + width top = bottom + height fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) p = patches.Rectangle((left, bottom), width, height, fill=False, transform=ax.transAxes, clip_on=False) ax.add_patch(p) ax.text(left, bottom, 'left top', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes) ax.text(left, bottom, 'left bottom', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes) ax.text(right, top, 'right bottom', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes) ax.text(right, top, 'right top', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes) ax.text(right, bottom, 'center top', horizontalalignment='center', verticalalignment='top', transform=ax.transAxes) ax.text(left, 0.5 * (bottom + top), 'right center', horizontalalignment='right', verticalalignment='center', rotation='vertical', transform=ax.transAxes) ax.text(left, 0.5 * (bottom + top), 'left center', horizontalalignment='left', verticalalignment='center', rotation='vertical', transform=ax.transAxes) ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle', horizontalalignment='center', verticalalignment='center', fontsize=20, color='red', transform=ax.transAxes) ax.text(right, 0.5 * (bottom + top), 'centered', horizontalalignment='center', verticalalignment='center', rotation='vertical', transform=ax.transAxes) ax.text(left, top, 'rotated\nwith newlines', horizontalalignment='center', verticalalignment='center', rotation=45, transform=ax.transAxes) ax.set_axis_off() plt.show() # File: matplotlib-main/galleries/users_explain/text/usetex.py """""" # File: matplotlib-main/lib/matplotlib/__init__.py """""" __all__ = ['__bibtex__', '__version__', '__version_info__', 'set_loglevel', 'ExecutableNotFoundError', 'get_configdir', 'get_cachedir', 'get_data_path', 'matplotlib_fname', 'MatplotlibDeprecationWarning', 'RcParams', 'rc_params', 'rc_params_from_file', 'rcParamsDefault', 'rcParams', 'rcParamsOrig', 'defaultParams', 'rc', 'rcdefaults', 'rc_file_defaults', 'rc_file', 'rc_context', 'use', 'get_backend', 'interactive', 'is_interactive', 'colormaps', 'multivar_colormaps', 'bivar_colormaps', 'color_sequences'] import atexit from collections import namedtuple from collections.abc import MutableMapping import contextlib import functools import importlib import inspect from inspect import Parameter import locale import logging import os from pathlib import Path import pprint import re import shutil import subprocess import sys import tempfile from packaging.version import parse as parse_version from . import _api, _version, cbook, _docstring, rcsetup from matplotlib._api import MatplotlibDeprecationWarning from matplotlib.rcsetup import cycler _log = logging.getLogger(__name__) __bibtex__ = '@Article{Hunter:2007,\n Author = {Hunter, J. D.},\n Title = {Matplotlib: A 2D graphics environment},\n Journal = {Computing in Science \\& Engineering},\n Volume = {9},\n Number = {3},\n Pages = {90--95},\n abstract = {Matplotlib is a 2D graphics package used for Python\n for application development, interactive scripting, and\n publication-quality image generation across user\n interfaces and operating systems.},\n publisher = {IEEE COMPUTER SOC},\n year = 2007\n}' _VersionInfo = namedtuple('_VersionInfo', 'major, minor, micro, releaselevel, serial') def _parse_to_version_info(version_str): v = parse_version(version_str) if v.pre is None and v.post is None and (v.dev is None): return _VersionInfo(v.major, v.minor, v.micro, 'final', 0) elif v.dev is not None: return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev) elif v.pre is not None: releaselevel = {'a': 'alpha', 'b': 'beta', 'rc': 'candidate'}.get(v.pre[0], 'alpha') return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1]) else: return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post) def _get_version(): root = Path(__file__).resolve().parents[2] if (root / '.matplotlib-repo').exists() and (root / '.git').exists() and (not (root / '.git/shallow').exists()): try: import setuptools_scm except ImportError: pass else: return setuptools_scm.get_version(root=root, dist_name='matplotlib', version_scheme='release-branch-semver', local_scheme='node-and-date', fallback_version=_version.version) return _version.version @_api.caching_module_getattr class __getattr__: __version__ = property(lambda self: _get_version()) __version_info__ = property(lambda self: _parse_to_version_info(self.__version__)) def _check_versions(): from . import ft2font for (modname, minver) in [('cycler', '0.10'), ('dateutil', '2.7'), ('kiwisolver', '1.3.1'), ('numpy', '1.23'), ('pyparsing', '2.3.1')]: module = importlib.import_module(modname) if parse_version(module.__version__) < parse_version(minver): raise ImportError(f'Matplotlib requires {modname}>={minver}; you have {module.__version__}') _check_versions() @functools.cache def _ensure_handler(): handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) _log.addHandler(handler) return handler def set_loglevel(level): _log.setLevel(level.upper()) _ensure_handler().setLevel(level.upper()) def _logged_cached(fmt, func=None): if func is None: return functools.partial(_logged_cached, fmt) called = False ret = None @functools.wraps(func) def wrapper(**kwargs): nonlocal called, ret if not called: ret = func(**kwargs) called = True _log.debug(fmt, ret) return ret return wrapper _ExecInfo = namedtuple('_ExecInfo', 'executable raw_version version') class ExecutableNotFoundError(FileNotFoundError): pass @functools.cache def _get_executable_info(name): def impl(args, regex, min_ver=None, ignore_exit_code=False): try: output = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True, errors='replace') except subprocess.CalledProcessError as _cpe: if ignore_exit_code: output = _cpe.output else: raise ExecutableNotFoundError(str(_cpe)) from _cpe except OSError as _ose: raise ExecutableNotFoundError(str(_ose)) from _ose match = re.search(regex, output) if match: raw_version = match.group(1) version = parse_version(raw_version) if min_ver is not None and version < parse_version(min_ver): raise ExecutableNotFoundError(f'You have {args[0]} version {version} but the minimum version supported by Matplotlib is {min_ver}') return _ExecInfo(args[0], raw_version, version) else: raise ExecutableNotFoundError(f"Failed to determine the version of {args[0]} from {' '.join(args)}, which output {output}") if name in os.environ.get('_MPLHIDEEXECUTABLES', '').split(','): raise ExecutableNotFoundError(f'{name} was hidden') if name == 'dvipng': return impl(['dvipng', '-version'], '(?m)^dvipng(?: .*)? (.+)', '1.6') elif name == 'gs': execs = ['gswin32c', 'gswin64c', 'mgs', 'gs'] if sys.platform == 'win32' else ['gs'] for e in execs: try: return impl([e, '--version'], '(.*)', '9') except ExecutableNotFoundError: pass message = 'Failed to find a Ghostscript installation' raise ExecutableNotFoundError(message) elif name == 'inkscape': try: return impl(['inkscape', '--without-gui', '-V'], 'Inkscape ([^ ]*)') except ExecutableNotFoundError: pass return impl(['inkscape', '-V'], 'Inkscape ([^ ]*)') elif name == 'magick': if sys.platform == 'win32': import winreg binpath = '' for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]: try: with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, 'Software\\Imagemagick\\Current', 0, winreg.KEY_QUERY_VALUE | flag) as hkey: binpath = winreg.QueryValueEx(hkey, 'BinPath')[0] except OSError: pass path = None if binpath: for name in ['convert.exe', 'magick.exe']: candidate = Path(binpath, name) if candidate.exists(): path = str(candidate) break if path is None: raise ExecutableNotFoundError('Failed to find an ImageMagick installation') else: path = 'convert' info = impl([path, '--version'], '^Version: ImageMagick (\\S*)') if info.raw_version == '7.0.10-34': raise ExecutableNotFoundError(f'You have ImageMagick {info.version}, which is unsupported') return info elif name == 'pdftocairo': return impl(['pdftocairo', '-v'], 'pdftocairo version (.*)') elif name == 'pdftops': info = impl(['pdftops', '-v'], '^pdftops version (.*)', ignore_exit_code=True) if info and (not (3 <= info.version.major or parse_version('0.9') <= info.version < parse_version('1.0'))): raise ExecutableNotFoundError(f'You have pdftops version {info.version} but the minimum version supported by Matplotlib is 3.0') return info else: raise ValueError(f'Unknown executable: {name!r}') def _get_xdg_config_dir(): return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / '.config') def _get_xdg_cache_dir(): return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / '.cache') def _get_config_or_cache_dir(xdg_base_getter): configdir = os.environ.get('MPLCONFIGDIR') if configdir: configdir = Path(configdir).resolve() elif sys.platform.startswith(('linux', 'freebsd')): configdir = Path(xdg_base_getter(), 'matplotlib') else: configdir = Path.home() / '.matplotlib' try: configdir.mkdir(parents=True, exist_ok=True) except OSError: pass else: if os.access(str(configdir), os.W_OK) and configdir.is_dir(): return str(configdir) try: tmpdir = tempfile.mkdtemp(prefix='matplotlib-') except OSError as exc: raise OSError(f'Matplotlib requires access to a writable cache directory, but the default path ({configdir}) is not a writable directory, and a temporary directory could not be created; set the MPLCONFIGDIR environment variable to a writable directory') from exc os.environ['MPLCONFIGDIR'] = tmpdir atexit.register(shutil.rmtree, tmpdir) _log.warning('Matplotlib created a temporary cache directory at %s because the default path (%s) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.', tmpdir, configdir) return tmpdir @_logged_cached('CONFIGDIR=%s') def get_configdir(): return _get_config_or_cache_dir(_get_xdg_config_dir) @_logged_cached('CACHEDIR=%s') def get_cachedir(): return _get_config_or_cache_dir(_get_xdg_cache_dir) @_logged_cached('matplotlib data path: %s') def get_data_path(): return str(Path(__file__).with_name('mpl-data')) def matplotlib_fname(): def gen_candidates(): yield 'matplotlibrc' try: matplotlibrc = os.environ['MATPLOTLIBRC'] except KeyError: pass else: yield matplotlibrc yield os.path.join(matplotlibrc, 'matplotlibrc') yield os.path.join(get_configdir(), 'matplotlibrc') yield os.path.join(get_data_path(), 'matplotlibrc') for fname in gen_candidates(): if os.path.exists(fname) and (not os.path.isdir(fname)): return fname raise RuntimeError('Could not find matplotlibrc file; your Matplotlib install is broken') _deprecated_map = {} _deprecated_ignore_map = {} _deprecated_remain_as_none = {} @_docstring.Substitution('\n'.join(map('- {}'.format, sorted(rcsetup._validators, key=str.lower)))) class RcParams(MutableMapping, dict): validate = rcsetup._validators def __init__(self, *args, **kwargs): self.update(*args, **kwargs) def _set(self, key, val): dict.__setitem__(self, key, val) def _get(self, key): return dict.__getitem__(self, key) def _update_raw(self, other_params): if isinstance(other_params, RcParams): other_params = dict.items(other_params) dict.update(self, other_params) def _ensure_has_backend(self): dict.setdefault(self, 'backend', rcsetup._auto_backend_sentinel) def __setitem__(self, key, val): try: if key in _deprecated_map: (version, alt_key, alt_val, inverse_alt) = _deprecated_map[key] _api.warn_deprecated(version, name=key, obj_type='rcparam', alternative=alt_key) key = alt_key val = alt_val(val) elif key in _deprecated_remain_as_none and val is not None: (version,) = _deprecated_remain_as_none[key] _api.warn_deprecated(version, name=key, obj_type='rcparam') elif key in _deprecated_ignore_map: (version, alt_key) = _deprecated_ignore_map[key] _api.warn_deprecated(version, name=key, obj_type='rcparam', alternative=alt_key) return elif key == 'backend': if val is rcsetup._auto_backend_sentinel: if 'backend' in self: return try: cval = self.validate[key](val) except ValueError as ve: raise ValueError(f'Key {key}: {ve}') from None self._set(key, cval) except KeyError as err: raise KeyError(f'{key} is not a valid rc parameter (see rcParams.keys() for a list of valid parameters)') from err def __getitem__(self, key): if key in _deprecated_map: (version, alt_key, alt_val, inverse_alt) = _deprecated_map[key] _api.warn_deprecated(version, name=key, obj_type='rcparam', alternative=alt_key) return inverse_alt(self._get(alt_key)) elif key in _deprecated_ignore_map: (version, alt_key) = _deprecated_ignore_map[key] _api.warn_deprecated(version, name=key, obj_type='rcparam', alternative=alt_key) return self._get(alt_key) if alt_key else None elif key == 'backend' and self is globals().get('rcParams'): val = self._get(key) if val is rcsetup._auto_backend_sentinel: from matplotlib import pyplot as plt plt.switch_backend(rcsetup._auto_backend_sentinel) return self._get(key) def _get_backend_or_none(self): backend = self._get('backend') return None if backend is rcsetup._auto_backend_sentinel else backend def __repr__(self): class_name = self.__class__.__name__ indent = len(class_name) + 1 with _api.suppress_matplotlib_deprecation_warning(): repr_split = pprint.pformat(dict(self), indent=1, width=80 - indent).split('\n') repr_indented = ('\n' + ' ' * indent).join(repr_split) return f'{class_name}({repr_indented})' def __str__(self): return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items()))) def __iter__(self): with _api.suppress_matplotlib_deprecation_warning(): yield from sorted(dict.__iter__(self)) def __len__(self): return dict.__len__(self) def find_all(self, pattern): pattern_re = re.compile(pattern) return RcParams(((key, value) for (key, value) in self.items() if pattern_re.search(key))) def copy(self): rccopy = RcParams() for k in self: rccopy._set(k, self._get(k)) return rccopy def rc_params(fail_on_error=False): return rc_params_from_file(matplotlib_fname(), fail_on_error) @functools.cache def _get_ssl_context(): try: import certifi except ImportError: _log.debug('Could not import certifi.') return None import ssl return ssl.create_default_context(cafile=certifi.where()) @contextlib.contextmanager def _open_file_or_url(fname): if isinstance(fname, str) and fname.startswith(('http://', 'https://', 'ftp://', 'file:')): import urllib.request ssl_ctx = _get_ssl_context() if ssl_ctx is None: _log.debug('Could not get certifi ssl context, https may not work.') with urllib.request.urlopen(fname, context=ssl_ctx) as f: yield (line.decode('utf-8') for line in f) else: fname = os.path.expanduser(fname) with open(fname, encoding='utf-8') as f: yield f def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): import matplotlib as mpl rc_temp = {} with _open_file_or_url(fname) as fd: try: for (line_no, line) in enumerate(fd, 1): line = transform(line) strippedline = cbook._strip_comment(line) if not strippedline: continue tup = strippedline.split(':', 1) if len(tup) != 2: _log.warning('Missing colon in file %r, line %d (%r)', fname, line_no, line.rstrip('\n')) continue (key, val) = tup key = key.strip() val = val.strip() if val.startswith('"') and val.endswith('"'): val = val[1:-1] if key in rc_temp: _log.warning('Duplicate key in file %r, line %d (%r)', fname, line_no, line.rstrip('\n')) rc_temp[key] = (val, line, line_no) except UnicodeDecodeError: _log.warning('Cannot decode configuration file %r as utf-8.', fname) raise config = RcParams() for (key, (val, line, line_no)) in rc_temp.items(): if key in rcsetup._validators: if fail_on_error: config[key] = val else: try: config[key] = val except Exception as msg: _log.warning('Bad value in file %r, line %d (%r): %s', fname, line_no, line.rstrip('\n'), msg) elif key in _deprecated_ignore_map: (version, alt_key) = _deprecated_ignore_map[key] _api.warn_deprecated(version, name=key, alternative=alt_key, obj_type='rcparam', addendum='Please update your matplotlibrc.') else: version = 'main' if '.post' in mpl.__version__ else f'v{mpl.__version__}' _log.warning('\nBad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)\nYou probably need to get an updated matplotlibrc file from\nhttps://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc\nor from the matplotlib source distribution', dict(key=key, fname=fname, line_no=line_no, line=line.rstrip('\n'), version=version)) return config def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error) if not use_default_template: return config_from_file with _api.suppress_matplotlib_deprecation_warning(): config = RcParams({**rcParamsDefault, **config_from_file}) if ''.join(config['text.latex.preamble']): _log.info('\n*****************************************************************\nYou have the following UNSUPPORTED LaTeX preamble customizations:\n%s\nPlease do not ask for support with these customizations active.\n*****************************************************************\n', '\n'.join(config['text.latex.preamble'])) _log.debug('loaded rc file %s', fname) return config rcParamsDefault = _rc_params_in_file(cbook._get_data_path('matplotlibrc'), transform=lambda line: line[1:] if line.startswith('#') else line, fail_on_error=True) rcParamsDefault._update_raw(rcsetup._hardcoded_defaults) rcParamsDefault._ensure_has_backend() rcParams = RcParams() rcParams._update_raw(rcParamsDefault) rcParams._update_raw(_rc_params_in_file(matplotlib_fname())) rcParamsOrig = rcParams.copy() with _api.suppress_matplotlib_deprecation_warning(): defaultParams = rcsetup.defaultParams = {key: [rcsetup._auto_backend_sentinel if key == 'backend' else rcParamsDefault[key], validator] for (key, validator) in rcsetup._validators.items()} if rcParams['axes.formatter.use_locale']: locale.setlocale(locale.LC_ALL, '') def rc(group, **kwargs): aliases = {'lw': 'linewidth', 'ls': 'linestyle', 'c': 'color', 'fc': 'facecolor', 'ec': 'edgecolor', 'mew': 'markeredgewidth', 'aa': 'antialiased'} if isinstance(group, str): group = (group,) for g in group: for (k, v) in kwargs.items(): name = aliases.get(k) or k key = f'{g}.{name}' try: rcParams[key] = v except KeyError as err: raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, g, name)) from err def rcdefaults(): with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.clear() rcParams.update({k: v for (k, v) in rcParamsDefault.items() if k not in STYLE_BLACKLIST}) def rc_file_defaults(): with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig if k not in STYLE_BLACKLIST}) def rc_file(fname, *, use_default_template=True): with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rc_from_file = rc_params_from_file(fname, use_default_template=use_default_template) rcParams.update({k: rc_from_file[k] for k in rc_from_file if k not in STYLE_BLACKLIST}) @contextlib.contextmanager def rc_context(rc=None, fname=None): orig = dict(rcParams.copy()) del orig['backend'] try: if fname: rc_file(fname) if rc: rcParams.update(rc) yield finally: rcParams._update_raw(orig) def use(backend, *, force=True): name = rcsetup.validate_backend(backend) if rcParams._get_backend_or_none() == name: pass else: plt = sys.modules.get('matplotlib.pyplot') if plt is not None: try: plt.switch_backend(name) except ImportError: if force: raise else: rcParams['backend'] = backend rcParams['backend_fallback'] = False if os.environ.get('MPLBACKEND'): rcParams['backend'] = os.environ.get('MPLBACKEND') def get_backend(): return rcParams['backend'] def interactive(b): rcParams['interactive'] = b def is_interactive(): return rcParams['interactive'] def _val_or_rc(val, rc_name): return val if val is not None else rcParams[rc_name] def _init_tests(): LOCAL_FREETYPE_VERSION = '2.6.1' from matplotlib import ft2font if ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or ft2font.__freetype_build_type__ != 'local': _log.warning('Matplotlib is not built with the correct FreeType version to run tests. Rebuild without setting system-freetype=true in Meson setup options. Expect many image comparison failures below. Expected freetype version %s. Found freetype version %s. Freetype build type is %slocal.', LOCAL_FREETYPE_VERSION, ft2font.__freetype_version__, '' if ft2font.__freetype_build_type__ == 'local' else 'not ') def _replacer(data, value): try: if isinstance(value, str): value = data[value] except Exception: pass return cbook.sanitize_sequence(value) def _label_from_arg(y, default_name): try: return y.name except AttributeError: if isinstance(default_name, str): return default_name return None def _add_data_doc(docstring, replace_names): if docstring is None or (replace_names is not None and len(replace_names) == 0): return docstring docstring = inspect.cleandoc(docstring) data_doc = ' If given, all parameters also accept a string ``s``, which is\n interpreted as ``data[s]`` if ``s`` is a key in ``data``.' if replace_names is None else f" If given, the following parameters also accept a string ``s``, which is\n interpreted as ``data[s]`` if ``s`` is a key in ``data``:\n\n {', '.join(map('*{}*'.format, replace_names))}" if _log.level <= logging.DEBUG: if 'data : indexable object, optional' not in docstring: _log.debug('data parameter docstring error: no data parameter') if 'DATA_PARAMETER_PLACEHOLDER' not in docstring: _log.debug('data parameter docstring error: missing placeholder') return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc) def _preprocess_data(func=None, *, replace_names=None, label_namer=None): if func is None: return functools.partial(_preprocess_data, replace_names=replace_names, label_namer=label_namer) sig = inspect.signature(func) varargs_name = None varkwargs_name = None arg_names = [] params = list(sig.parameters.values()) for p in params: if p.kind is Parameter.VAR_POSITIONAL: varargs_name = p.name elif p.kind is Parameter.VAR_KEYWORD: varkwargs_name = p.name else: arg_names.append(p.name) data_param = Parameter('data', Parameter.KEYWORD_ONLY, default=None) if varkwargs_name: params.insert(-1, data_param) else: params.append(data_param) new_sig = sig.replace(parameters=params) arg_names = arg_names[1:] assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, f'Matplotlib internal error: invalid replace_names ({replace_names!r}) for {func.__name__!r}' assert label_namer is None or label_namer in arg_names, f'Matplotlib internal error: invalid label_namer ({label_namer!r}) for {func.__name__!r}' @functools.wraps(func) def inner(ax, *args, data=None, **kwargs): if data is None: return func(ax, *map(cbook.sanitize_sequence, args), **{k: cbook.sanitize_sequence(v) for (k, v) in kwargs.items()}) bound = new_sig.bind(ax, *args, **kwargs) auto_label = bound.arguments.get(label_namer) or bound.kwargs.get(label_namer) for (k, v) in bound.arguments.items(): if k == varkwargs_name: for (k1, v1) in v.items(): if replace_names is None or k1 in replace_names: v[k1] = _replacer(data, v1) elif k == varargs_name: if replace_names is None: bound.arguments[k] = tuple((_replacer(data, v1) for v1 in v)) elif replace_names is None or k in replace_names: bound.arguments[k] = _replacer(data, v) new_args = bound.args new_kwargs = bound.kwargs args_and_kwargs = {**bound.arguments, **bound.kwargs} if label_namer and 'label' not in args_and_kwargs: new_kwargs['label'] = _label_from_arg(args_and_kwargs.get(label_namer), auto_label) return func(*new_args, **new_kwargs) inner.__doc__ = _add_data_doc(inner.__doc__, replace_names) inner.__signature__ = new_sig return inner _log.debug('interactive is %s', is_interactive()) _log.debug('platform is %s', sys.platform) @_api.deprecated('3.10', alternative='matplotlib.cbook.sanitize_sequence') def sanitize_sequence(data): return cbook.sanitize_sequence(data) @_api.deprecated('3.10', alternative='matplotlib.rcsetup.validate_backend') def validate_backend(s): return rcsetup.validate_backend(s) from matplotlib.cm import _colormaps as colormaps from matplotlib.cm import _multivar_colormaps as multivar_colormaps from matplotlib.cm import _bivar_colormaps as bivar_colormaps from matplotlib.colors import _color_sequences as color_sequences # File: matplotlib-main/lib/matplotlib/_afm.py """""" from collections import namedtuple import logging import re from ._mathtext_data import uni2type1 _log = logging.getLogger(__name__) def _to_int(x): return int(float(x)) def _to_float(x): if isinstance(x, bytes): 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): 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, b'Notice': lambda x: x, b'EncodingScheme': _to_str, b'CapHeight': _to_float, b'Capheight': _to_float, 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: 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__ = '\n Represents the character metrics of a single character.\n\n Notes\n -----\n The fields do currently only describe a subset of character metrics\n information defined in the AFM standard.\n ' CharMetrics.width.__doc__ = 'The character width (WX).' CharMetrics.name.__doc__ = 'The character name (N).' CharMetrics.bbox.__doc__ = '\n The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*).' def _parse_char_metrics(fh): required_keys = {'C', 'WX', 'N', 'B'} ascii_d = {} name_d = {} for line in fh: line = _to_str(line.rstrip()) if line.startswith('EndCharMetrics'): return (ascii_d, name_d) vals = dict((s.strip().split(' ', 1) for s in line.split(';') if s)) 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) if name == 'Euro': num = 128 elif name == 'minus': num = ord('−') if num != -1: ascii_d[num] = metrics name_d[name] = metrics raise RuntimeError('Bad parse') def _parse_kern_pairs(fh): 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) 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__ = '\n 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): 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): 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): 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): if not len(s): return (0, 0) total_width = 0 namelast = None miny = 1000000000.0 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): if not len(s): return (0, 0, 0, 0, 0) total_width = 0 namelast = None miny = 1000000000.0 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 self.get_str_bbox_and_descent(s)[:4] def get_name_char(self, c, isord=False): if not isord: c = ord(c) return self._metrics[c].name def get_width_char(self, c, isord=False): if not isord: c = ord(c) return self._metrics[c].width def get_width_from_char_name(self, name): return self._metrics_by_name[name].width def get_height_char(self, c, isord=False): if not isord: c = ord(c) return self._metrics[c].bbox[-1] def get_kern_dist(self, c1, 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 self._kern.get((name1, name2), 0) def get_fontname(self): return self._header[b'FontName'] @property def postscript_name(self): return self.get_fontname() def get_fullname(self): name = self._header.get(b'FullName') if name is None: name = self._header[b'FontName'] return name def get_familyname(self): name = self._header.get(b'FamilyName') if name is not None: return name name = self.get_fullname() extras = '(?i)([ -](regular|plain|italic|oblique|bold|semibold|light|ultralight|extra|condensed))+$' return re.sub(extras, '', name) @property def family_name(self): return self.get_familyname() def get_weight(self): return self._header[b'Weight'] def get_angle(self): return self._header[b'ItalicAngle'] def get_capheight(self): return self._header[b'CapHeight'] def get_xheight(self): return self._header[b'XHeight'] def get_underline_thickness(self): return self._header[b'UnderlineThickness'] def get_horizontal_stem_width(self): return self._header.get(b'StdHW', None) def get_vertical_stem_width(self): return self._header.get(b'StdVW', None) # File: matplotlib-main/lib/matplotlib/_animation_data.py JS_INCLUDE = '\n\n\n' STYLE_INCLUDE = '\n\n' DISPLAY_TEMPLATE = '\n
\n \n
\n \n
\n \n \n \n \n \n \n \n \n \n
\n
\n \n \n \n \n \n \n
\n
\n
\n\n\n\n' INCLUDED_FRAMES = '\n for (var i=0; i<{Nframes}; i++){{\n frames[i] = "{frame_dir}/frame" + ("0000000" + i).slice(-7) +\n ".{frame_format}";\n }}\n' # File: matplotlib-main/lib/matplotlib/_api/__init__.py """""" import functools import itertools import pathlib import re import sys import warnings from .deprecation import deprecated, warn_deprecated, rename_parameter, delete_parameter, make_keyword_only, deprecate_method_override, deprecate_privatize_attribute, suppress_matplotlib_deprecation_warning, MatplotlibDeprecationWarning class classproperty: def __init__(self, fget, fset=None, fdel=None, doc=None): self._fget = fget if fset is not None or fdel is not None: raise ValueError('classproperty only implements fget.') self.fset = fset self.fdel = fdel self._doc = doc def __get__(self, instance, owner): return self._fget(owner) @property def fget(self): return self._fget def check_isinstance(types, /, **kwargs): none_type = type(None) types = (types,) if isinstance(types, type) else (none_type,) if types is None else tuple((none_type if tp is None else tp for tp in types)) def type_name(tp): return 'None' if tp is none_type else tp.__qualname__ if tp.__module__ == 'builtins' else f'{tp.__module__}.{tp.__qualname__}' for (k, v) in kwargs.items(): if not isinstance(v, types): names = [*map(type_name, types)] if 'None' in names: names.remove('None') names.append('None') raise TypeError('{!r} must be an instance of {}, not a {}'.format(k, ', '.join(names[:-1]) + ' or ' + names[-1] if len(names) > 1 else names[0], type_name(type(v)))) def check_in_list(values, /, *, _print_supported_values=True, **kwargs): if not kwargs: raise TypeError('No argument to check!') for (key, val) in kwargs.items(): if val not in values: msg = f'{val!r} is not a valid value for {key}' if _print_supported_values: msg += f"; supported values are {', '.join(map(repr, values))}" raise ValueError(msg) def check_shape(shape, /, **kwargs): for (k, v) in kwargs.items(): data_shape = v.shape if len(data_shape) != len(shape) or any((s != t and t is not None for (s, t) in zip(data_shape, shape))): dim_labels = iter(itertools.chain('NMLKJIH', (f'D{i}' for i in itertools.count()))) text_shape = ', '.join([str(n) if n is not None else next(dim_labels) for n in shape[::-1]][::-1]) if len(shape) == 1: text_shape += ',' raise ValueError(f'{k!r} must be {len(shape)}D with shape ({text_shape}), but your input has shape {v.shape}') def check_getitem(mapping, /, **kwargs): if len(kwargs) != 1: raise ValueError('check_getitem takes a single keyword argument') ((k, v),) = kwargs.items() try: return mapping[v] except KeyError: raise ValueError(f"{v!r} is not a valid value for {k}; supported values are {', '.join(map(repr, mapping))}") from None def caching_module_getattr(cls): assert cls.__name__ == '__getattr__' props = {name: prop for (name, prop) in vars(cls).items() if isinstance(prop, property)} instance = cls() @functools.cache def __getattr__(name): if name in props: return props[name].__get__(instance) raise AttributeError(f'module {cls.__module__!r} has no attribute {name!r}') return __getattr__ def define_aliases(alias_d, cls=None): if cls is None: return functools.partial(define_aliases, alias_d) def make_alias(name): @functools.wraps(getattr(cls, name)) def method(self, *args, **kwargs): return getattr(self, name)(*args, **kwargs) return method for (prop, aliases) in alias_d.items(): exists = False for prefix in ['get_', 'set_']: if prefix + prop in vars(cls): exists = True for alias in aliases: method = make_alias(prefix + prop) method.__name__ = prefix + alias method.__doc__ = f'Alias for `{prefix + prop}`.' setattr(cls, prefix + alias, method) if not exists: raise ValueError(f'Neither getter nor setter exists for {prop!r}') def get_aliased_and_aliases(d): return {*d, *(alias for aliases in d.values() for alias in aliases)} preexisting_aliases = getattr(cls, '_alias_map', {}) conflicting = get_aliased_and_aliases(preexisting_aliases) & get_aliased_and_aliases(alias_d) if conflicting: raise NotImplementedError(f'Parent class already defines conflicting aliases: {conflicting}') cls._alias_map = {**preexisting_aliases, **alias_d} return cls def select_matching_signature(funcs, *args, **kwargs): for (i, func) in enumerate(funcs): try: return func(*args, **kwargs) except TypeError: if i == len(funcs) - 1: raise def nargs_error(name, takes, given): return TypeError(f'{name}() takes {takes} positional arguments but {given} were given') def kwarg_error(name, kw): if not isinstance(kw, str): kw = next(iter(kw)) return TypeError(f"{name}() got an unexpected keyword argument '{kw}'") def recursive_subclasses(cls): yield cls for subcls in cls.__subclasses__(): yield from recursive_subclasses(subcls) def warn_external(message, category=None): kwargs = {} if sys.version_info[:2] >= (3, 12): basedir = pathlib.Path(__file__).parents[2] kwargs['skip_file_prefixes'] = (str(basedir / 'matplotlib'), str(basedir / 'mpl_toolkits')) else: frame = sys._getframe() for stacklevel in itertools.count(1): if frame is None: kwargs['stacklevel'] = stacklevel break if not re.match('\\A(matplotlib|mpl_toolkits)(\\Z|\\.(?!tests\\.))', frame.f_globals.get('__name__', '')): kwargs['stacklevel'] = stacklevel break frame = frame.f_back del frame warnings.warn(message, category, **kwargs) # File: matplotlib-main/lib/matplotlib/_api/deprecation.py """""" import contextlib import functools import inspect import math import warnings class MatplotlibDeprecationWarning(DeprecationWarning): def _generate_deprecation_warning(since, message='', name='', alternative='', pending=False, obj_type='', addendum='', *, removal=''): if pending: if removal: raise ValueError('A pending deprecation cannot have a scheduled removal') else: if not removal: (macro, meso, *_) = since.split('.') removal = f'{macro}.{int(meso) + 2}' removal = f'in {removal}' if not message: message = ('The %(name)s %(obj_type)s' if obj_type else '%(name)s') + (' will be deprecated in a future version' if pending else ' was deprecated in Matplotlib %(since)s and will be removed %(removal)s') + '.' + (' Use %(alternative)s instead.' if alternative else '') + (' %(addendum)s' if addendum else '') warning_cls = PendingDeprecationWarning if pending else MatplotlibDeprecationWarning return warning_cls(message % dict(func=name, name=name, obj_type=obj_type, since=since, removal=removal, alternative=alternative, addendum=addendum)) def warn_deprecated(since, *, message='', name='', alternative='', pending=False, obj_type='', addendum='', removal=''): warning = _generate_deprecation_warning(since, message, name, alternative, pending, obj_type, addendum, removal=removal) from . import warn_external warn_external(warning, category=MatplotlibDeprecationWarning) def deprecated(since, *, message='', name='', alternative='', pending=False, obj_type=None, addendum='', removal=''): def deprecate(obj, message=message, name=name, alternative=alternative, pending=pending, obj_type=obj_type, addendum=addendum): from matplotlib._api import classproperty if isinstance(obj, type): if obj_type is None: obj_type = 'class' func = obj.__init__ name = name or obj.__name__ old_doc = obj.__doc__ def finalize(wrapper, new_doc): try: obj.__doc__ = new_doc except AttributeError: pass obj.__init__ = functools.wraps(obj.__init__)(wrapper) return obj elif isinstance(obj, (property, classproperty)): if obj_type is None: obj_type = 'attribute' func = None name = name or obj.fget.__name__ old_doc = obj.__doc__ class _deprecated_property(type(obj)): def __get__(self, instance, owner=None): if instance is not None or (owner is not None and isinstance(self, classproperty)): emit_warning() return super().__get__(instance, owner) def __set__(self, instance, value): if instance is not None: emit_warning() return super().__set__(instance, value) def __delete__(self, instance): if instance is not None: emit_warning() return super().__delete__(instance) def __set_name__(self, owner, set_name): nonlocal name if name == '': name = set_name def finalize(_, new_doc): return _deprecated_property(fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc) else: if obj_type is None: obj_type = 'function' func = obj name = name or obj.__name__ old_doc = func.__doc__ def finalize(wrapper, new_doc): wrapper = functools.wraps(func)(wrapper) wrapper.__doc__ = new_doc return wrapper def emit_warning(): warn_deprecated(since, message=message, name=name, alternative=alternative, pending=pending, obj_type=obj_type, addendum=addendum, removal=removal) def wrapper(*args, **kwargs): emit_warning() return func(*args, **kwargs) old_doc = inspect.cleandoc(old_doc or '').strip('\n') notes_header = '\nNotes\n-----' second_arg = ' '.join([t.strip() for t in (message, f'Use {alternative} instead.' if alternative else '', addendum) if t]) new_doc = f"[*Deprecated*] {old_doc}\n{(notes_header if notes_header not in old_doc else '')}\n.. deprecated:: {since}\n {second_arg}" if not old_doc: new_doc += '\\ ' return finalize(wrapper, new_doc) return deprecate class deprecate_privatize_attribute: def __init__(self, *args, **kwargs): self.deprecator = deprecated(*args, **kwargs) def __set_name__(self, owner, name): setattr(owner, name, self.deprecator(property(lambda self: getattr(self, f'_{name}'), lambda self, value: setattr(self, f'_{name}', value)), name=name)) DECORATORS = {} def rename_parameter(since, old, new, func=None): decorator = functools.partial(rename_parameter, since, old, new) if func is None: return decorator signature = inspect.signature(func) assert old not in signature.parameters, f'Matplotlib internal error: {old!r} cannot be a parameter for {func.__name__}()' assert new in signature.parameters, f'Matplotlib internal error: {new!r} must be a parameter for {func.__name__}()' @functools.wraps(func) def wrapper(*args, **kwargs): if old in kwargs: warn_deprecated(since, message=f'The {old!r} parameter of {func.__name__}() has been renamed {new!r} since Matplotlib {since}; support for the old name will be dropped %(removal)s.') kwargs[new] = kwargs.pop(old) return func(*args, **kwargs) DECORATORS[wrapper] = decorator return wrapper class _deprecated_parameter_class: def __repr__(self): return '' _deprecated_parameter = _deprecated_parameter_class() def delete_parameter(since, name, func=None, **kwargs): decorator = functools.partial(delete_parameter, since, name, **kwargs) if func is None: return decorator signature = inspect.signature(func) kwargs_name = next((param.name for param in signature.parameters.values() if param.kind == inspect.Parameter.VAR_KEYWORD), None) if name in signature.parameters: kind = signature.parameters[name].kind is_varargs = kind is inspect.Parameter.VAR_POSITIONAL is_varkwargs = kind is inspect.Parameter.VAR_KEYWORD if not is_varargs and (not is_varkwargs): name_idx = math.inf if kind is inspect.Parameter.KEYWORD_ONLY else [*signature.parameters].index(name) func.__signature__ = signature = signature.replace(parameters=[param.replace(default=_deprecated_parameter) if param.name == name else param for param in signature.parameters.values()]) else: name_idx = -1 else: is_varargs = is_varkwargs = False name_idx = math.inf assert kwargs_name, f'Matplotlib internal error: {name!r} must be a parameter for {func.__name__}()' addendum = kwargs.pop('addendum', None) @functools.wraps(func) def wrapper(*inner_args, **inner_kwargs): if len(inner_args) <= name_idx and name not in inner_kwargs: return func(*inner_args, **inner_kwargs) arguments = signature.bind(*inner_args, **inner_kwargs).arguments if is_varargs and arguments.get(name): warn_deprecated(since, message=f'Additional positional arguments to {func.__name__}() are deprecated since %(since)s and support for them will be removed %(removal)s.') elif is_varkwargs and arguments.get(name): warn_deprecated(since, message=f'Additional keyword arguments to {func.__name__}() are deprecated since %(since)s and support for them will be removed %(removal)s.') elif any((name in d and d[name] != _deprecated_parameter for d in [arguments, arguments.get(kwargs_name, {})])): deprecation_addendum = f'If any parameter follows {name!r}, they should be passed as keyword, not positionally.' warn_deprecated(since, name=repr(name), obj_type=f'parameter of {func.__name__}()', addendum=addendum + ' ' + deprecation_addendum if addendum else deprecation_addendum, **kwargs) return func(*inner_args, **inner_kwargs) DECORATORS[wrapper] = decorator return wrapper def make_keyword_only(since, name, func=None): decorator = functools.partial(make_keyword_only, since, name) if func is None: return decorator signature = inspect.signature(func) POK = inspect.Parameter.POSITIONAL_OR_KEYWORD KWO = inspect.Parameter.KEYWORD_ONLY assert name in signature.parameters and signature.parameters[name].kind == POK, f'Matplotlib internal error: {name!r} must be a positional-or-keyword parameter for {func.__name__}(). If this error happens on a function with a pyplot wrapper, make sure make_keyword_only() is the outermost decorator.' names = [*signature.parameters] name_idx = names.index(name) kwonly = [name for name in names[name_idx:] if signature.parameters[name].kind == POK] @functools.wraps(func) def wrapper(*args, **kwargs): if len(args) > name_idx: warn_deprecated(since, message='Passing the %(name)s %(obj_type)s positionally is deprecated since Matplotlib %(since)s; the parameter will become keyword-only %(removal)s.', name=name, obj_type=f'parameter of {func.__name__}()') return func(*args, **kwargs) wrapper.__signature__ = signature.replace(parameters=[param.replace(kind=KWO) if param.name in kwonly else param for param in signature.parameters.values()]) DECORATORS[wrapper] = decorator return wrapper def deprecate_method_override(method, obj, *, allow_empty=False, **kwargs): def empty(): pass def empty_with_docstring(): name = method.__name__ bound_child = getattr(obj, name) bound_base = method if isinstance(bound_child, type(empty)) and isinstance(obj, type) else method.__get__(obj) if bound_child != bound_base and (not allow_empty or getattr(getattr(bound_child, '__code__', None), 'co_code', None) not in [empty.__code__.co_code, empty_with_docstring.__code__.co_code]): warn_deprecated(**{'name': name, 'obj_type': 'method', **kwargs}) return bound_child return None @contextlib.contextmanager def suppress_matplotlib_deprecation_warning(): with warnings.catch_warnings(): warnings.simplefilter('ignore', MatplotlibDeprecationWarning) yield # File: matplotlib-main/lib/matplotlib/_blocking_input.py def blocking_input_loop(figure, event_names, timeout, handler): if figure.canvas.manager: figure.show() cids = [figure.canvas.mpl_connect(name, handler) for name in event_names] try: figure.canvas.start_event_loop(timeout) finally: for cid in cids: figure.canvas.mpl_disconnect(cid) # File: matplotlib-main/lib/matplotlib/_cm.py """""" from functools import partial import numpy as np _binary_data = {'red': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0))} _autumn_data = {'red': ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0))} _bone_data = {'red': ((0.0, 0.0, 0.0), (0.746032, 0.652778, 0.652778), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.365079, 0.319444, 0.319444), (0.746032, 0.777778, 0.777778), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (0.365079, 0.444444, 0.444444), (1.0, 1.0, 1.0))} _cool_data = {'red': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0))} _copper_data = {'red': ((0.0, 0.0, 0.0), (0.809524, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.7812, 0.7812)), 'blue': ((0.0, 0.0, 0.0), (1.0, 0.4975, 0.4975))} def _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5 def _flag_green(x): return np.sin(x * 31.5 * np.pi) def _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5 _flag_data = {'red': _flag_red, 'green': _flag_green, 'blue': _flag_blue} def _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67 def _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33 def _prism_blue(x): return -1.1 * np.sin(x * 20.9 * np.pi) _prism_data = {'red': _prism_red, 'green': _prism_green, 'blue': _prism_blue} def _ch_helper(gamma, s, r, h, p0, p1, x): xg = x ** gamma a = h * xg * (1 - xg) / 2 phi = 2 * np.pi * (s / 3 + r * x) return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi)) def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0): return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277), 'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649), 'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)} _cubehelix_data = cubehelix() _bwr_data = ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0)) _brg_data = ((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)) def _g0(x): return 0 def _g1(x): return 0.5 def _g2(x): return 1 def _g3(x): return x def _g4(x): return x ** 2 def _g5(x): return x ** 3 def _g6(x): return x ** 4 def _g7(x): return np.sqrt(x) def _g8(x): return np.sqrt(np.sqrt(x)) def _g9(x): return np.sin(x * np.pi / 2) def _g10(x): return np.cos(x * np.pi / 2) def _g11(x): return np.abs(x - 0.5) def _g12(x): return (2 * x - 1) ** 2 def _g13(x): return np.sin(x * np.pi) def _g14(x): return np.abs(np.cos(x * np.pi)) def _g15(x): return np.sin(x * 2 * np.pi) def _g16(x): return np.cos(x * 2 * np.pi) def _g17(x): return np.abs(np.sin(x * 2 * np.pi)) def _g18(x): return np.abs(np.cos(x * 2 * np.pi)) def _g19(x): return np.abs(np.sin(x * 4 * np.pi)) def _g20(x): return np.abs(np.cos(x * 4 * np.pi)) def _g21(x): return 3 * x def _g22(x): return 3 * x - 1 def _g23(x): return 3 * x - 2 def _g24(x): return np.abs(3 * x - 1) def _g25(x): return np.abs(3 * x - 2) def _g26(x): return (3 * x - 1) / 2 def _g27(x): return (3 * x - 2) / 2 def _g28(x): return np.abs((3 * x - 1) / 2) def _g29(x): return np.abs((3 * x - 2) / 2) def _g30(x): return x / 0.32 - 0.78125 def _g31(x): return 2 * x - 0.84 def _g32(x): ret = np.zeros(len(x)) m = x < 0.25 ret[m] = 4 * x[m] m = (x >= 0.25) & (x < 0.92) ret[m] = -2 * x[m] + 1.84 m = x >= 0.92 ret[m] = x[m] / 0.08 - 11.5 return ret def _g33(x): return np.abs(2 * x - 0.5) def _g34(x): return 2 * x def _g35(x): return 2 * x - 0.5 def _g36(x): return 2 * x - 1 gfunc = {i: globals()[f'_g{i}'] for i in range(37)} _gnuplot_data = {'red': gfunc[7], 'green': gfunc[5], 'blue': gfunc[15]} _gnuplot2_data = {'red': gfunc[30], 'green': gfunc[31], 'blue': gfunc[32]} _ocean_data = {'red': gfunc[23], 'green': gfunc[28], 'blue': gfunc[3]} _afmhot_data = {'red': gfunc[34], 'green': gfunc[35], 'blue': gfunc[36]} _rainbow_data = {'red': gfunc[33], 'green': gfunc[13], 'blue': gfunc[10]} _seismic_data = ((0.0, 0.0, 0.3), (0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0), (0.5, 0.0, 0.0)) _terrain_data = ((0.0, (0.2, 0.2, 0.6)), (0.15, (0.0, 0.6, 1.0)), (0.25, (0.0, 0.8, 0.4)), (0.5, (1.0, 1.0, 0.6)), (0.75, (0.5, 0.36, 0.33)), (1.0, (1.0, 1.0, 1.0))) _gray_data = {'red': ((0.0, 0, 0), (1.0, 1, 1)), 'green': ((0.0, 0, 0), (1.0, 1, 1)), 'blue': ((0.0, 0, 0), (1.0, 1, 1))} _hot_data = {'red': ((0.0, 0.0416, 0.0416), (0.365079, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.365079, 0.0, 0.0), (0.746032, 1.0, 1.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (0.746032, 0.0, 0.0), (1.0, 1.0, 1.0))} _hsv_data = {'red': ((0.0, 1.0, 1.0), (0.15873, 1.0, 1.0), (0.174603, 0.96875, 0.96875), (0.333333, 0.03125, 0.03125), (0.349206, 0.0, 0.0), (0.666667, 0.0, 0.0), (0.68254, 0.03125, 0.03125), (0.84127, 0.96875, 0.96875), (0.857143, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.15873, 0.9375, 0.9375), (0.174603, 1.0, 1.0), (0.507937, 1.0, 1.0), (0.666667, 0.0625, 0.0625), (0.68254, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (0.333333, 0.0, 0.0), (0.349206, 0.0625, 0.0625), (0.507937, 1.0, 1.0), (0.84127, 1.0, 1.0), (0.857143, 0.9375, 0.9375), (1.0, 0.09375, 0.09375))} _jet_data = {'red': ((0.0, 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1.0, 0.5, 0.5)), 'green': ((0.0, 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1), (0.91, 0, 0), (1.0, 0, 0)), 'blue': ((0.0, 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65, 0, 0), (1.0, 0, 0))} _pink_data = {'red': ((0.0, 0.1178, 0.1178), (0.015873, 0.195857, 0.195857), (0.031746, 0.250661, 0.250661), (0.047619, 0.295468, 0.295468), (0.063492, 0.334324, 0.334324), (0.079365, 0.369112, 0.369112), (0.095238, 0.400892, 0.400892), (0.111111, 0.430331, 0.430331), (0.126984, 0.457882, 0.457882), (0.142857, 0.483867, 0.483867), (0.15873, 0.508525, 0.508525), (0.174603, 0.532042, 0.532042), (0.190476, 0.554563, 0.554563), (0.206349, 0.576204, 0.576204), (0.222222, 0.597061, 0.597061), (0.238095, 0.617213, 0.617213), (0.253968, 0.636729, 0.636729), (0.269841, 0.655663, 0.655663), (0.285714, 0.674066, 0.674066), (0.301587, 0.69198, 0.69198), (0.31746, 0.709441, 0.709441), (0.333333, 0.726483, 0.726483), (0.349206, 0.743134, 0.743134), (0.365079, 0.759421, 0.759421), (0.380952, 0.766356, 0.766356), (0.396825, 0.773229, 0.773229), (0.412698, 0.780042, 0.780042), (0.428571, 0.786796, 0.786796), (0.444444, 0.793492, 0.793492), (0.460317, 0.800132, 0.800132), (0.47619, 0.806718, 0.806718), (0.492063, 0.81325, 0.81325), (0.507937, 0.81973, 0.81973), (0.52381, 0.82616, 0.82616), (0.539683, 0.832539, 0.832539), (0.555556, 0.83887, 0.83887), (0.571429, 0.845154, 0.845154), (0.587302, 0.851392, 0.851392), (0.603175, 0.857584, 0.857584), (0.619048, 0.863731, 0.863731), (0.634921, 0.869835, 0.869835), (0.650794, 0.875897, 0.875897), (0.666667, 0.881917, 0.881917), (0.68254, 0.887896, 0.887896), (0.698413, 0.893835, 0.893835), (0.714286, 0.899735, 0.899735), (0.730159, 0.905597, 0.905597), (0.746032, 0.911421, 0.911421), (0.761905, 0.917208, 0.917208), (0.777778, 0.922958, 0.922958), (0.793651, 0.928673, 0.928673), (0.809524, 0.934353, 0.934353), (0.825397, 0.939999, 0.939999), (0.84127, 0.945611, 0.945611), (0.857143, 0.95119, 0.95119), (0.873016, 0.956736, 0.956736), (0.888889, 0.96225, 0.96225), (0.904762, 0.967733, 0.967733), (0.920635, 0.973185, 0.973185), (0.936508, 0.978607, 0.978607), (0.952381, 0.983999, 0.983999), (0.968254, 0.989361, 0.989361), (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.015873, 0.102869, 0.102869), (0.031746, 0.145479, 0.145479), (0.047619, 0.178174, 0.178174), (0.063492, 0.205738, 0.205738), (0.079365, 0.230022, 0.230022), (0.095238, 0.251976, 0.251976), (0.111111, 0.272166, 0.272166), (0.126984, 0.290957, 0.290957), (0.142857, 0.308607, 0.308607), (0.15873, 0.3253, 0.3253), (0.174603, 0.341178, 0.341178), (0.190476, 0.356348, 0.356348), (0.206349, 0.370899, 0.370899), (0.222222, 0.3849, 0.3849), (0.238095, 0.39841, 0.39841), (0.253968, 0.411476, 0.411476), (0.269841, 0.424139, 0.424139), (0.285714, 0.436436, 0.436436), (0.301587, 0.448395, 0.448395), (0.31746, 0.460044, 0.460044), (0.333333, 0.471405, 0.471405), (0.349206, 0.482498, 0.482498), (0.365079, 0.493342, 0.493342), (0.380952, 0.517549, 0.517549), (0.396825, 0.540674, 0.540674), (0.412698, 0.562849, 0.562849), (0.428571, 0.584183, 0.584183), (0.444444, 0.604765, 0.604765), (0.460317, 0.624669, 0.624669), (0.47619, 0.643958, 0.643958), (0.492063, 0.662687, 0.662687), (0.507937, 0.6809, 0.6809), (0.52381, 0.698638, 0.698638), (0.539683, 0.715937, 0.715937), (0.555556, 0.732828, 0.732828), (0.571429, 0.749338, 0.749338), (0.587302, 0.765493, 0.765493), (0.603175, 0.781313, 0.781313), (0.619048, 0.796819, 0.796819), (0.634921, 0.812029, 0.812029), (0.650794, 0.82696, 0.82696), (0.666667, 0.841625, 0.841625), (0.68254, 0.85604, 0.85604), (0.698413, 0.870216, 0.870216), (0.714286, 0.884164, 0.884164), (0.730159, 0.897896, 0.897896), (0.746032, 0.911421, 0.911421), (0.761905, 0.917208, 0.917208), (0.777778, 0.922958, 0.922958), (0.793651, 0.928673, 0.928673), (0.809524, 0.934353, 0.934353), (0.825397, 0.939999, 0.939999), (0.84127, 0.945611, 0.945611), (0.857143, 0.95119, 0.95119), (0.873016, 0.956736, 0.956736), (0.888889, 0.96225, 0.96225), (0.904762, 0.967733, 0.967733), (0.920635, 0.973185, 0.973185), (0.936508, 0.978607, 0.978607), (0.952381, 0.983999, 0.983999), (0.968254, 0.989361, 0.989361), (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (0.015873, 0.102869, 0.102869), (0.031746, 0.145479, 0.145479), (0.047619, 0.178174, 0.178174), (0.063492, 0.205738, 0.205738), (0.079365, 0.230022, 0.230022), (0.095238, 0.251976, 0.251976), (0.111111, 0.272166, 0.272166), (0.126984, 0.290957, 0.290957), (0.142857, 0.308607, 0.308607), (0.15873, 0.3253, 0.3253), (0.174603, 0.341178, 0.341178), (0.190476, 0.356348, 0.356348), (0.206349, 0.370899, 0.370899), (0.222222, 0.3849, 0.3849), (0.238095, 0.39841, 0.39841), (0.253968, 0.411476, 0.411476), (0.269841, 0.424139, 0.424139), (0.285714, 0.436436, 0.436436), (0.301587, 0.448395, 0.448395), (0.31746, 0.460044, 0.460044), (0.333333, 0.471405, 0.471405), (0.349206, 0.482498, 0.482498), (0.365079, 0.493342, 0.493342), (0.380952, 0.503953, 0.503953), (0.396825, 0.514344, 0.514344), (0.412698, 0.524531, 0.524531), (0.428571, 0.534522, 0.534522), (0.444444, 0.544331, 0.544331), (0.460317, 0.553966, 0.553966), (0.47619, 0.563436, 0.563436), (0.492063, 0.57275, 0.57275), (0.507937, 0.581914, 0.581914), (0.52381, 0.590937, 0.590937), (0.539683, 0.599824, 0.599824), (0.555556, 0.608581, 0.608581), (0.571429, 0.617213, 0.617213), (0.587302, 0.625727, 0.625727), (0.603175, 0.634126, 0.634126), (0.619048, 0.642416, 0.642416), (0.634921, 0.6506, 0.6506), (0.650794, 0.658682, 0.658682), (0.666667, 0.666667, 0.666667), (0.68254, 0.674556, 0.674556), (0.698413, 0.682355, 0.682355), (0.714286, 0.690066, 0.690066), (0.730159, 0.697691, 0.697691), (0.746032, 0.705234, 0.705234), (0.761905, 0.727166, 0.727166), (0.777778, 0.748455, 0.748455), (0.793651, 0.769156, 0.769156), (0.809524, 0.789314, 0.789314), (0.825397, 0.808969, 0.808969), (0.84127, 0.828159, 0.828159), (0.857143, 0.846913, 0.846913), (0.873016, 0.865261, 0.865261), (0.888889, 0.883229, 0.883229), (0.904762, 0.900837, 0.900837), (0.920635, 0.918109, 0.918109), (0.936508, 0.935061, 0.935061), (0.952381, 0.951711, 0.951711), (0.968254, 0.968075, 0.968075), (0.984127, 0.984167, 0.984167), (1.0, 1.0, 1.0))} _spring_data = {'red': ((0.0, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0))} _summer_data = {'red': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.5, 0.5), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.4, 0.4), (1.0, 0.4, 0.4))} _winter_data = {'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 1.0, 1.0), (1.0, 0.5, 0.5))} _nipy_spectral_data = {'red': [(0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667), (0.1, 0.5333, 0.5333), (0.15, 0.0, 0.0), (0.2, 0.0, 0.0), (0.25, 0.0, 0.0), (0.3, 0.0, 0.0), (0.35, 0.0, 0.0), (0.4, 0.0, 0.0), (0.45, 0.0, 0.0), (0.5, 0.0, 0.0), (0.55, 0.0, 0.0), (0.6, 0.0, 0.0), (0.65, 0.7333, 0.7333), (0.7, 0.9333, 0.9333), (0.75, 1.0, 1.0), (0.8, 1.0, 1.0), (0.85, 1.0, 1.0), (0.9, 0.8667, 0.8667), (0.95, 0.8, 0.8), (1.0, 0.8, 0.8)], 'green': [(0.0, 0.0, 0.0), (0.05, 0.0, 0.0), (0.1, 0.0, 0.0), (0.15, 0.0, 0.0), (0.2, 0.0, 0.0), (0.25, 0.4667, 0.4667), (0.3, 0.6, 0.6), (0.35, 0.6667, 0.6667), (0.4, 0.6667, 0.6667), (0.45, 0.6, 0.6), (0.5, 0.7333, 0.7333), (0.55, 0.8667, 0.8667), (0.6, 1.0, 1.0), (0.65, 1.0, 1.0), (0.7, 0.9333, 0.9333), (0.75, 0.8, 0.8), (0.8, 0.6, 0.6), (0.85, 0.0, 0.0), (0.9, 0.0, 0.0), (0.95, 0.0, 0.0), (1.0, 0.8, 0.8)], 'blue': [(0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333), (0.1, 0.6, 0.6), (0.15, 0.6667, 0.6667), (0.2, 0.8667, 0.8667), (0.25, 0.8667, 0.8667), (0.3, 0.8667, 0.8667), (0.35, 0.6667, 0.6667), (0.4, 0.5333, 0.5333), (0.45, 0.0, 0.0), (0.5, 0.0, 0.0), (0.55, 0.0, 0.0), (0.6, 0.0, 0.0), (0.65, 0.0, 0.0), (0.7, 0.0, 0.0), (0.75, 0.0, 0.0), (0.8, 0.0, 0.0), (0.85, 0.0, 0.0), (0.9, 0.0, 0.0), (0.95, 0.0, 0.0), (1.0, 0.8, 0.8)]} _Blues_data = ((0.9686274509803922, 0.984313725490196, 1.0), (0.8705882352941177, 0.9215686274509803, 0.9686274509803922), (0.7764705882352941, 0.8588235294117647, 0.9372549019607843), (0.6196078431372549, 0.792156862745098, 0.8823529411764706), (0.4196078431372549, 0.6823529411764706, 0.8392156862745098), (0.25882352941176473, 0.5725490196078431, 0.7764705882352941), (0.12941176470588237, 0.44313725490196076, 0.7098039215686275), (0.03137254901960784, 0.3176470588235294, 0.611764705882353), (0.03137254901960784, 0.18823529411764706, 0.4196078431372549)) _BrBG_data = ((0.32941176470588235, 0.18823529411764706, 0.0196078431372549), (0.5490196078431373, 0.3176470588235294, 0.0392156862745098), (0.7490196078431373, 0.5058823529411764, 0.17647058823529413), (0.8745098039215686, 0.7607843137254902, 0.49019607843137253), (0.9647058823529412, 0.9098039215686274, 0.7647058823529411), (0.9607843137254902, 0.9607843137254902, 0.9607843137254902), (0.7803921568627451, 0.9176470588235294, 0.8980392156862745), (0.5019607843137255, 0.803921568627451, 0.7568627450980392), (0.20784313725490197, 0.592156862745098, 0.5607843137254902), (0.00392156862745098, 0.4, 0.3686274509803922), (0.0, 0.23529411764705882, 0.18823529411764706)) _BuGn_data = ((0.9686274509803922, 0.9882352941176471, 0.9921568627450981), (0.8980392156862745, 0.9607843137254902, 0.9764705882352941), (0.8, 0.9254901960784314, 0.9019607843137255), (0.6, 0.8470588235294118, 0.788235294117647), (0.4, 0.7607843137254902, 0.6431372549019608), (0.2549019607843137, 0.6823529411764706, 0.4627450980392157), (0.13725490196078433, 0.5450980392156862, 0.27058823529411763), (0.0, 0.42745098039215684, 0.17254901960784313), (0.0, 0.26666666666666666, 0.10588235294117647)) _BuPu_data = ((0.9686274509803922, 0.9882352941176471, 0.9921568627450981), (0.8784313725490196, 0.9254901960784314, 0.9568627450980393), (0.7490196078431373, 0.8274509803921568, 0.9019607843137255), (0.6196078431372549, 0.7372549019607844, 0.8549019607843137), (0.5490196078431373, 0.5882352941176471, 0.7764705882352941), (0.5490196078431373, 0.4196078431372549, 0.6941176470588235), (0.5333333333333333, 0.2549019607843137, 0.615686274509804), (0.5058823529411764, 0.05882352941176471, 0.48627450980392156), (0.30196078431372547, 0.0, 0.29411764705882354)) _GnBu_data = ((0.9686274509803922, 0.9882352941176471, 0.9411764705882353), (0.8784313725490196, 0.9529411764705882, 0.8588235294117647), (0.8, 0.9215686274509803, 0.7725490196078432), (0.6588235294117647, 0.8666666666666667, 0.7098039215686275), (0.4823529411764706, 0.8, 0.7686274509803922), (0.3058823529411765, 0.7019607843137254, 0.8274509803921568), (0.16862745098039217, 0.5490196078431373, 0.7450980392156863), (0.03137254901960784, 0.40784313725490196, 0.6745098039215687), (0.03137254901960784, 0.25098039215686274, 0.5058823529411764)) _Greens_data = ((0.9686274509803922, 0.9882352941176471, 0.9607843137254902), (0.8980392156862745, 0.9607843137254902, 0.8784313725490196), (0.7803921568627451, 0.9137254901960784, 0.7529411764705882), (0.6313725490196078, 0.8509803921568627, 0.6078431372549019), (0.4549019607843137, 0.7686274509803922, 0.4627450980392157), (0.2549019607843137, 0.6705882352941176, 0.36470588235294116), (0.13725490196078433, 0.5450980392156862, 0.27058823529411763), (0.0, 0.42745098039215684, 0.17254901960784313), (0.0, 0.26666666666666666, 0.10588235294117647)) _Greys_data = ((1.0, 1.0, 1.0), (0.9411764705882353, 0.9411764705882353, 0.9411764705882353), (0.8509803921568627, 0.8509803921568627, 0.8509803921568627), (0.7411764705882353, 0.7411764705882353, 0.7411764705882353), (0.5882352941176471, 0.5882352941176471, 0.5882352941176471), (0.45098039215686275, 0.45098039215686275, 0.45098039215686275), (0.3215686274509804, 0.3215686274509804, 0.3215686274509804), (0.1450980392156863, 0.1450980392156863, 0.1450980392156863), (0.0, 0.0, 0.0)) _Oranges_data = ((1.0, 0.9607843137254902, 0.9215686274509803), (0.996078431372549, 0.9019607843137255, 0.807843137254902), (0.9921568627450981, 0.8156862745098039, 0.6352941176470588), (0.9921568627450981, 0.6823529411764706, 0.4196078431372549), (0.9921568627450981, 0.5529411764705883, 0.23529411764705882), (0.9450980392156862, 0.4117647058823529, 0.07450980392156863), (0.8509803921568627, 0.2823529411764706, 0.00392156862745098), (0.6509803921568628, 0.21176470588235294, 0.01176470588235294), (0.4980392156862745, 0.15294117647058825, 0.01568627450980392)) _OrRd_data = ((1.0, 0.9686274509803922, 0.9254901960784314), (0.996078431372549, 0.9098039215686274, 0.7843137254901961), (0.9921568627450981, 0.8313725490196079, 0.6196078431372549), (0.9921568627450981, 0.7333333333333333, 0.5176470588235295), (0.9882352941176471, 0.5529411764705883, 0.34901960784313724), (0.9372549019607843, 0.396078431372549, 0.2823529411764706), (0.8431372549019608, 0.18823529411764706, 0.12156862745098039), (0.7019607843137254, 0.0, 0.0), (0.4980392156862745, 0.0, 0.0)) _PiYG_data = ((0.5568627450980392, 0.00392156862745098, 0.3215686274509804), (0.7725490196078432, 0.10588235294117647, 0.49019607843137253), (0.8705882352941177, 0.4666666666666667, 0.6823529411764706), (0.9450980392156862, 0.7137254901960784, 0.8549019607843137), (0.9921568627450981, 0.8784313725490196, 0.9372549019607843), (0.9686274509803922, 0.9686274509803922, 0.9686274509803922), (0.9019607843137255, 0.9607843137254902, 0.8156862745098039), (0.7215686274509804, 0.8823529411764706, 0.5254901960784314), (0.4980392156862745, 0.7372549019607844, 0.2549019607843137), (0.30196078431372547, 0.5725490196078431, 0.12941176470588237), (0.15294117647058825, 0.39215686274509803, 0.09803921568627451)) _PRGn_data = ((0.25098039215686274, 0.0, 0.29411764705882354), (0.4627450980392157, 0.16470588235294117, 0.5137254901960784), (0.6, 0.4392156862745098, 0.6705882352941176), (0.7607843137254902, 0.6470588235294118, 0.8117647058823529), (0.9058823529411765, 0.8313725490196079, 0.9098039215686274), (0.9686274509803922, 0.9686274509803922, 0.9686274509803922), (0.8509803921568627, 0.9411764705882353, 0.8274509803921568), (0.6509803921568628, 0.8588235294117647, 0.6274509803921569), (0.35294117647058826, 0.6823529411764706, 0.3803921568627451), (0.10588235294117647, 0.47058823529411764, 0.21568627450980393), (0.0, 0.26666666666666666, 0.10588235294117647)) _PuBu_data = ((1.0, 0.9686274509803922, 0.984313725490196), (0.9254901960784314, 0.9058823529411765, 0.9490196078431372), (0.8156862745098039, 0.8196078431372549, 0.9019607843137255), (0.6509803921568628, 0.7411764705882353, 0.8588235294117647), (0.4549019607843137, 0.6627450980392157, 0.8117647058823529), (0.21176470588235294, 0.5647058823529412, 0.7529411764705882), (0.0196078431372549, 0.4392156862745098, 0.6901960784313725), (0.01568627450980392, 0.35294117647058826, 0.5529411764705883), (0.00784313725490196, 0.2196078431372549, 0.34509803921568627)) _PuBuGn_data = ((1.0, 0.9686274509803922, 0.984313725490196), (0.9254901960784314, 0.8862745098039215, 0.9411764705882353), (0.8156862745098039, 0.8196078431372549, 0.9019607843137255), (0.6509803921568628, 0.7411764705882353, 0.8588235294117647), (0.403921568627451, 0.6627450980392157, 0.8117647058823529), (0.21176470588235294, 0.5647058823529412, 0.7529411764705882), (0.00784313725490196, 0.5058823529411764, 0.5411764705882353), (0.00392156862745098, 0.4235294117647059, 0.34901960784313724), (0.00392156862745098, 0.27450980392156865, 0.21176470588235294)) _PuOr_data = ((0.4980392156862745, 0.23137254901960785, 0.03137254901960784), (0.7019607843137254, 0.34509803921568627, 0.02352941176470588), (0.8784313725490196, 0.5098039215686274, 0.0784313725490196), (0.9921568627450981, 0.7215686274509804, 0.38823529411764707), (0.996078431372549, 0.8784313725490196, 0.7137254901960784), (0.9686274509803922, 0.9686274509803922, 0.9686274509803922), (0.8470588235294118, 0.8549019607843137, 0.9215686274509803), (0.6980392156862745, 0.6705882352941176, 0.8235294117647058), (0.5019607843137255, 0.45098039215686275, 0.6745098039215687), (0.32941176470588235, 0.15294117647058825, 0.5333333333333333), (0.17647058823529413, 0.0, 0.29411764705882354)) _PuRd_data = ((0.9686274509803922, 0.9568627450980393, 0.9764705882352941), (0.9058823529411765, 0.8823529411764706, 0.9372549019607843), (0.8313725490196079, 0.7254901960784313, 0.8549019607843137), (0.788235294117647, 0.5803921568627451, 0.7803921568627451), (0.8745098039215686, 0.396078431372549, 0.6901960784313725), (0.9058823529411765, 0.1607843137254902, 0.5411764705882353), (0.807843137254902, 0.07058823529411765, 0.33725490196078434), (0.596078431372549, 0.0, 0.2627450980392157), (0.403921568627451, 0.0, 0.12156862745098039)) _Purples_data = ((0.9882352941176471, 0.984313725490196, 0.9921568627450981), (0.9372549019607843, 0.9294117647058824, 0.9607843137254902), (0.8549019607843137, 0.8549019607843137, 0.9215686274509803), (0.7372549019607844, 0.7411764705882353, 0.8627450980392157), (0.6196078431372549, 0.6039215686274509, 0.7843137254901961), (0.5019607843137255, 0.49019607843137253, 0.7294117647058823), (0.41568627450980394, 0.3176470588235294, 0.6392156862745098), (0.32941176470588235, 0.15294117647058825, 0.5607843137254902), (0.24705882352941178, 0.0, 0.49019607843137253)) _RdBu_data = ((0.403921568627451, 0.0, 0.12156862745098039), (0.6980392156862745, 0.09411764705882353, 0.16862745098039217), (0.8392156862745098, 0.3764705882352941, 0.30196078431372547), (0.9568627450980393, 0.6470588235294118, 0.5098039215686274), (0.9921568627450981, 0.8588235294117647, 0.7803921568627451), (0.9686274509803922, 0.9686274509803922, 0.9686274509803922), (0.8196078431372549, 0.8980392156862745, 0.9411764705882353), (0.5725490196078431, 0.7725490196078432, 0.8705882352941177), (0.2627450980392157, 0.5764705882352941, 0.7647058823529411), (0.12941176470588237, 0.4, 0.6745098039215687), (0.0196078431372549, 0.18823529411764706, 0.3803921568627451)) _RdGy_data = ((0.403921568627451, 0.0, 0.12156862745098039), (0.6980392156862745, 0.09411764705882353, 0.16862745098039217), (0.8392156862745098, 0.3764705882352941, 0.30196078431372547), (0.9568627450980393, 0.6470588235294118, 0.5098039215686274), (0.9921568627450981, 0.8588235294117647, 0.7803921568627451), (1.0, 1.0, 1.0), (0.8784313725490196, 0.8784313725490196, 0.8784313725490196), (0.7294117647058823, 0.7294117647058823, 0.7294117647058823), (0.5294117647058824, 0.5294117647058824, 0.5294117647058824), (0.30196078431372547, 0.30196078431372547, 0.30196078431372547), (0.10196078431372549, 0.10196078431372549, 0.10196078431372549)) _RdPu_data = ((1.0, 0.9686274509803922, 0.9529411764705882), (0.9921568627450981, 0.8784313725490196, 0.8666666666666667), (0.9882352941176471, 0.7725490196078432, 0.7529411764705882), (0.9803921568627451, 0.6235294117647059, 0.7098039215686275), (0.9686274509803922, 0.40784313725490196, 0.6313725490196078), (0.8666666666666667, 0.20392156862745098, 0.592156862745098), (0.6823529411764706, 0.00392156862745098, 0.49411764705882355), (0.47843137254901963, 0.00392156862745098, 0.4666666666666667), (0.28627450980392155, 0.0, 0.41568627450980394)) _RdYlBu_data = ((0.6470588235294118, 0.0, 0.14901960784313725), (0.8431372549019608, 0.18823529411764706, 0.15294117647058825), (0.9568627450980393, 0.42745098039215684, 0.2627450980392157), (0.9921568627450981, 0.6823529411764706, 0.3803921568627451), (0.996078431372549, 0.8784313725490196, 0.5647058823529412), (1.0, 1.0, 0.7490196078431373), (0.8784313725490196, 0.9529411764705882, 0.9725490196078431), (0.6705882352941176, 0.8509803921568627, 0.9137254901960784), (0.4549019607843137, 0.6784313725490196, 0.8196078431372549), (0.27058823529411763, 0.4588235294117647, 0.7058823529411765), (0.19215686274509805, 0.21176470588235294, 0.5843137254901961)) _RdYlGn_data = ((0.6470588235294118, 0.0, 0.14901960784313725), (0.8431372549019608, 0.18823529411764706, 0.15294117647058825), (0.9568627450980393, 0.42745098039215684, 0.2627450980392157), (0.9921568627450981, 0.6823529411764706, 0.3803921568627451), (0.996078431372549, 0.8784313725490196, 0.5450980392156862), (1.0, 1.0, 0.7490196078431373), (0.8509803921568627, 0.9372549019607843, 0.5450980392156862), (0.6509803921568628, 0.8509803921568627, 0.41568627450980394), (0.4, 0.7411764705882353, 0.38823529411764707), (0.10196078431372549, 0.596078431372549, 0.3137254901960784), (0.0, 0.40784313725490196, 0.21568627450980393)) _Reds_data = ((1.0, 0.9607843137254902, 0.9411764705882353), (0.996078431372549, 0.8784313725490196, 0.8235294117647058), (0.9882352941176471, 0.7333333333333333, 0.6313725490196078), (0.9882352941176471, 0.5725490196078431, 0.4470588235294118), (0.984313725490196, 0.41568627450980394, 0.2901960784313726), (0.9372549019607843, 0.23137254901960785, 0.17254901960784313), (0.796078431372549, 0.09411764705882353, 0.11372549019607843), (0.6470588235294118, 0.058823529411764705, 0.08235294117647057), (0.403921568627451, 0.0, 0.05098039215686274)) _Spectral_data = ((0.6196078431372549, 0.00392156862745098, 0.25882352941176473), (0.8352941176470589, 0.24313725490196078, 0.30980392156862746), (0.9568627450980393, 0.42745098039215684, 0.2627450980392157), (0.9921568627450981, 0.6823529411764706, 0.3803921568627451), (0.996078431372549, 0.8784313725490196, 0.5450980392156862), (1.0, 1.0, 0.7490196078431373), (0.9019607843137255, 0.9607843137254902, 0.596078431372549), (0.6705882352941176, 0.8666666666666667, 0.6431372549019608), (0.4, 0.7607843137254902, 0.6470588235294118), (0.19607843137254902, 0.5333333333333333, 0.7411764705882353), (0.3686274509803922, 0.30980392156862746, 0.6352941176470588)) _YlGn_data = ((1.0, 1.0, 0.8980392156862745), (0.9686274509803922, 0.9882352941176471, 0.7254901960784313), (0.8509803921568627, 0.9411764705882353, 0.6392156862745098), (0.6784313725490196, 0.8666666666666667, 0.5568627450980392), (0.47058823529411764, 0.7764705882352941, 0.4745098039215686), (0.2549019607843137, 0.6705882352941176, 0.36470588235294116), (0.13725490196078433, 0.5176470588235295, 0.2627450980392157), (0.0, 0.40784313725490196, 0.21568627450980393), (0.0, 0.27058823529411763, 0.1607843137254902)) _YlGnBu_data = ((1.0, 1.0, 0.8509803921568627), (0.9294117647058824, 0.9725490196078431, 0.6941176470588235), (0.7803921568627451, 0.9137254901960784, 0.7058823529411765), (0.4980392156862745, 0.803921568627451, 0.7333333333333333), (0.2549019607843137, 0.7137254901960784, 0.7686274509803922), (0.11372549019607843, 0.5686274509803921, 0.7529411764705882), (0.13333333333333333, 0.3686274509803922, 0.6588235294117647), (0.1450980392156863, 0.20392156862745098, 0.5803921568627451), (0.03137254901960784, 0.11372549019607843, 0.34509803921568627)) _YlOrBr_data = ((1.0, 1.0, 0.8980392156862745), (1.0, 0.9686274509803922, 0.7372549019607844), (0.996078431372549, 0.8901960784313725, 0.5686274509803921), (0.996078431372549, 0.7686274509803922, 0.30980392156862746), (0.996078431372549, 0.6, 0.1607843137254902), (0.9254901960784314, 0.4392156862745098, 0.0784313725490196), (0.8, 0.2980392156862745, 0.00784313725490196), (0.6, 0.20392156862745098, 0.01568627450980392), (0.4, 0.1450980392156863, 0.02352941176470588)) _YlOrRd_data = ((1.0, 1.0, 0.8), (1.0, 0.9294117647058824, 0.6274509803921569), (0.996078431372549, 0.8509803921568627, 0.4627450980392157), (0.996078431372549, 0.6980392156862745, 0.2980392156862745), (0.9921568627450981, 0.5529411764705883, 0.23529411764705882), (0.9882352941176471, 0.3058823529411765, 0.16470588235294117), (0.8901960784313725, 0.10196078431372549, 0.10980392156862745), (0.7411764705882353, 0.0, 0.14901960784313725), (0.5019607843137255, 0.0, 0.14901960784313725)) _Accent_data = ((0.4980392156862745, 0.788235294117647, 0.4980392156862745), (0.7450980392156863, 0.6823529411764706, 0.8313725490196079), (0.9921568627450981, 0.7529411764705882, 0.5254901960784314), (1.0, 1.0, 0.6), (0.2196078431372549, 0.4235294117647059, 0.6901960784313725), (0.9411764705882353, 0.00784313725490196, 0.4980392156862745), (0.7490196078431373, 0.3568627450980392, 0.09019607843137253), (0.4, 0.4, 0.4)) _Dark2_data = ((0.10588235294117647, 0.6196078431372549, 0.4666666666666667), (0.8509803921568627, 0.37254901960784315, 0.00784313725490196), (0.4588235294117647, 0.4392156862745098, 0.7019607843137254), (0.9058823529411765, 0.1607843137254902, 0.5411764705882353), (0.4, 0.6509803921568628, 0.11764705882352941), (0.9019607843137255, 0.6705882352941176, 0.00784313725490196), (0.6509803921568628, 0.4627450980392157, 0.11372549019607843), (0.4, 0.4, 0.4)) _Paired_data = ((0.6509803921568628, 0.807843137254902, 0.8901960784313725), (0.12156862745098039, 0.47058823529411764, 0.7058823529411765), (0.6980392156862745, 0.8745098039215686, 0.5411764705882353), (0.2, 0.6274509803921569, 0.17254901960784313), (0.984313725490196, 0.6039215686274509, 0.6), (0.8901960784313725, 0.10196078431372549, 0.10980392156862745), (0.9921568627450981, 0.7490196078431373, 0.43529411764705883), (1.0, 0.4980392156862745, 0.0), (0.792156862745098, 0.6980392156862745, 0.8392156862745098), (0.41568627450980394, 0.23921568627450981, 0.6039215686274509), (1.0, 1.0, 0.6), (0.6941176470588235, 0.34901960784313724, 0.1568627450980392)) _Pastel1_data = ((0.984313725490196, 0.7058823529411765, 0.6823529411764706), (0.7019607843137254, 0.803921568627451, 0.8901960784313725), (0.8, 0.9215686274509803, 0.7725490196078432), (0.8705882352941177, 0.796078431372549, 0.8941176470588236), (0.996078431372549, 0.8509803921568627, 0.6509803921568628), (1.0, 1.0, 0.8), (0.8980392156862745, 0.8470588235294118, 0.7411764705882353), (0.9921568627450981, 0.8549019607843137, 0.9254901960784314), (0.9490196078431372, 0.9490196078431372, 0.9490196078431372)) _Pastel2_data = ((0.7019607843137254, 0.8862745098039215, 0.803921568627451), (0.9921568627450981, 0.803921568627451, 0.6745098039215687), (0.796078431372549, 0.8352941176470589, 0.9098039215686274), (0.9568627450980393, 0.792156862745098, 0.8941176470588236), (0.9019607843137255, 0.9607843137254902, 0.788235294117647), (1.0, 0.9490196078431372, 0.6823529411764706), (0.9450980392156862, 0.8862745098039215, 0.8), (0.8, 0.8, 0.8)) _Set1_data = ((0.8941176470588236, 0.10196078431372549, 0.10980392156862745), (0.21568627450980393, 0.49411764705882355, 0.7215686274509804), (0.30196078431372547, 0.6862745098039216, 0.2901960784313726), (0.596078431372549, 0.3058823529411765, 0.6392156862745098), (1.0, 0.4980392156862745, 0.0), (1.0, 1.0, 0.2), (0.6509803921568628, 0.33725490196078434, 0.1568627450980392), (0.9686274509803922, 0.5058823529411764, 0.7490196078431373), (0.6, 0.6, 0.6)) _Set2_data = ((0.4, 0.7607843137254902, 0.6470588235294118), (0.9882352941176471, 0.5529411764705883, 0.3843137254901961), (0.5529411764705883, 0.6274509803921569, 0.796078431372549), (0.9058823529411765, 0.5411764705882353, 0.7647058823529411), (0.6509803921568628, 0.8470588235294118, 0.32941176470588235), (1.0, 0.8509803921568627, 0.1843137254901961), (0.8980392156862745, 0.7686274509803922, 0.5803921568627451), (0.7019607843137254, 0.7019607843137254, 0.7019607843137254)) _Set3_data = ((0.5529411764705883, 0.8274509803921568, 0.7803921568627451), (1.0, 1.0, 0.7019607843137254), (0.7450980392156863, 0.7294117647058823, 0.8549019607843137), (0.984313725490196, 0.5019607843137255, 0.4470588235294118), (0.5019607843137255, 0.6941176470588235, 0.8274509803921568), (0.9921568627450981, 0.7058823529411765, 0.3843137254901961), (0.7019607843137254, 0.8705882352941177, 0.4117647058823529), (0.9882352941176471, 0.803921568627451, 0.8980392156862745), (0.8509803921568627, 0.8509803921568627, 0.8509803921568627), (0.7372549019607844, 0.5019607843137255, 0.7411764705882353), (0.8, 0.9215686274509803, 0.7725490196078432), (1.0, 0.9294117647058824, 0.43529411764705883)) _gist_earth_data = {'red': ((0.0, 0.0, 0.0), (0.2824, 0.1882, 0.1882), (0.4588, 0.2714, 0.2714), (0.549, 0.4719, 0.4719), (0.698, 0.7176, 0.7176), (0.7882, 0.7553, 0.7553), (1.0, 0.9922, 0.9922)), 'green': ((0.0, 0.0, 0.0), (0.0275, 0.0, 0.0), (0.1098, 0.1893, 0.1893), (0.1647, 0.3035, 0.3035), (0.2078, 0.3841, 0.3841), (0.2824, 0.502, 0.502), (0.5216, 0.6397, 0.6397), (0.698, 0.7171, 0.7171), (0.7882, 0.6392, 0.6392), (0.7922, 0.6413, 0.6413), (0.8, 0.6447, 0.6447), (0.8078, 0.6481, 0.6481), (0.8157, 0.6549, 0.6549), (0.8667, 0.6991, 0.6991), (0.8745, 0.7103, 0.7103), (0.8824, 0.7216, 0.7216), (0.8902, 0.7323, 0.7323), (0.898, 0.743, 0.743), (0.9412, 0.8275, 0.8275), (0.9569, 0.8635, 0.8635), (0.9647, 0.8816, 0.8816), (0.9961, 0.9733, 0.9733), (1.0, 0.9843, 0.9843)), 'blue': ((0.0, 0.0, 0.0), (0.0039, 0.1684, 0.1684), (0.0078, 0.2212, 0.2212), (0.0275, 0.4329, 0.4329), (0.0314, 0.4549, 0.4549), (0.2824, 0.5004, 0.5004), (0.4667, 0.2748, 0.2748), (0.5451, 0.3205, 0.3205), (0.7843, 0.3961, 0.3961), (0.8941, 0.6651, 0.6651), (1.0, 0.9843, 0.9843))} _gist_gray_data = {'red': gfunc[3], 'green': gfunc[3], 'blue': gfunc[3]} def _gist_heat_red(x): return 1.5 * x def _gist_heat_green(x): return 2 * x - 1 def _gist_heat_blue(x): return 4 * x - 3 _gist_heat_data = {'red': _gist_heat_red, 'green': _gist_heat_green, 'blue': _gist_heat_blue} _gist_ncar_data = {'red': ((0.0, 0.0, 0.0), (0.3098, 0.0, 0.0), (0.3725, 0.3993, 0.3993), (0.4235, 0.5003, 0.5003), (0.5333, 1.0, 1.0), (0.7922, 1.0, 1.0), (0.8471, 0.6218, 0.6218), (0.898, 0.9235, 0.9235), (1.0, 0.9961, 0.9961)), 'green': ((0.0, 0.0, 0.0), (0.051, 0.3722, 0.3722), (0.1059, 0.0, 0.0), (0.1569, 0.7202, 0.7202), (0.1608, 0.7537, 0.7537), (0.1647, 0.7752, 0.7752), (0.2157, 1.0, 1.0), (0.2588, 0.9804, 0.9804), (0.2706, 0.9804, 0.9804), (0.3176, 1.0, 1.0), (0.3686, 0.8081, 0.8081), (0.4275, 1.0, 1.0), (0.5216, 1.0, 1.0), (0.6314, 0.7292, 0.7292), (0.6863, 0.2796, 0.2796), (0.7451, 0.0, 0.0), (0.7922, 0.0, 0.0), (0.8431, 0.1753, 0.1753), (0.898, 0.5, 0.5), (1.0, 0.9725, 0.9725)), 'blue': ((0.0, 0.502, 0.502), (0.051, 0.0222, 0.0222), (0.1098, 1.0, 1.0), (0.2039, 1.0, 1.0), (0.2627, 0.6145, 0.6145), (0.3216, 0.0, 0.0), (0.4157, 0.0, 0.0), (0.4745, 0.2342, 0.2342), (0.5333, 0.0, 0.0), (0.5804, 0.0, 0.0), (0.6314, 0.0549, 0.0549), (0.6902, 0.0, 0.0), (0.7373, 0.0, 0.0), (0.7922, 0.9738, 0.9738), (0.8, 1.0, 1.0), (0.8431, 1.0, 1.0), (0.898, 0.9341, 0.9341), (1.0, 0.9961, 0.9961))} _gist_rainbow_data = ((0.0, (1.0, 0.0, 0.16)), (0.03, (1.0, 0.0, 0.0)), (0.215, (1.0, 1.0, 0.0)), (0.4, (0.0, 1.0, 0.0)), (0.586, (0.0, 1.0, 1.0)), (0.77, (0.0, 0.0, 1.0)), (0.954, (1.0, 0.0, 1.0)), (1.0, (1.0, 0.0, 0.75))) _gist_stern_data = {'red': ((0.0, 0.0, 0.0), (0.0547, 1.0, 1.0), (0.25, 0.027, 0.25), (1.0, 1.0, 1.0)), 'green': ((0, 0, 0), (1, 1, 1)), 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (0.735, 0.0, 0.0), (1.0, 1.0, 1.0))} def _gist_yarg(x): return 1 - x _gist_yarg_data = {'red': _gist_yarg, 'green': _gist_yarg, 'blue': _gist_yarg} _coolwarm_data = {'red': [(0.0, 0.2298057, 0.2298057), (0.03125, 0.26623388, 0.26623388), (0.0625, 0.30386891, 0.30386891), (0.09375, 0.342804478, 0.342804478), (0.125, 0.38301334, 0.38301334), (0.15625, 0.424369608, 0.424369608), (0.1875, 0.46666708, 0.46666708), (0.21875, 0.509635204, 0.509635204), (0.25, 0.552953156, 0.552953156), (0.28125, 0.596262162, 0.596262162), (0.3125, 0.639176211, 0.639176211), (0.34375, 0.681291281, 0.681291281), (0.375, 0.722193294, 0.722193294), (0.40625, 0.761464949, 0.761464949), (0.4375, 0.798691636, 0.798691636), (0.46875, 0.833466556, 0.833466556), (0.5, 0.865395197, 0.865395197), (0.53125, 0.897787179, 0.897787179), (0.5625, 0.924127593, 0.924127593), (0.59375, 0.944468518, 0.944468518), (0.625, 0.958852946, 0.958852946), (0.65625, 0.96732803, 0.96732803), (0.6875, 0.969954137, 0.969954137), (0.71875, 0.966811177, 0.966811177), (0.75, 0.958003065, 0.958003065), (0.78125, 0.943660866, 0.943660866), (0.8125, 0.923944917, 0.923944917), (0.84375, 0.89904617, 0.89904617), (0.875, 0.869186849, 0.869186849), (0.90625, 0.834620542, 0.834620542), (0.9375, 0.795631745, 0.795631745), (0.96875, 0.752534934, 0.752534934), (1.0, 0.705673158, 0.705673158)], 'green': [(0.0, 0.298717966, 0.298717966), (0.03125, 0.353094838, 0.353094838), (0.0625, 0.406535296, 0.406535296), (0.09375, 0.458757618, 0.458757618), (0.125, 0.50941904, 0.50941904), (0.15625, 0.558148092, 0.558148092), (0.1875, 0.604562568, 0.604562568), (0.21875, 0.648280772, 0.648280772), (0.25, 0.688929332, 0.688929332), (0.28125, 0.726149107, 0.726149107), (0.3125, 0.759599947, 0.759599947), (0.34375, 0.788964712, 0.788964712), (0.375, 0.813952739, 0.813952739), (0.40625, 0.834302879, 0.834302879), (0.4375, 0.849786142, 0.849786142), (0.46875, 0.860207984, 0.860207984), (0.5, 0.86541021, 0.86541021), (0.53125, 0.848937047, 0.848937047), (0.5625, 0.827384882, 0.827384882), (0.59375, 0.800927443, 0.800927443), (0.625, 0.769767752, 0.769767752), (0.65625, 0.734132809, 0.734132809), (0.6875, 0.694266682, 0.694266682), (0.71875, 0.650421156, 0.650421156), (0.75, 0.602842431, 0.602842431), (0.78125, 0.551750968, 0.551750968), (0.8125, 0.49730856, 0.49730856), (0.84375, 0.439559467, 0.439559467), (0.875, 0.378313092, 0.378313092), (0.90625, 0.312874446, 0.312874446), (0.9375, 0.24128379, 0.24128379), (0.96875, 0.157246067, 0.157246067), (1.0, 0.01555616, 0.01555616)], 'blue': [(0.0, 0.753683153, 0.753683153), (0.03125, 0.801466763, 0.801466763), (0.0625, 0.84495867, 0.84495867), (0.09375, 0.883725899, 0.883725899), (0.125, 0.917387822, 0.917387822), (0.15625, 0.945619588, 0.945619588), (0.1875, 0.968154911, 0.968154911), (0.21875, 0.98478814, 0.98478814), (0.25, 0.995375608, 0.995375608), (0.28125, 0.999836203, 0.999836203), (0.3125, 0.998151185, 0.998151185), (0.34375, 0.990363227, 0.990363227), (0.375, 0.976574709, 0.976574709), (0.40625, 0.956945269, 0.956945269), (0.4375, 0.931688648, 0.931688648), (0.46875, 0.901068838, 0.901068838), (0.5, 0.865395561, 0.865395561), (0.53125, 0.820880546, 0.820880546), (0.5625, 0.774508472, 0.774508472), (0.59375, 0.726736146, 0.726736146), (0.625, 0.678007945, 0.678007945), (0.65625, 0.628751763, 0.628751763), (0.6875, 0.579375448, 0.579375448), (0.71875, 0.530263762, 0.530263762), (0.75, 0.481775914, 0.481775914), (0.78125, 0.434243684, 0.434243684), (0.8125, 0.387970225, 0.387970225), (0.84375, 0.343229596, 0.343229596), (0.875, 0.300267182, 0.300267182), (0.90625, 0.259301199, 0.259301199), (0.9375, 0.220525627, 0.220525627), (0.96875, 0.184115123, 0.184115123), (1.0, 0.150232812, 0.150232812)]} _CMRmap_data = {'red': ((0.0, 0.0, 0.0), (0.125, 0.15, 0.15), (0.25, 0.3, 0.3), (0.375, 0.6, 0.6), (0.5, 1.0, 1.0), (0.625, 0.9, 0.9), (0.75, 0.9, 0.9), (0.875, 0.9, 0.9), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.125, 0.15, 0.15), (0.25, 0.15, 0.15), (0.375, 0.2, 0.2), (0.5, 0.25, 0.25), (0.625, 0.5, 0.5), (0.75, 0.75, 0.75), (0.875, 0.9, 0.9), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (0.125, 0.5, 0.5), (0.25, 0.75, 0.75), (0.375, 0.5, 0.5), (0.5, 0.15, 0.15), (0.625, 0.0, 0.0), (0.75, 0.1, 0.1), (0.875, 0.5, 0.5), (1.0, 1.0, 1.0))} _wistia_data = {'red': [(0.0, 0.8941176470588236, 0.8941176470588236), (0.25, 1.0, 1.0), (0.5, 1.0, 1.0), (0.75, 1.0, 1.0), (1.0, 0.9882352941176471, 0.9882352941176471)], 'green': [(0.0, 1.0, 1.0), (0.25, 0.9098039215686274, 0.9098039215686274), (0.5, 0.7411764705882353, 0.7411764705882353), (0.75, 0.6274509803921569, 0.6274509803921569), (1.0, 0.4980392156862745, 0.4980392156862745)], 'blue': [(0.0, 0.47843137254901963, 0.47843137254901963), (0.25, 0.10196078431372549, 0.10196078431372549), (0.5, 0.0, 0.0), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)]} _tab10_data = ((0.12156862745098039, 0.4666666666666667, 0.7058823529411765), (1.0, 0.4980392156862745, 0.054901960784313725), (0.17254901960784313, 0.6274509803921569, 0.17254901960784313), (0.8392156862745098, 0.15294117647058825, 0.1568627450980392), (0.5803921568627451, 0.403921568627451, 0.7411764705882353), (0.5490196078431373, 0.33725490196078434, 0.29411764705882354), (0.8901960784313725, 0.4666666666666667, 0.7607843137254902), (0.4980392156862745, 0.4980392156862745, 0.4980392156862745), (0.7372549019607844, 0.7411764705882353, 0.13333333333333333), (0.09019607843137255, 0.7450980392156863, 0.8117647058823529)) _tab20_data = ((0.12156862745098039, 0.4666666666666667, 0.7058823529411765), (0.6823529411764706, 0.7803921568627451, 0.9098039215686274), (1.0, 0.4980392156862745, 0.054901960784313725), (1.0, 0.7333333333333333, 0.47058823529411764), (0.17254901960784313, 0.6274509803921569, 0.17254901960784313), (0.596078431372549, 0.8745098039215686, 0.5411764705882353), (0.8392156862745098, 0.15294117647058825, 0.1568627450980392), (1.0, 0.596078431372549, 0.5882352941176471), (0.5803921568627451, 0.403921568627451, 0.7411764705882353), (0.7725490196078432, 0.6901960784313725, 0.8352941176470589), (0.5490196078431373, 0.33725490196078434, 0.29411764705882354), (0.7686274509803922, 0.611764705882353, 0.5803921568627451), (0.8901960784313725, 0.4666666666666667, 0.7607843137254902), (0.9686274509803922, 0.7137254901960784, 0.8235294117647058), (0.4980392156862745, 0.4980392156862745, 0.4980392156862745), (0.7803921568627451, 0.7803921568627451, 0.7803921568627451), (0.7372549019607844, 0.7411764705882353, 0.13333333333333333), (0.8588235294117647, 0.8588235294117647, 0.5529411764705883), (0.09019607843137255, 0.7450980392156863, 0.8117647058823529), (0.6196078431372549, 0.8549019607843137, 0.8980392156862745)) _tab20b_data = ((0.2235294117647059, 0.23137254901960785, 0.4745098039215686), (0.3215686274509804, 0.32941176470588235, 0.6392156862745098), (0.4196078431372549, 0.43137254901960786, 0.8117647058823529), (0.611764705882353, 0.6196078431372549, 0.8705882352941177), (0.38823529411764707, 0.4745098039215686, 0.2235294117647059), (0.5490196078431373, 0.6352941176470588, 0.3215686274509804), (0.7098039215686275, 0.8117647058823529, 0.4196078431372549), (0.807843137254902, 0.8588235294117647, 0.611764705882353), (0.5490196078431373, 0.42745098039215684, 0.19215686274509805), (0.7411764705882353, 0.6196078431372549, 0.2235294117647059), (0.9058823529411765, 0.7294117647058823, 0.3215686274509804), (0.9058823529411765, 0.796078431372549, 0.5803921568627451), (0.5176470588235295, 0.23529411764705882, 0.2235294117647059), (0.6784313725490196, 0.28627450980392155, 0.2901960784313726), (0.8392156862745098, 0.3803921568627451, 0.4196078431372549), (0.9058823529411765, 0.5882352941176471, 0.611764705882353), (0.4823529411764706, 0.2549019607843137, 0.45098039215686275), (0.6470588235294118, 0.3176470588235294, 0.5803921568627451), (0.807843137254902, 0.42745098039215684, 0.7411764705882353), (0.8705882352941177, 0.6196078431372549, 0.8392156862745098)) _tab20c_data = ((0.19215686274509805, 0.5098039215686274, 0.7411764705882353), (0.4196078431372549, 0.6823529411764706, 0.8392156862745098), (0.6196078431372549, 0.792156862745098, 0.8823529411764706), (0.7764705882352941, 0.8588235294117647, 0.9372549019607843), (0.9019607843137255, 0.3333333333333333, 0.050980392156862744), (0.9921568627450981, 0.5529411764705883, 0.23529411764705882), (0.9921568627450981, 0.6823529411764706, 0.4196078431372549), (0.9921568627450981, 0.8156862745098039, 0.6352941176470588), (0.19215686274509805, 0.6392156862745098, 0.32941176470588235), (0.4549019607843137, 0.7686274509803922, 0.4627450980392157), (0.6313725490196078, 0.8509803921568627, 0.6078431372549019), (0.7803921568627451, 0.9137254901960784, 0.7529411764705882), (0.4588235294117647, 0.4196078431372549, 0.6941176470588235), (0.6196078431372549, 0.6039215686274509, 0.7843137254901961), (0.7372549019607844, 0.7411764705882353, 0.8627450980392157), (0.8549019607843137, 0.8549019607843137, 0.9215686274509803), (0.38823529411764707, 0.38823529411764707, 0.38823529411764707), (0.5882352941176471, 0.5882352941176471, 0.5882352941176471), (0.7411764705882353, 0.7411764705882353, 0.7411764705882353), (0.8509803921568627, 0.8509803921568627, 0.8509803921568627)) _petroff10_data = ((0.24705882352941178, 0.5647058823529412, 0.8549019607843137), (1.0, 0.6627450980392157, 0.054901960784313725), (0.7411764705882353, 0.12156862745098039, 0.00392156862745098), (0.5803921568627451, 0.6431372549019608, 0.6352941176470588), (0.5137254901960784, 0.17647058823529413, 0.7137254901960784), (0.6627450980392157, 0.4196078431372549, 0.34901960784313724), (0.9058823529411765, 0.38823529411764707, 0.0), (0.7254901960784313, 0.6745098039215687, 0.4392156862745098), (0.44313725490196076, 0.4588235294117647, 0.5058823529411764), (0.5725490196078431, 0.8549019607843137, 0.8666666666666667)) datad = {'Blues': _Blues_data, 'BrBG': _BrBG_data, 'BuGn': _BuGn_data, 'BuPu': _BuPu_data, 'CMRmap': _CMRmap_data, 'GnBu': _GnBu_data, 'Greens': _Greens_data, 'Greys': _Greys_data, 'OrRd': _OrRd_data, 'Oranges': _Oranges_data, 'PRGn': _PRGn_data, 'PiYG': _PiYG_data, 'PuBu': _PuBu_data, 'PuBuGn': _PuBuGn_data, 'PuOr': _PuOr_data, 'PuRd': _PuRd_data, 'Purples': _Purples_data, 'RdBu': _RdBu_data, 'RdGy': _RdGy_data, 'RdPu': _RdPu_data, 'RdYlBu': _RdYlBu_data, 'RdYlGn': _RdYlGn_data, 'Reds': _Reds_data, 'Spectral': _Spectral_data, 'Wistia': _wistia_data, 'YlGn': _YlGn_data, 'YlGnBu': _YlGnBu_data, 'YlOrBr': _YlOrBr_data, 'YlOrRd': _YlOrRd_data, 'afmhot': _afmhot_data, 'autumn': _autumn_data, 'binary': _binary_data, 'bone': _bone_data, 'brg': _brg_data, 'bwr': _bwr_data, 'cool': _cool_data, 'coolwarm': _coolwarm_data, 'copper': _copper_data, 'cubehelix': _cubehelix_data, 'flag': _flag_data, 'gist_earth': _gist_earth_data, 'gist_gray': _gist_gray_data, 'gist_heat': _gist_heat_data, 'gist_ncar': _gist_ncar_data, 'gist_rainbow': _gist_rainbow_data, 'gist_stern': _gist_stern_data, 'gist_yarg': _gist_yarg_data, 'gnuplot': _gnuplot_data, 'gnuplot2': _gnuplot2_data, 'gray': _gray_data, 'hot': _hot_data, 'hsv': _hsv_data, 'jet': _jet_data, 'nipy_spectral': _nipy_spectral_data, 'ocean': _ocean_data, 'pink': _pink_data, 'prism': _prism_data, 'rainbow': _rainbow_data, 'seismic': _seismic_data, 'spring': _spring_data, 'summer': _summer_data, 'terrain': _terrain_data, 'winter': _winter_data, 'Accent': {'listed': _Accent_data}, 'Dark2': {'listed': _Dark2_data}, 'Paired': {'listed': _Paired_data}, 'Pastel1': {'listed': _Pastel1_data}, 'Pastel2': {'listed': _Pastel2_data}, 'Set1': {'listed': _Set1_data}, 'Set2': {'listed': _Set2_data}, 'Set3': {'listed': _Set3_data}, 'tab10': {'listed': _tab10_data}, 'tab20': {'listed': _tab20_data}, 'tab20b': {'listed': _tab20b_data}, 'tab20c': {'listed': _tab20c_data}} # File: matplotlib-main/lib/matplotlib/_cm_bivar.py import numpy as np from matplotlib.colors import SegmentedBivarColormap BiPeak = np.array([0.0, 0.674, 0.931, 0.0, 0.68, 0.922, 0.0, 0.685, 0.914, 0.0, 0.691, 0.906, 0.0, 0.696, 0.898, 0.0, 0.701, 0.89, 0.0, 0.706, 0.882, 0.0, 0.711, 0.875, 0.0, 0.715, 0.867, 0.0, 0.72, 0.86, 0.0, 0.725, 0.853, 0.0, 0.729, 0.845, 0.0, 0.733, 0.838, 0.0, 0.737, 0.831, 0.0, 0.741, 0.824, 0.0, 0.745, 0.816, 0.0, 0.749, 0.809, 0.0, 0.752, 0.802, 0.0, 0.756, 0.794, 0.0, 0.759, 0.787, 0.0, 0.762, 0.779, 0.0, 0.765, 0.771, 0.0, 0.767, 0.764, 0.0, 0.77, 0.755, 0.0, 0.772, 0.747, 0.0, 0.774, 0.739, 0.0, 0.776, 0.73, 0.0, 0.777, 0.721, 0.0, 0.779, 0.712, 0.021, 0.78, 0.702, 0.055, 0.781, 0.693, 0.079, 0.782, 0.682, 0.097, 0.782, 0.672, 0.111, 0.782, 0.661, 0.122, 0.782, 0.65, 0.132, 0.782, 0.639, 0.14, 0.781, 0.627, 0.147, 0.781, 0.615, 0.154, 0.78, 0.602, 0.159, 0.778, 0.589, 0.164, 0.777, 0.576, 0.169, 0.775, 0.563, 0.173, 0.773, 0.549, 0.177, 0.771, 0.535, 0.18, 0.768, 0.52, 0.184, 0.766, 0.505, 0.187, 0.763, 0.49, 0.19, 0.76, 0.474, 0.193, 0.756, 0.458, 0.196, 0.753, 0.442, 0.2, 0.749, 0.425, 0.203, 0.745, 0.408, 0.206, 0.741, 0.391, 0.21, 0.736, 0.373, 0.213, 0.732, 0.355, 0.216, 0.727, 0.337, 0.22, 0.722, 0.318, 0.224, 0.717, 0.298, 0.227, 0.712, 0.278, 0.231, 0.707, 0.258, 0.235, 0.701, 0.236, 0.239, 0.696, 0.214, 0.242, 0.69, 0.19, 0.246, 0.684, 0.165, 0.25, 0.678, 0.136, 0.0, 0.675, 0.934, 0.0, 0.681, 0.925, 0.0, 0.687, 0.917, 0.0, 0.692, 0.909, 0.0, 0.697, 0.901, 0.0, 0.703, 0.894, 0.0, 0.708, 0.886, 0.0, 0.713, 0.879, 0.0, 0.718, 0.872, 0.0, 0.722, 0.864, 0.0, 0.727, 0.857, 0.0, 0.731, 0.85, 0.0, 0.736, 0.843, 0.0, 0.74, 0.836, 0.0, 0.744, 0.829, 0.0, 0.748, 0.822, 0.0, 0.752, 0.815, 0.0, 0.755, 0.808, 0.0, 0.759, 0.8, 0.0, 0.762, 0.793, 0.0, 0.765, 0.786, 0.0, 0.768, 0.778, 0.0, 0.771, 0.77, 0.0, 0.773, 0.762, 0.051, 0.776, 0.754, 0.087, 0.778, 0.746, 0.111, 0.78, 0.737, 0.131, 0.782, 0.728, 0.146, 0.783, 0.719, 0.159, 0.784, 0.71, 0.171, 0.785, 0.7, 0.18, 0.786, 0.69, 0.189, 0.786, 0.68, 0.196, 0.787, 0.669, 0.202, 0.787, 0.658, 0.208, 0.786, 0.647, 0.213, 0.786, 0.635, 0.217, 0.785, 0.623, 0.221, 0.784, 0.61, 0.224, 0.782, 0.597, 0.227, 0.781, 0.584, 0.23, 0.779, 0.57, 0.232, 0.777, 0.556, 0.234, 0.775, 0.542, 0.236, 0.772, 0.527, 0.238, 0.769, 0.512, 0.24, 0.766, 0.497, 0.242, 0.763, 0.481, 0.244, 0.76, 0.465, 0.246, 0.756, 0.448, 0.248, 0.752, 0.432, 0.25, 0.748, 0.415, 0.252, 0.744, 0.397, 0.254, 0.739, 0.379, 0.256, 0.735, 0.361, 0.259, 0.73, 0.343, 0.261, 0.725, 0.324, 0.264, 0.72, 0.304, 0.266, 0.715, 0.284, 0.269, 0.709, 0.263, 0.271, 0.704, 0.242, 0.274, 0.698, 0.22, 0.277, 0.692, 0.196, 0.28, 0.686, 0.17, 0.283, 0.68, 0.143, 0.0, 0.676, 0.937, 0.0, 0.682, 0.928, 0.0, 0.688, 0.92, 0.0, 0.694, 0.913, 0.0, 0.699, 0.905, 0.0, 0.704, 0.897, 0.0, 0.71, 0.89, 0.0, 0.715, 0.883, 0.0, 0.72, 0.876, 0.0, 0.724, 0.869, 0.0, 0.729, 0.862, 0.0, 0.734, 0.855, 0.0, 0.738, 0.848, 0.0, 0.743, 0.841, 0.0, 0.747, 0.834, 0.0, 0.751, 0.827, 0.0, 0.755, 0.82, 0.0, 0.759, 0.813, 0.0, 0.762, 0.806, 0.003, 0.766, 0.799, 0.066, 0.769, 0.792, 0.104, 0.772, 0.784, 0.131, 0.775, 0.777, 0.152, 0.777, 0.769, 0.17, 0.78, 0.761, 0.185, 0.782, 0.753, 0.198, 0.784, 0.744, 0.209, 0.786, 0.736, 0.219, 0.787, 0.727, 0.228, 0.788, 0.717, 0.236, 0.789, 0.708, 0.243, 0.79, 0.698, 0.249, 0.791, 0.688, 0.254, 0.791, 0.677, 0.259, 0.791, 0.666, 0.263, 0.791, 0.654, 0.266, 0.79, 0.643, 0.269, 0.789, 0.631, 0.272, 0.788, 0.618, 0.274, 0.787, 0.605, 0.276, 0.785, 0.592, 0.278, 0.783, 0.578, 0.279, 0.781, 0.564, 0.28, 0.779, 0.549, 0.282, 0.776, 0.535, 0.283, 0.773, 0.519, 0.284, 0.77, 0.504, 0.285, 0.767, 0.488, 0.286, 0.763, 0.472, 0.287, 0.759, 0.455, 0.288, 0.756, 0.438, 0.289, 0.751, 0.421, 0.291, 0.747, 0.403, 0.292, 0.742, 0.385, 0.293, 0.738, 0.367, 0.295, 0.733, 0.348, 0.296, 0.728, 0.329, 0.298, 0.723, 0.31, 0.3, 0.717, 0.29, 0.302, 0.712, 0.269, 0.304, 0.706, 0.247, 0.306, 0.7, 0.225, 0.308, 0.694, 0.201, 0.31, 0.688, 0.176, 0.312, 0.682, 0.149, 0.0, 0.678, 0.939, 0.0, 0.683, 0.931, 0.0, 0.689, 0.923, 0.0, 0.695, 0.916, 0.0, 0.701, 0.908, 0.0, 0.706, 0.901, 0.0, 0.711, 0.894, 0.0, 0.717, 0.887, 0.0, 0.722, 0.88, 0.0, 0.727, 0.873, 0.0, 0.732, 0.866, 0.0, 0.736, 0.859, 0.0, 0.741, 0.853, 0.0, 0.745, 0.846, 0.0, 0.75, 0.839, 0.0, 0.754, 0.833, 0.035, 0.758, 0.826, 0.091, 0.762, 0.819, 0.126, 0.765, 0.812, 0.153, 0.769, 0.805, 0.174, 0.772, 0.798, 0.193, 0.775, 0.791, 0.209, 0.778, 0.783, 0.223, 0.781, 0.776, 0.236, 0.784, 0.768, 0.247, 0.786, 0.76, 0.257, 0.788, 0.752, 0.266, 0.79, 0.743, 0.273, 0.791, 0.734, 0.28, 0.793, 0.725, 0.287, 0.794, 0.715, 0.292, 0.794, 0.706, 0.297, 0.795, 0.695, 0.301, 0.795, 0.685, 0.305, 0.795, 0.674, 0.308, 0.795, 0.662, 0.31, 0.794, 0.651, 0.312, 0.794, 0.638, 0.314, 0.792, 0.626, 0.316, 0.791, 0.613, 0.317, 0.789, 0.599, 0.318, 0.787, 0.586, 0.319, 0.785, 0.571, 0.32, 0.783, 0.557, 0.32, 0.78, 0.542, 0.321, 0.777, 0.527, 0.321, 0.774, 0.511, 0.322, 0.77, 0.495, 0.322, 0.767, 0.478, 0.323, 0.763, 0.462, 0.323, 0.759, 0.445, 0.324, 0.755, 0.427, 0.325, 0.75, 0.41, 0.325, 0.745, 0.391, 0.326, 0.741, 0.373, 0.327, 0.736, 0.354, 0.328, 0.73, 0.335, 0.329, 0.725, 0.315, 0.33, 0.72, 0.295, 0.331, 0.714, 0.274, 0.333, 0.708, 0.253, 0.334, 0.702, 0.23, 0.336, 0.696, 0.207, 0.337, 0.69, 0.182, 0.339, 0.684, 0.154, 0.0, 0.679, 0.942, 0.0, 0.685, 0.934, 0.0, 0.691, 0.927, 0.0, 0.696, 0.919, 0.0, 0.702, 0.912, 0.0, 0.708, 0.905, 0.0, 0.713, 0.898, 0.0, 0.718, 0.891, 0.0, 0.724, 0.884, 0.0, 0.729, 0.877, 0.0, 0.734, 0.871, 0.0, 0.739, 0.864, 0.0, 0.743, 0.857, 0.035, 0.748, 0.851, 0.096, 0.752, 0.844, 0.133, 0.757, 0.838, 0.161, 0.761, 0.831, 0.185, 0.765, 0.825, 0.205, 0.769, 0.818, 0.223, 0.772, 0.811, 0.238, 0.776, 0.804, 0.252, 0.779, 0.797, 0.265, 0.782, 0.79, 0.276, 0.785, 0.783, 0.286, 0.788, 0.775, 0.296, 0.79, 0.767, 0.304, 0.792, 0.759, 0.311, 0.794, 0.751, 0.318, 0.796, 0.742, 0.324, 0.797, 0.733, 0.329, 0.798, 0.723, 0.334, 0.799, 0.714, 0.338, 0.799, 0.703, 0.341, 0.8, 0.693, 0.344, 0.8, 0.682, 0.347, 0.799, 0.67, 0.349, 0.799, 0.659, 0.351, 0.798, 0.646, 0.352, 0.797, 0.634, 0.353, 0.795, 0.621, 0.354, 0.794, 0.607, 0.354, 0.792, 0.593, 0.355, 0.789, 0.579, 0.355, 0.787, 0.564, 0.355, 0.784, 0.549, 0.355, 0.781, 0.534, 0.355, 0.778, 0.518, 0.355, 0.774, 0.502, 0.355, 0.77, 0.485, 0.355, 0.766, 0.468, 0.355, 0.762, 0.451, 0.355, 0.758, 0.434, 0.355, 0.753, 0.416, 0.356, 0.748, 0.397, 0.356, 0.743, 0.379, 0.356, 0.738, 0.36, 0.357, 0.733, 0.34, 0.357, 0.728, 0.321, 0.358, 0.722, 0.3, 0.359, 0.716, 0.279, 0.36, 0.71, 0.258, 0.361, 0.704, 0.235, 0.361, 0.698, 0.212, 0.362, 0.692, 0.187, 0.363, 0.686, 0.16, 0.0, 0.68, 0.945, 0.0, 0.686, 0.937, 0.0, 0.692, 0.93, 0.0, 0.698, 0.922, 0.0, 0.703, 0.915, 0.0, 0.709, 0.908, 0.0, 0.715, 0.901, 0.0, 0.72, 0.894, 0.0, 0.726, 0.888, 0.0, 0.731, 0.881, 0.007, 0.736, 0.875, 0.084, 0.741, 0.869, 0.127, 0.746, 0.862, 0.159, 0.751, 0.856, 0.185, 0.755, 0.85, 0.208, 0.76, 0.843, 0.227, 0.764, 0.837, 0.245, 0.768, 0.83, 0.26, 0.772, 0.824, 0.275, 0.776, 0.817, 0.288, 0.779, 0.811, 0.3, 0.783, 0.804, 0.31, 0.786, 0.797, 0.32, 0.789, 0.789, 0.329, 0.792, 0.782, 0.337, 0.794, 0.774, 0.345, 0.796, 0.766, 0.351, 0.798, 0.758, 0.357, 0.8, 0.749, 0.363, 0.801, 0.74, 0.367, 0.803, 0.731, 0.371, 0.803, 0.721, 0.375, 0.804, 0.711, 0.378, 0.804, 0.701, 0.38, 0.804, 0.69, 0.382, 0.804, 0.679, 0.384, 0.803, 0.667, 0.385, 0.802, 0.654, 0.386, 0.801, 0.642, 0.386, 0.8, 0.629, 0.387, 0.798, 0.615, 0.387, 0.796, 0.601, 0.387, 0.793, 0.587, 0.387, 0.791, 0.572, 0.387, 0.788, 0.557, 0.386, 0.785, 0.541, 0.386, 0.781, 0.525, 0.385, 0.778, 0.509, 0.385, 0.774, 0.492, 0.385, 0.77, 0.475, 0.384, 0.765, 0.457, 0.384, 0.761, 0.44, 0.384, 0.756, 0.422, 0.384, 0.751, 0.403, 0.384, 0.746, 0.384, 0.384, 0.741, 0.365, 0.384, 0.735, 0.346, 0.384, 0.73, 0.326, 0.384, 0.724, 0.305, 0.384, 0.718, 0.284, 0.385, 0.712, 0.263, 0.385, 0.706, 0.24, 0.386, 0.7, 0.217, 0.386, 0.694, 0.192, 0.387, 0.687, 0.165, 0.0, 0.68, 0.948, 0.0, 0.687, 0.94, 0.0, 0.693, 0.933, 0.0, 0.699, 0.925, 0.0, 0.705, 0.918, 0.0, 0.711, 0.912, 0.0, 0.716, 0.905, 0.0, 0.722, 0.898, 0.05, 0.728, 0.892, 0.109, 0.733, 0.886, 0.147, 0.738, 0.879, 0.177, 0.743, 0.873, 0.202, 0.748, 0.867, 0.224, 0.753, 0.861, 0.243, 0.758, 0.855, 0.261, 0.763, 0.849, 0.277, 0.767, 0.842, 0.292, 0.771, 0.836, 0.305, 0.775, 0.83, 0.318, 0.779, 0.823, 0.329, 0.783, 0.817, 0.34, 0.787, 0.81, 0.35, 0.79, 0.803, 0.359, 0.793, 0.796, 0.367, 0.796, 0.789, 0.374, 0.798, 0.782, 0.381, 0.801, 0.774, 0.387, 0.803, 0.766, 0.393, 0.804, 0.757, 0.397, 0.806, 0.748, 0.402, 0.807, 0.739, 0.405, 0.808, 0.729, 0.408, 0.809, 0.719, 0.411, 0.809, 0.709, 0.413, 0.809, 0.698, 0.415, 0.808, 0.687, 0.416, 0.808, 0.675, 0.417, 0.807, 0.663, 0.417, 0.806, 0.65, 0.417, 0.804, 0.637, 0.418, 0.802, 0.623, 0.417, 0.8, 0.609, 0.417, 0.798, 0.594, 0.416, 0.795, 0.579, 0.416, 0.792, 0.564, 0.415, 0.789, 0.548, 0.414, 0.785, 0.532, 0.414, 0.781, 0.515, 0.413, 0.777, 0.499, 0.412, 0.773, 0.481, 0.412, 0.769, 0.464, 0.411, 0.764, 0.446, 0.41, 0.759, 0.428, 0.41, 0.754, 0.409, 0.409, 0.749, 0.39, 0.409, 0.743, 0.371, 0.409, 0.738, 0.351, 0.409, 0.732, 0.331, 0.408, 0.726, 0.31, 0.408, 0.72, 0.289, 0.408, 0.714, 0.268, 0.408, 0.708, 0.245, 0.409, 0.702, 0.222, 0.409, 0.695, 0.197, 0.409, 0.689, 0.17, 0.0, 0.681, 0.95, 0.0, 0.688, 0.943, 0.0, 0.694, 0.936, 0.0, 0.7, 0.929, 0.0, 0.706, 0.922, 0.0, 0.712, 0.915, 0.074, 0.718, 0.908, 0.124, 0.724, 0.902, 0.159, 0.73, 0.896, 0.188, 0.735, 0.89, 0.213, 0.74, 0.884, 0.235, 0.746, 0.878, 0.255, 0.751, 0.872, 0.273, 0.756, 0.866, 0.289, 0.761, 0.86, 0.305, 0.766, 0.854, 0.319, 0.77, 0.848, 0.332, 0.775, 0.842, 0.344, 0.779, 0.836, 0.356, 0.783, 0.83, 0.366, 0.787, 0.823, 0.376, 0.79, 0.817, 0.385, 0.794, 0.81, 0.394, 0.797, 0.803, 0.401, 0.8, 0.796, 0.408, 0.802, 0.789, 0.414, 0.805, 0.781, 0.42, 0.807, 0.773, 0.425, 0.809, 0.765, 0.43, 0.81, 0.756, 0.433, 0.812, 0.747, 0.437, 0.813, 0.738, 0.44, 0.813, 0.728, 0.442, 0.814, 0.717, 0.444, 0.813, 0.706, 0.445, 0.813, 0.695, 0.446, 0.812, 0.683, 0.446, 0.811, 0.671, 0.447, 0.81, 0.658, 0.447, 0.809, 0.645, 0.446, 0.807, 0.631, 0.446, 0.804, 0.617, 0.445, 0.802, 0.602, 0.444, 0.799, 0.587, 0.443, 0.796, 0.571, 0.442, 0.792, 0.555, 0.441, 0.789, 0.539, 0.44, 0.785, 0.522, 0.439, 0.781, 0.505, 0.438, 0.776, 0.488, 0.437, 0.772, 0.47, 0.436, 0.767, 0.452, 0.435, 0.762, 0.433, 0.435, 0.757, 0.415, 0.434, 0.751, 0.396, 0.433, 0.746, 0.376, 0.432, 0.74, 0.356, 0.432, 0.734, 0.336, 0.431, 0.728, 0.315, 0.431, 0.722, 0.294, 0.431, 0.716, 0.272, 0.43, 0.71, 0.25, 0.43, 0.703, 0.226, 0.43, 0.697, 0.201, 0.43, 0.69, 0.175, 0.0, 0.682, 0.953, 0.0, 0.689, 0.946, 0.0, 0.695, 0.938, 0.002, 0.701, 0.932, 0.086, 0.708, 0.925, 0.133, 0.714, 0.918, 0.167, 0.72, 0.912, 0.196, 0.726, 0.906, 0.221, 0.731, 0.9, 0.243, 0.737, 0.894, 0.263, 0.743, 0.888, 0.281, 0.748, 0.882, 0.298, 0.753, 0.876, 0.314, 0.759, 0.87, 0.329, 0.764, 0.865, 0.342, 0.768, 0.859, 0.355, 0.773, 0.853, 0.368, 0.778, 0.847, 0.379, 0.782, 0.842, 0.39, 0.786, 0.836, 0.4, 0.79, 0.83, 0.409, 0.794, 0.823, 0.417, 0.798, 0.817, 0.425, 0.801, 0.81, 0.433, 0.804, 0.803, 0.439, 0.807, 0.796, 0.445, 0.809, 0.789, 0.451, 0.811, 0.781, 0.456, 0.813, 0.773, 0.46, 0.815, 0.764, 0.463, 0.816, 0.755, 0.466, 0.817, 0.746, 0.469, 0.818, 0.736, 0.471, 0.818, 0.725, 0.472, 0.818, 0.715, 0.473, 0.818, 0.703, 0.474, 0.817, 0.691, 0.474, 0.816, 0.679, 0.474, 0.815, 0.666, 0.474, 0.813, 0.653, 0.473, 0.811, 0.639, 0.473, 0.809, 0.624, 0.472, 0.806, 0.61, 0.471, 0.803, 0.594, 0.469, 0.8, 0.579, 0.468, 0.796, 0.562, 0.467, 0.792, 0.546, 0.466, 0.788, 0.529, 0.464, 0.784, 0.512, 0.463, 0.78, 0.494, 0.462, 0.775, 0.476, 0.46, 0.77, 0.458, 0.459, 0.765, 0.439, 0.458, 0.759, 0.42, 0.457, 0.754, 0.401, 0.456, 0.748, 0.381, 0.455, 0.742, 0.361, 0.454, 0.736, 0.341, 0.453, 0.73, 0.32, 0.453, 0.724, 0.299, 0.452, 0.718, 0.277, 0.452, 0.711, 0.254, 0.451, 0.705, 0.231, 0.451, 0.698, 0.206, 0.45, 0.691, 0.179, 0.0, 0.683, 0.955, 0.013, 0.689, 0.948, 0.092, 0.696, 0.941, 0.137, 0.702, 0.935, 0.171, 0.709, 0.928, 0.2, 0.715, 0.922, 0.225, 0.721, 0.916, 0.247, 0.727, 0.909, 0.267, 0.733, 0.904, 0.286, 0.739, 0.898, 0.303, 0.745, 0.892, 0.32, 0.75, 0.886, 0.335, 0.756, 0.881, 0.35, 0.761, 0.875, 0.363, 0.766, 0.87, 0.376, 0.771, 0.864, 0.388, 0.776, 0.859, 0.4, 0.781, 0.853, 0.411, 0.785, 0.847, 0.421, 0.79, 0.842, 0.43, 0.794, 0.836, 0.439, 0.798, 0.83, 0.448, 0.802, 0.824, 0.455, 0.805, 0.817, 0.462, 0.808, 0.81, 0.469, 0.811, 0.804, 0.475, 0.814, 0.796, 0.48, 0.816, 0.789, 0.484, 0.818, 0.781, 0.488, 0.82, 0.772, 0.492, 0.821, 0.763, 0.495, 0.822, 0.754, 0.497, 0.823, 0.744, 0.499, 0.823, 0.734, 0.5, 0.823, 0.723, 0.501, 0.823, 0.712, 0.501, 0.822, 0.7, 0.501, 0.821, 0.687, 0.501, 0.819, 0.674, 0.5, 0.818, 0.661, 0.499, 0.815, 0.647, 0.498, 0.813, 0.632, 0.497, 0.81, 0.617, 0.496, 0.807, 0.602, 0.494, 0.804, 0.586, 0.493, 0.8, 0.569, 0.491, 0.796, 0.553, 0.49, 0.792, 0.536, 0.488, 0.787, 0.518, 0.486, 0.783, 0.5, 0.485, 0.778, 0.482, 0.483, 0.773, 0.463, 0.482, 0.767, 0.445, 0.48, 0.762, 0.425, 0.479, 0.756, 0.406, 0.478, 0.75, 0.386, 0.477, 0.744, 0.366, 0.476, 0.738, 0.345, 0.475, 0.732, 0.325, 0.474, 0.726, 0.303, 0.473, 0.719, 0.281, 0.472, 0.713, 0.258, 0.471, 0.706, 0.235, 0.47, 0.699, 0.21, 0.469, 0.692, 0.184, 0.095, 0.683, 0.958, 0.139, 0.69, 0.951, 0.173, 0.697, 0.944, 0.201, 0.703, 0.938, 0.226, 0.71, 0.931, 0.249, 0.716, 0.925, 0.269, 0.723, 0.919, 0.288, 0.729, 0.913, 0.306, 0.735, 0.907, 0.323, 0.741, 0.902, 0.339, 0.747, 0.896, 0.354, 0.752, 0.891, 0.368, 0.758, 0.885, 0.382, 0.764, 0.88, 0.394, 0.769, 0.875, 0.407, 0.774, 0.869, 0.418, 0.779, 0.864, 0.429, 0.784, 0.859, 0.44, 0.789, 0.853, 0.45, 0.793, 0.848, 0.459, 0.798, 0.842, 0.468, 0.802, 0.836, 0.476, 0.806, 0.83, 0.483, 0.809, 0.824, 0.49, 0.812, 0.818, 0.496, 0.815, 0.811, 0.502, 0.818, 0.804, 0.507, 0.821, 0.796, 0.512, 0.823, 0.789, 0.515, 0.825, 0.78, 0.519, 0.826, 0.772, 0.521, 0.827, 0.762, 0.524, 0.828, 0.753, 0.525, 0.828, 0.742, 0.526, 0.828, 0.732, 0.527, 0.828, 0.72, 0.527, 0.827, 0.708, 0.527, 0.826, 0.696, 0.526, 0.824, 0.683, 0.525, 0.822, 0.669, 0.524, 0.82, 0.655, 0.523, 0.817, 0.64, 0.522, 0.814, 0.625, 0.52, 0.811, 0.609, 0.518, 0.808, 0.593, 0.516, 0.804, 0.576, 0.515, 0.8, 0.559, 0.513, 0.795, 0.542, 0.511, 0.791, 0.524, 0.509, 0.786, 0.506, 0.507, 0.781, 0.488, 0.505, 0.775, 0.469, 0.504, 0.77, 0.45, 0.502, 0.764, 0.431, 0.5, 0.759, 0.411, 0.499, 0.753, 0.391, 0.497, 0.746, 0.371, 0.496, 0.74, 0.35, 0.495, 0.734, 0.329, 0.494, 0.727, 0.307, 0.492, 0.721, 0.285, 0.491, 0.714, 0.262, 0.49, 0.707, 0.239, 0.489, 0.7, 0.214, 0.488, 0.693, 0.188, 0.172, 0.684, 0.961, 0.201, 0.691, 0.954, 0.226, 0.698, 0.947, 0.248, 0.704, 0.941, 0.269, 0.711, 0.934, 0.289, 0.717, 0.928, 0.307, 0.724, 0.922, 0.324, 0.73, 0.917, 0.34, 0.736, 0.911, 0.356, 0.743, 0.906, 0.37, 0.749, 0.9, 0.384, 0.755, 0.895, 0.398, 0.76, 0.89, 0.411, 0.766, 0.885, 0.423, 0.772, 0.88, 0.435, 0.777, 0.874, 0.446, 0.782, 0.869, 0.457, 0.787, 0.864, 0.467, 0.792, 0.859, 0.477, 0.797, 0.854, 0.486, 0.801, 0.848, 0.494, 0.806, 0.843, 0.502, 0.81, 0.837, 0.51, 0.813, 0.831, 0.517, 0.817, 0.825, 0.523, 0.82, 0.818, 0.528, 0.823, 0.811, 0.533, 0.825, 0.804, 0.538, 0.828, 0.797, 0.542, 0.829, 0.788, 0.545, 0.831, 0.78, 0.547, 0.832, 0.771, 0.549, 0.833, 0.761, 0.551, 0.833, 0.751, 0.552, 0.833, 0.74, 0.552, 0.833, 0.729, 0.552, 0.832, 0.717, 0.551, 0.83, 0.704, 0.551, 0.829, 0.691, 0.55, 0.827, 0.677, 0.548, 0.824, 0.663, 0.547, 0.822, 0.648, 0.545, 0.819, 0.632, 0.543, 0.815, 0.617, 0.541, 0.812, 0.6, 0.539, 0.808, 0.583, 0.537, 0.803, 0.566, 0.535, 0.799, 0.549, 0.533, 0.794, 0.531, 0.531, 0.789, 0.512, 0.529, 0.784, 0.494, 0.527, 0.778, 0.475, 0.525, 0.773, 0.455, 0.523, 0.767, 0.436, 0.521, 0.761, 0.416, 0.519, 0.755, 0.396, 0.517, 0.748, 0.375, 0.516, 0.742, 0.354, 0.514, 0.735, 0.333, 0.513, 0.729, 0.311, 0.511, 0.722, 0.289, 0.51, 0.715, 0.266, 0.509, 0.708, 0.242, 0.507, 0.701, 0.218, 0.506, 0.694, 0.191, 0.224, 0.684, 0.963, 0.247, 0.691, 0.956, 0.268, 0.698, 0.95, 0.287, 0.705, 0.943, 0.305, 0.712, 0.937, 0.323, 0.719, 0.931, 0.339, 0.725, 0.926, 0.355, 0.732, 0.92, 0.37, 0.738, 0.915, 0.385, 0.744, 0.909, 0.399, 0.751, 0.904, 0.412, 0.757, 0.899, 0.425, 0.763, 0.894, 0.438, 0.768, 0.889, 0.45, 0.774, 0.884, 0.461, 0.78, 0.879, 0.472, 0.785, 0.875, 0.483, 0.79, 0.87, 0.493, 0.795, 0.865, 0.502, 0.8, 0.86, 0.511, 0.805, 0.855, 0.52, 0.809, 0.849, 0.528, 0.814, 0.844, 0.535, 0.818, 0.838, 0.542, 0.821, 0.832, 0.548, 0.824, 0.826, 0.554, 0.827, 0.819, 0.559, 0.83, 0.812, 0.563, 0.832, 0.805, 0.567, 0.834, 0.797, 0.57, 0.836, 0.788, 0.572, 0.837, 0.779, 0.574, 0.838, 0.77, 0.575, 0.838, 0.76, 0.576, 0.838, 0.749, 0.576, 0.838, 0.737, 0.576, 0.837, 0.725, 0.575, 0.835, 0.713, 0.574, 0.834, 0.699, 0.573, 0.831, 0.685, 0.571, 0.829, 0.671, 0.57, 0.826, 0.656, 0.568, 0.823, 0.64, 0.566, 0.819, 0.624, 0.563, 0.815, 0.607, 0.561, 0.811, 0.59, 0.559, 0.807, 0.573, 0.556, 0.802, 0.555, 0.554, 0.797, 0.537, 0.552, 0.792, 0.518, 0.549, 0.786, 0.499, 0.547, 0.781, 0.48, 0.545, 0.775, 0.46, 0.543, 0.769, 0.441, 0.541, 0.763, 0.42, 0.539, 0.756, 0.4, 0.537, 0.75, 0.379, 0.535, 0.743, 0.358, 0.533, 0.737, 0.337, 0.531, 0.73, 0.315, 0.53, 0.723, 0.293, 0.528, 0.716, 0.27, 0.527, 0.709, 0.246, 0.525, 0.702, 0.221, 0.524, 0.694, 0.195, 0.265, 0.685, 0.965, 0.284, 0.692, 0.959, 0.303, 0.699, 0.952, 0.32, 0.706, 0.946, 0.337, 0.713, 0.94, 0.353, 0.72, 0.935, 0.369, 0.726, 0.929, 0.384, 0.733, 0.924, 0.398, 0.739, 0.918, 0.412, 0.746, 0.913, 0.425, 0.752, 0.908, 0.438, 0.759, 0.903, 0.451, 0.765, 0.899, 0.463, 0.771, 0.894, 0.475, 0.777, 0.889, 0.486, 0.782, 0.884, 0.497, 0.788, 0.88, 0.507, 0.793, 0.875, 0.517, 0.799, 0.87, 0.527, 0.804, 0.866, 0.536, 0.809, 0.861, 0.544, 0.813, 0.856, 0.552, 0.818, 0.85, 0.56, 0.822, 0.845, 0.566, 0.826, 0.839, 0.573, 0.829, 0.833, 0.578, 0.832, 0.827, 0.583, 0.835, 0.82, 0.587, 0.837, 0.813, 0.591, 0.839, 0.805, 0.594, 0.841, 0.797, 0.596, 0.842, 0.788, 0.598, 0.843, 0.778, 0.599, 0.843, 0.768, 0.6, 0.843, 0.758, 0.6, 0.843, 0.746, 0.599, 0.842, 0.734, 0.599, 0.84, 0.721, 0.597, 0.838, 0.708, 0.596, 0.836, 0.694, 0.594, 0.834, 0.679, 0.592, 0.831, 0.663, 0.59, 0.827, 0.648, 0.587, 0.823, 0.631, 0.585, 0.819, 0.614, 0.582, 0.815, 0.597, 0.58, 0.81, 0.579, 0.577, 0.805, 0.561, 0.575, 0.8, 0.542, 0.572, 0.795, 0.524, 0.569, 0.789, 0.504, 0.567, 0.783, 0.485, 0.565, 0.777, 0.465, 0.562, 0.771, 0.445, 0.56, 0.765, 0.425, 0.558, 0.758, 0.404, 0.556, 0.752, 0.383, 0.554, 0.745, 0.362, 0.552, 0.738, 0.341, 0.55, 0.731, 0.319, 0.548, 0.724, 0.296, 0.546, 0.717, 0.273, 0.544, 0.709, 0.249, 0.542, 0.702, 0.224, 0.541, 0.695, 0.198, 0.299, 0.685, 0.968, 0.317, 0.692, 0.961, 0.334, 0.699, 0.955, 0.35, 0.706, 0.949, 0.366, 0.713, 0.943, 0.381, 0.72, 0.938, 0.395, 0.727, 0.932, 0.41, 0.734, 0.927, 0.423, 0.741, 0.922, 0.437, 0.747, 0.917, 0.45, 0.754, 0.912, 0.463, 0.76, 0.907, 0.475, 0.767, 0.903, 0.487, 0.773, 0.898, 0.498, 0.779, 0.894, 0.509, 0.785, 0.889, 0.52, 0.791, 0.885, 0.531, 0.796, 0.88, 0.54, 0.802, 0.876, 0.55, 0.807, 0.871, 0.559, 0.812, 0.867, 0.568, 0.817, 0.862, 0.576, 0.822, 0.857, 0.583, 0.826, 0.852, 0.59, 0.83, 0.847, 0.596, 0.834, 0.841, 0.602, 0.837, 0.835, 0.607, 0.84, 0.828, 0.611, 0.843, 0.821, 0.615, 0.845, 0.814, 0.618, 0.846, 0.805, 0.62, 0.848, 0.797, 0.622, 0.848, 0.787, 0.623, 0.849, 0.777, 0.623, 0.849, 0.766, 0.623, 0.848, 0.755, 0.622, 0.847, 0.743, 0.621, 0.845, 0.73, 0.62, 0.843, 0.716, 0.618, 0.841, 0.702, 0.616, 0.838, 0.687, 0.613, 0.835, 0.671, 0.611, 0.831, 0.655, 0.608, 0.827, 0.638, 0.606, 0.823, 0.621, 0.603, 0.818, 0.604, 0.6, 0.814, 0.585, 0.597, 0.808, 0.567, 0.594, 0.803, 0.548, 0.592, 0.797, 0.529, 0.589, 0.792, 0.51, 0.586, 0.785, 0.49, 0.584, 0.779, 0.47, 0.581, 0.773, 0.45, 0.579, 0.766, 0.429, 0.576, 0.76, 0.408, 0.574, 0.753, 0.387, 0.572, 0.746, 0.366, 0.569, 0.739, 0.344, 0.567, 0.732, 0.322, 0.565, 0.725, 0.299, 0.563, 0.717, 0.276, 0.561, 0.71, 0.252, 0.559, 0.703, 0.227, 0.557, 0.695, 0.201, 0.329, 0.685, 0.97, 0.346, 0.692, 0.964, 0.362, 0.699, 0.958, 0.377, 0.707, 0.952, 0.392, 0.714, 0.946, 0.406, 0.721, 0.941, 0.42, 0.728, 0.935, 0.434, 0.735, 0.93, 0.447, 0.742, 0.925, 0.46, 0.749, 0.92, 0.473, 0.756, 0.916, 0.485, 0.762, 0.911, 0.497, 0.769, 0.907, 0.509, 0.775, 0.903, 0.521, 0.781, 0.898, 0.532, 0.788, 0.894, 0.542, 0.794, 0.89, 0.553, 0.799, 0.886, 0.563, 0.805, 0.882, 0.572, 0.811, 0.877, 0.581, 0.816, 0.873, 0.59, 0.821, 0.868, 0.598, 0.826, 0.864, 0.606, 0.83, 0.859, 0.613, 0.834, 0.854, 0.619, 0.838, 0.848, 0.625, 0.842, 0.842, 0.63, 0.845, 0.836, 0.634, 0.848, 0.829, 0.638, 0.85, 0.822, 0.641, 0.852, 0.814, 0.643, 0.853, 0.805, 0.645, 0.854, 0.796, 0.645, 0.854, 0.786, 0.646, 0.854, 0.775, 0.645, 0.853, 0.764, 0.645, 0.852, 0.751, 0.643, 0.851, 0.738, 0.642, 0.848, 0.725, 0.639, 0.846, 0.71, 0.637, 0.843, 0.695, 0.635, 0.839, 0.679, 0.632, 0.836, 0.662, 0.629, 0.831, 0.645, 0.626, 0.827, 0.628, 0.623, 0.822, 0.61, 0.62, 0.817, 0.592, 0.617, 0.811, 0.573, 0.614, 0.806, 0.554, 0.611, 0.8, 0.534, 0.608, 0.794, 0.515, 0.605, 0.788, 0.495, 0.602, 0.781, 0.474, 0.599, 0.775, 0.454, 0.597, 0.768, 0.433, 0.594, 0.761, 0.412, 0.592, 0.754, 0.391, 0.589, 0.747, 0.369, 0.587, 0.74, 0.347, 0.584, 0.733, 0.325, 0.582, 0.725, 0.302, 0.58, 0.718, 0.279, 0.577, 0.71, 0.255, 0.575, 0.703, 0.23, 0.573, 0.695, 0.204, 0.357, 0.685, 0.972, 0.372, 0.692, 0.966, 0.387, 0.7, 0.96, 0.401, 0.707, 0.954, 0.416, 0.714, 0.949, 0.429, 0.722, 0.943, 0.443, 0.729, 0.938, 0.456, 0.736, 0.933, 0.469, 0.743, 0.929, 0.482, 0.75, 0.924, 0.494, 0.757, 0.919, 0.507, 0.764, 0.915, 0.519, 0.771, 0.911, 0.53, 0.777, 0.907, 0.542, 0.784, 0.903, 0.553, 0.79, 0.899, 0.563, 0.796, 0.895, 0.574, 0.802, 0.891, 0.584, 0.808, 0.887, 0.593, 0.814, 0.883, 0.603, 0.82, 0.879, 0.611, 0.825, 0.875, 0.62, 0.83, 0.87, 0.627, 0.835, 0.866, 0.635, 0.839, 0.861, 0.641, 0.843, 0.856, 0.647, 0.847, 0.85, 0.652, 0.85, 0.844, 0.657, 0.853, 0.838, 0.66, 0.855, 0.831, 0.663, 0.857, 0.823, 0.666, 0.859, 0.814, 0.667, 0.859, 0.805, 0.668, 0.86, 0.795, 0.668, 0.86, 0.784, 0.667, 0.859, 0.773, 0.666, 0.858, 0.76, 0.665, 0.856, 0.747, 0.663, 0.853, 0.733, 0.661, 0.851, 0.718, 0.658, 0.847, 0.703, 0.655, 0.844, 0.687, 0.652, 0.84, 0.67, 0.649, 0.835, 0.652, 0.646, 0.83, 0.635, 0.642, 0.825, 0.616, 0.639, 0.82, 0.598, 0.636, 0.814, 0.579, 0.633, 0.808, 0.559, 0.629, 0.802, 0.539, 0.626, 0.796, 0.519, 0.623, 0.79, 0.499, 0.62, 0.783, 0.479, 0.617, 0.776, 0.458, 0.614, 0.769, 0.437, 0.611, 0.762, 0.416, 0.609, 0.755, 0.394, 0.606, 0.748, 0.372, 0.603, 0.74, 0.35, 0.601, 0.733, 0.328, 0.598, 0.726, 0.305, 0.596, 0.718, 0.282, 0.593, 0.71, 0.257, 0.591, 0.703, 0.232, 0.589, 0.695, 0.206, 0.381, 0.684, 0.974, 0.396, 0.692, 0.968, 0.41, 0.7, 0.962, 0.424, 0.707, 0.957, 0.438, 0.715, 0.951, 0.451, 0.722, 0.946, 0.464, 0.729, 0.941, 0.477, 0.737, 0.936, 0.49, 0.744, 0.932, 0.503, 0.751, 0.927, 0.515, 0.758, 0.923, 0.527, 0.765, 0.919, 0.539, 0.772, 0.915, 0.55, 0.779, 0.911, 0.562, 0.786, 0.907, 0.573, 0.792, 0.903, 0.584, 0.799, 0.9, 0.594, 0.805, 0.896, 0.604, 0.811, 0.892, 0.614, 0.817, 0.889, 0.623, 0.823, 0.885, 0.632, 0.829, 0.881, 0.641, 0.834, 0.877, 0.649, 0.839, 0.873, 0.656, 0.844, 0.868, 0.663, 0.848, 0.863, 0.669, 0.852, 0.858, 0.674, 0.855, 0.852, 0.679, 0.858, 0.846, 0.682, 0.861, 0.839, 0.685, 0.863, 0.832, 0.688, 0.864, 0.823, 0.689, 0.865, 0.814, 0.69, 0.865, 0.804, 0.69, 0.865, 0.794, 0.689, 0.864, 0.782, 0.688, 0.863, 0.769, 0.686, 0.861, 0.756, 0.684, 0.858, 0.742, 0.681, 0.855, 0.726, 0.678, 0.852, 0.711, 0.675, 0.848, 0.694, 0.672, 0.844, 0.677, 0.668, 0.839, 0.659, 0.665, 0.834, 0.641, 0.662, 0.829, 0.622, 0.658, 0.823, 0.603, 0.655, 0.817, 0.584, 0.651, 0.811, 0.564, 0.648, 0.805, 0.544, 0.644, 0.798, 0.524, 0.641, 0.791, 0.503, 0.638, 0.785, 0.483, 0.635, 0.778, 0.462, 0.631, 0.77, 0.44, 0.628, 0.763, 0.419, 0.625, 0.756, 0.397, 0.623, 0.748, 0.375, 0.62, 0.741, 0.353, 0.617, 0.733, 0.33, 0.614, 0.726, 0.307, 0.612, 0.718, 0.284, 0.609, 0.71, 0.26, 0.606, 0.702, 0.235, 0.604, 0.694, 0.208, 0.404, 0.684, 0.977, 0.418, 0.692, 0.971, 0.432, 0.699, 0.965, 0.445, 0.707, 0.959, 0.458, 0.715, 0.954, 0.472, 0.722, 0.949, 0.484, 0.73, 0.944, 0.497, 0.737, 0.939, 0.51, 0.745, 0.935, 0.522, 0.752, 0.931, 0.534, 0.759, 0.926, 0.546, 0.767, 0.922, 0.558, 0.774, 0.919, 0.569, 0.781, 0.915, 0.581, 0.788, 0.911, 0.592, 0.794, 0.908, 0.603, 0.801, 0.904, 0.613, 0.808, 0.901, 0.624, 0.814, 0.897, 0.633, 0.82, 0.894, 0.643, 0.826, 0.891, 0.652, 0.832, 0.887, 0.661, 0.838, 0.883, 0.669, 0.843, 0.879, 0.677, 0.848, 0.875, 0.684, 0.853, 0.871, 0.69, 0.857, 0.866, 0.695, 0.86, 0.86, 0.7, 0.864, 0.855, 0.704, 0.866, 0.848, 0.707, 0.869, 0.841, 0.709, 0.87, 0.833, 0.711, 0.871, 0.824, 0.711, 0.871, 0.814, 0.711, 0.871, 0.803, 0.71, 0.87, 0.791, 0.709, 0.868, 0.778, 0.707, 0.866, 0.765, 0.704, 0.864, 0.75, 0.701, 0.86, 0.735, 0.698, 0.857, 0.718, 0.695, 0.852, 0.702, 0.691, 0.848, 0.684, 0.688, 0.843, 0.666, 0.684, 0.837, 0.647, 0.68, 0.832, 0.628, 0.676, 0.826, 0.609, 0.673, 0.82, 0.589, 0.669, 0.813, 0.569, 0.665, 0.807, 0.549, 0.662, 0.8, 0.528, 0.658, 0.793, 0.507, 0.655, 0.786, 0.486, 0.651, 0.779, 0.465, 0.648, 0.771, 0.444, 0.645, 0.764, 0.422, 0.642, 0.756, 0.4, 0.639, 0.749, 0.378, 0.636, 0.741, 0.356, 0.633, 0.733, 0.333, 0.63, 0.726, 0.31, 0.627, 0.718, 0.286, 0.624, 0.71, 0.262, 0.621, 0.702, 0.237, 0.619, 0.694, 0.21, 0.425, 0.683, 0.979, 0.439, 0.691, 0.973, 0.452, 0.699, 0.967, 0.465, 0.707, 0.962, 0.478, 0.715, 0.956, 0.491, 0.722, 0.951, 0.503, 0.73, 0.947, 0.516, 0.738, 0.942, 0.528, 0.745, 0.938, 0.54, 0.753, 0.934, 0.552, 0.76, 0.93, 0.564, 0.768, 0.926, 0.576, 0.775, 0.922, 0.588, 0.782, 0.919, 0.599, 0.789, 0.915, 0.61, 0.797, 0.912, 0.621, 0.803, 0.909, 0.632, 0.81, 0.906, 0.642, 0.817, 0.902, 0.652, 0.823, 0.899, 0.662, 0.83, 0.896, 0.671, 0.836, 0.893, 0.68, 0.842, 0.89, 0.689, 0.847, 0.886, 0.697, 0.853, 0.882, 0.704, 0.857, 0.878, 0.71, 0.862, 0.874, 0.716, 0.866, 0.869, 0.721, 0.869, 0.863, 0.725, 0.872, 0.857, 0.729, 0.874, 0.85, 0.731, 0.876, 0.842, 0.732, 0.877, 0.833, 0.733, 0.877, 0.823, 0.732, 0.877, 0.812, 0.731, 0.876, 0.8, 0.729, 0.874, 0.787, 0.727, 0.872, 0.773, 0.724, 0.869, 0.759, 0.721, 0.865, 0.743, 0.718, 0.861, 0.726, 0.714, 0.857, 0.709, 0.71, 0.852, 0.691, 0.706, 0.846, 0.672, 0.702, 0.841, 0.653, 0.698, 0.835, 0.634, 0.694, 0.828, 0.614, 0.69, 0.822, 0.594, 0.686, 0.815, 0.574, 0.683, 0.808, 0.553, 0.679, 0.801, 0.532, 0.675, 0.794, 0.511, 0.672, 0.787, 0.49, 0.668, 0.779, 0.468, 0.665, 0.772, 0.446, 0.661, 0.764, 0.425, 0.658, 0.757, 0.403, 0.654, 0.749, 0.38, 0.651, 0.741, 0.358, 0.648, 0.733, 0.335, 0.645, 0.725, 0.312, 0.642, 0.717, 0.288, 0.639, 0.709, 0.264, 0.636, 0.701, 0.238, 0.633, 0.693, 0.212, 0.445, 0.682, 0.981, 0.458, 0.691, 0.975, 0.471, 0.699, 0.969, 0.484, 0.707, 0.964, 0.496, 0.715, 0.959, 0.509, 0.722, 0.954, 0.521, 0.73, 0.949, 0.534, 0.738, 0.945, 0.546, 0.746, 0.941, 0.558, 0.753, 0.937, 0.57, 0.761, 0.933, 0.582, 0.769, 0.929, 0.593, 0.776, 0.926, 0.605, 0.784, 0.922, 0.616, 0.791, 0.919, 0.628, 0.798, 0.916, 0.639, 0.806, 0.913, 0.649, 0.813, 0.91, 0.66, 0.82, 0.907, 0.67, 0.826, 0.904, 0.68, 0.833, 0.902, 0.69, 0.839, 0.899, 0.699, 0.846, 0.896, 0.708, 0.851, 0.893, 0.716, 0.857, 0.889, 0.724, 0.862, 0.885, 0.731, 0.867, 0.881, 0.737, 0.871, 0.877, 0.742, 0.875, 0.872, 0.746, 0.878, 0.866, 0.75, 0.88, 0.859, 0.752, 0.882, 0.851, 0.753, 0.883, 0.843, 0.754, 0.883, 0.833, 0.753, 0.883, 0.822, 0.752, 0.882, 0.81, 0.75, 0.88, 0.797, 0.747, 0.877, 0.782, 0.744, 0.874, 0.767, 0.74, 0.87, 0.751, 0.737, 0.866, 0.734, 0.733, 0.861, 0.716, 0.729, 0.855, 0.697, 0.724, 0.85, 0.678, 0.72, 0.844, 0.659, 0.716, 0.837, 0.639, 0.712, 0.831, 0.619, 0.708, 0.824, 0.598, 0.704, 0.817, 0.578, 0.699, 0.81, 0.557, 0.696, 0.803, 0.535, 0.692, 0.795, 0.514, 0.688, 0.788, 0.493, 0.684, 0.78, 0.471, 0.68, 0.772, 0.449, 0.677, 0.765, 0.427, 0.673, 0.757, 0.405, 0.67, 0.749, 0.382, 0.666, 0.741, 0.36, 0.663, 0.733, 0.337, 0.66, 0.725, 0.313, 0.657, 0.716, 0.289, 0.653, 0.708, 0.265, 0.65, 0.7, 0.24, 0.647, 0.692, 0.213, 0.464, 0.681, 0.982, 0.476, 0.69, 0.977, 0.489, 0.698, 0.971, 0.501, 0.706, 0.966, 0.514, 0.714, 0.961, 0.526, 0.722, 0.956, 0.538, 0.73, 0.952, 0.55, 0.738, 0.947, 0.562, 0.746, 0.943, 0.574, 0.754, 0.939, 0.586, 0.762, 0.936, 0.598, 0.769, 0.932, 0.61, 0.777, 0.929, 0.621, 0.785, 0.926, 0.633, 0.792, 0.923, 0.644, 0.8, 0.92, 0.655, 0.807, 0.917, 0.666, 0.815, 0.915, 0.677, 0.822, 0.912, 0.688, 0.829, 0.909, 0.698, 0.836, 0.907, 0.708, 0.843, 0.904, 0.717, 0.849, 0.902, 0.727, 0.855, 0.899, 0.735, 0.861, 0.896, 0.743, 0.867, 0.893, 0.75, 0.872, 0.889, 0.757, 0.877, 0.885, 0.762, 0.881, 0.88, 0.767, 0.884, 0.875, 0.77, 0.887, 0.868, 0.773, 0.888, 0.861, 0.774, 0.889, 0.852, 0.774, 0.89, 0.842, 0.774, 0.889, 0.831, 0.772, 0.888, 0.819, 0.77, 0.885, 0.806, 0.767, 0.883, 0.791, 0.763, 0.879, 0.775, 0.759, 0.875, 0.759, 0.755, 0.87, 0.741, 0.751, 0.865, 0.723, 0.747, 0.859, 0.704, 0.742, 0.853, 0.684, 0.738, 0.847, 0.664, 0.733, 0.84, 0.644, 0.729, 0.833, 0.623, 0.724, 0.826, 0.603, 0.72, 0.819, 0.581, 0.716, 0.811, 0.56, 0.712, 0.804, 0.539, 0.708, 0.796, 0.517, 0.704, 0.788, 0.495, 0.7, 0.78, 0.473, 0.696, 0.772, 0.451, 0.692, 0.764, 0.429, 0.688, 0.756, 0.407, 0.685, 0.748, 0.384, 0.681, 0.74, 0.361, 0.678, 0.732, 0.338, 0.674, 0.724, 0.315, 0.671, 0.715, 0.291, 0.667, 0.707, 0.266, 0.664, 0.699, 0.241, 0.661, 0.691, 0.214, 0.481, 0.68, 0.984, 0.494, 0.689, 0.978, 0.506, 0.697, 0.973, 0.518, 0.705, 0.968, 0.53, 0.713, 0.963, 0.542, 0.722, 0.958, 0.554, 0.73, 0.954, 0.566, 0.738, 0.95, 0.578, 0.746, 0.946, 0.59, 0.754, 0.942, 0.602, 0.762, 0.939, 0.614, 0.77, 0.935, 0.626, 0.778, 0.932, 0.637, 0.786, 0.929, 0.649, 0.794, 0.926, 0.66, 0.801, 0.924, 0.671, 0.809, 0.921, 0.683, 0.817, 0.919, 0.694, 0.824, 0.916, 0.704, 0.832, 0.914, 0.715, 0.839, 0.912, 0.725, 0.846, 0.91, 0.735, 0.853, 0.908, 0.744, 0.859, 0.905, 0.753, 0.866, 0.903, 0.762, 0.872, 0.9, 0.77, 0.877, 0.897, 0.776, 0.882, 0.893, 0.782, 0.886, 0.889, 0.787, 0.89, 0.884, 0.791, 0.893, 0.878, 0.794, 0.895, 0.871, 0.795, 0.896, 0.862, 0.795, 0.896, 0.852, 0.794, 0.895, 0.841, 0.792, 0.894, 0.829, 0.789, 0.891, 0.815, 0.786, 0.888, 0.8, 0.782, 0.884, 0.783, 0.778, 0.879, 0.766, 0.774, 0.874, 0.748, 0.769, 0.868, 0.729, 0.764, 0.862, 0.71, 0.76, 0.856, 0.69, 0.755, 0.849, 0.669, 0.75, 0.842, 0.649, 0.745, 0.835, 0.628, 0.741, 0.827, 0.606, 0.736, 0.82, 0.585, 0.732, 0.812, 0.563, 0.728, 0.804, 0.542, 0.723, 0.796, 0.52, 0.719, 0.788, 0.498, 0.715, 0.78, 0.475, 0.711, 0.772, 0.453, 0.707, 0.764, 0.431, 0.703, 0.756, 0.408, 0.699, 0.748, 0.386, 0.696, 0.739, 0.363, 0.692, 0.731, 0.339, 0.688, 0.723, 0.316, 0.685, 0.714, 0.292, 0.681, 0.706, 0.267, 0.678, 0.697, 0.242, 0.674, 0.689, 0.215, 0.498, 0.679, 0.986, 0.51, 0.687, 0.98, 0.522, 0.696, 0.975, 0.534, 0.704, 0.97, 0.546, 0.712, 0.965, 0.558, 0.721, 0.961, 0.57, 0.729, 0.956, 0.581, 0.737, 0.952, 0.593, 0.746, 0.948, 0.605, 0.754, 0.945, 0.617, 0.762, 0.941, 0.629, 0.77, 0.938, 0.64, 0.778, 0.935, 0.652, 0.786, 0.932, 0.664, 0.794, 0.93, 0.675, 0.802, 0.927, 0.687, 0.81, 0.925, 0.698, 0.818, 0.923, 0.709, 0.826, 0.921, 0.72, 0.834, 0.919, 0.731, 0.841, 0.917, 0.742, 0.849, 0.915, 0.752, 0.856, 0.913, 0.762, 0.863, 0.911, 0.771, 0.87, 0.909, 0.78, 0.876, 0.907, 0.788, 0.882, 0.904, 0.796, 0.887, 0.901, 0.802, 0.892, 0.897, 0.807, 0.896, 0.893, 0.811, 0.899, 0.887, 0.814, 0.902, 0.88, 0.815, 0.903, 0.872, 0.815, 0.903, 0.862, 0.814, 0.902, 0.851, 0.812, 0.9, 0.838, 0.809, 0.897, 0.824, 0.805, 0.893, 0.808, 0.801, 0.889, 0.791, 0.796, 0.884, 0.774, 0.791, 0.878, 0.755, 0.786, 0.872, 0.735, 0.781, 0.865, 0.715, 0.776, 0.858, 0.695, 0.771, 0.851, 0.674, 0.767, 0.844, 0.653, 0.762, 0.836, 0.631, 0.757, 0.829, 0.61, 0.752, 0.821, 0.588, 0.748, 0.813, 0.566, 0.743, 0.805, 0.544, 0.739, 0.796, 0.522, 0.734, 0.788, 0.5, 0.73, 0.78, 0.477, 0.726, 0.772, 0.455, 0.722, 0.763, 0.432, 0.718, 0.755, 0.41, 0.714, 0.746, 0.387, 0.71, 0.738, 0.364, 0.706, 0.73, 0.34, 0.702, 0.721, 0.317, 0.698, 0.713, 0.293, 0.694, 0.704, 0.268, 0.691, 0.696, 0.243, 0.687, 0.687, 0.216, 0.513, 0.677, 0.987, 0.525, 0.686, 0.982, 0.537, 0.694, 0.977, 0.549, 0.703, 0.972, 0.561, 0.711, 0.967, 0.572, 0.72, 0.962, 0.584, 0.728, 0.958, 0.596, 0.737, 0.954, 0.608, 0.745, 0.951, 0.619, 0.753, 0.947, 0.631, 0.762, 0.944, 0.643, 0.77, 0.941, 0.655, 0.778, 0.938, 0.666, 0.787, 0.935, 0.678, 0.795, 0.933, 0.689, 0.803, 0.93, 0.701, 0.811, 0.928, 0.713, 0.82, 0.926, 0.724, 0.828, 0.925, 0.735, 0.836, 0.923, 0.746, 0.844, 0.921, 0.757, 0.852, 0.92, 0.768, 0.859, 0.918, 0.778, 0.867, 0.917, 0.788, 0.874, 0.915, 0.797, 0.881, 0.913, 0.806, 0.887, 0.911, 0.814, 0.893, 0.909, 0.821, 0.898, 0.906, 0.827, 0.902, 0.902, 0.831, 0.906, 0.897, 0.834, 0.908, 0.89, 0.836, 0.91, 0.882, 0.836, 0.91, 0.873, 0.834, 0.909, 0.861, 0.832, 0.906, 0.848, 0.828, 0.903, 0.833, 0.824, 0.899, 0.817, 0.819, 0.894, 0.799, 0.814, 0.888, 0.781, 0.809, 0.882, 0.761, 0.804, 0.875, 0.741, 0.798, 0.868, 0.72, 0.793, 0.861, 0.699, 0.788, 0.853, 0.678, 0.783, 0.845, 0.656, 0.777, 0.837, 0.635, 0.772, 0.829, 0.613, 0.768, 0.821, 0.59, 0.763, 0.813, 0.568, 0.758, 0.804, 0.546, 0.753, 0.796, 0.524, 0.749, 0.788, 0.501, 0.744, 0.779, 0.479, 0.74, 0.771, 0.456, 0.736, 0.762, 0.433, 0.731, 0.754, 0.411, 0.727, 0.745, 0.388, 0.723, 0.736, 0.365, 0.719, 0.728, 0.341, 0.715, 0.719, 0.317, 0.711, 0.711, 0.293, 0.707, 0.702, 0.268, 0.704, 0.694, 0.243, 0.7, 0.685, 0.216, 0.528, 0.675, 0.989, 0.54, 0.684, 0.983, 0.551, 0.693, 0.978, 0.563, 0.701, 0.973, 0.575, 0.71, 0.969, 0.586, 0.718, 0.964, 0.598, 0.727, 0.96, 0.61, 0.736, 0.956, 0.621, 0.744, 0.953, 0.633, 0.753, 0.949, 0.645, 0.761, 0.946, 0.656, 0.77, 0.943, 0.668, 0.778, 0.94, 0.68, 0.787, 0.938, 0.691, 0.795, 0.936, 0.703, 0.804, 0.933, 0.715, 0.812, 0.932, 0.726, 0.821, 0.93, 0.738, 0.829, 0.928, 0.749, 0.837, 0.927, 0.761, 0.846, 0.926, 0.772, 0.854, 0.924, 0.783, 0.862, 0.923, 0.794, 0.87, 0.922, 0.804, 0.877, 0.921, 0.814, 0.885, 0.92, 0.824, 0.892, 0.918, 0.832, 0.898, 0.917, 0.84, 0.904, 0.914, 0.846, 0.909, 0.911, 0.851, 0.913, 0.906, 0.855, 0.915, 0.901, 0.856, 0.917, 0.893, 0.856, 0.917, 0.883, 0.854, 0.915, 0.871, 0.851, 0.913, 0.858, 0.847, 0.909, 0.842, 0.842, 0.904, 0.825, 0.837, 0.898, 0.806, 0.831, 0.892, 0.787, 0.826, 0.885, 0.767, 0.82, 0.878, 0.746, 0.814, 0.87, 0.725, 0.809, 0.862, 0.703, 0.803, 0.854, 0.681, 0.798, 0.846, 0.659, 0.793, 0.838, 0.637, 0.788, 0.829, 0.615, 0.782, 0.821, 0.592, 0.777, 0.812, 0.57, 0.773, 0.804, 0.548, 0.768, 0.795, 0.525, 0.763, 0.787, 0.502, 0.758, 0.778, 0.48, 0.754, 0.769, 0.457, 0.749, 0.761, 0.434, 0.745, 0.752, 0.411, 0.741, 0.743, 0.388, 0.737, 0.735, 0.365, 0.732, 0.726, 0.342, 0.728, 0.717, 0.318, 0.724, 0.709, 0.293, 0.72, 0.7, 0.269, 0.716, 0.691, 0.243, 0.712, 0.683, 0.216, 0.542, 0.673, 0.99, 0.554, 0.682, 0.985, 0.565, 0.691, 0.98, 0.577, 0.7, 0.975, 0.588, 0.708, 0.97, 0.6, 0.717, 0.966, 0.611, 0.726, 0.962, 0.623, 0.734, 0.958, 0.634, 0.743, 0.955, 0.646, 0.752, 0.951, 0.657, 0.76, 0.948, 0.669, 0.769, 0.945, 0.681, 0.778, 0.943, 0.692, 0.786, 0.94, 0.704, 0.795, 0.938, 0.716, 0.804, 0.936, 0.728, 0.812, 0.934, 0.739, 0.821, 0.933, 0.751, 0.83, 0.932, 0.763, 0.838, 0.93, 0.774, 0.847, 0.929, 0.786, 0.856, 0.929, 0.797, 0.864, 0.928, 0.809, 0.873, 0.927, 0.819, 0.881, 0.927, 0.83, 0.889, 0.926, 0.84, 0.896, 0.925, 0.85, 0.903, 0.924, 0.858, 0.91, 0.922, 0.865, 0.915, 0.92, 0.871, 0.92, 0.916, 0.875, 0.923, 0.911, 0.876, 0.924, 0.903, 0.876, 0.924, 0.894, 0.873, 0.922, 0.882, 0.87, 0.919, 0.867, 0.865, 0.914, 0.851, 0.86, 0.909, 0.832, 0.854, 0.902, 0.813, 0.848, 0.895, 0.793, 0.842, 0.888, 0.772, 0.836, 0.88, 0.75, 0.83, 0.872, 0.729, 0.824, 0.864, 0.707, 0.819, 0.855, 0.684, 0.813, 0.847, 0.662, 0.808, 0.838, 0.639, 0.802, 0.829, 0.617, 0.797, 0.82, 0.594, 0.792, 0.812, 0.571, 0.787, 0.803, 0.549, 0.782, 0.794, 0.526, 0.777, 0.785, 0.503, 0.772, 0.776, 0.48, 0.767, 0.768, 0.458, 0.763, 0.759, 0.435, 0.758, 0.75, 0.412, 0.754, 0.741, 0.388, 0.749, 0.732, 0.365, 0.745, 0.724, 0.342, 0.741, 0.715, 0.318, 0.737, 0.706, 0.293, 0.732, 0.697, 0.269, 0.728, 0.689, 0.243, 0.724, 0.68, 0.216, 0.556, 0.671, 0.992, 0.567, 0.68, 0.986, 0.578, 0.689, 0.981, 0.59, 0.697, 0.976, 0.601, 0.706, 0.972, 0.612, 0.715, 0.968, 0.624, 0.724, 0.964, 0.635, 0.733, 0.96, 0.646, 0.741, 0.956, 0.658, 0.75, 0.953, 0.67, 0.759, 0.95, 0.681, 0.768, 0.947, 0.693, 0.777, 0.945, 0.704, 0.786, 0.943, 0.716, 0.794, 0.941, 0.728, 0.803, 0.939, 0.74, 0.812, 0.937, 0.752, 0.821, 0.936, 0.763, 0.83, 0.935, 0.775, 0.839, 0.934, 0.787, 0.848, 0.933, 0.799, 0.857, 0.932, 0.811, 0.866, 0.932, 0.822, 0.875, 0.932, 0.834, 0.883, 0.932, 0.845, 0.892, 0.931, 0.856, 0.9, 0.931, 0.866, 0.908, 0.931, 0.876, 0.915, 0.93, 0.884, 0.922, 0.929, 0.89, 0.927, 0.926, 0.895, 0.93, 0.921, 0.896, 0.932, 0.914, 0.896, 0.932, 0.905, 0.893, 0.929, 0.892, 0.888, 0.925, 0.876, 0.883, 0.92, 0.859, 0.877, 0.913, 0.84, 0.871, 0.906, 0.819, 0.864, 0.898, 0.798, 0.858, 0.89, 0.776, 0.852, 0.882, 0.754, 0.845, 0.873, 0.732, 0.839, 0.864, 0.709, 0.833, 0.855, 0.686, 0.828, 0.846, 0.664, 0.822, 0.837, 0.641, 0.816, 0.828, 0.618, 0.811, 0.819, 0.595, 0.806, 0.81, 0.572, 0.8, 0.801, 0.549, 0.795, 0.792, 0.526, 0.79, 0.783, 0.504, 0.785, 0.774, 0.481, 0.781, 0.765, 0.458, 0.776, 0.756, 0.435, 0.771, 0.748, 0.412, 0.766, 0.739, 0.388, 0.762, 0.73, 0.365, 0.757, 0.721, 0.341, 0.753, 0.712, 0.318, 0.749, 0.703, 0.293, 0.744, 0.695, 0.268, 0.74, 0.686, 0.243, 0.736, 0.677, 0.216, 0.569, 0.668, 0.993, 0.58, 0.677, 0.987, 0.591, 0.686, 0.982, 0.602, 0.695, 0.978, 0.613, 0.704, 0.973, 0.624, 0.713, 0.969, 0.635, 0.722, 0.965, 0.647, 0.731, 0.961, 0.658, 0.74, 0.958, 0.67, 0.748, 0.955, 0.681, 0.757, 0.952, 0.693, 0.766, 0.949, 0.704, 0.775, 0.947, 0.716, 0.784, 0.945, 0.728, 0.793, 0.943, 0.739, 0.802, 0.941, 0.751, 0.812, 0.939, 0.763, 0.821, 0.938, 0.775, 0.83, 0.937, 0.787, 0.839, 0.936, 0.799, 0.848, 0.936, 0.811, 0.858, 0.936, 0.823, 0.867, 0.935, 0.835, 0.876, 0.936, 0.847, 0.886, 0.936, 0.859, 0.895, 0.936, 0.87, 0.904, 0.937, 0.882, 0.912, 0.937, 0.892, 0.92, 0.937, 0.901, 0.928, 0.937, 0.909, 0.934, 0.936, 0.914, 0.938, 0.932, 0.917, 0.94, 0.926, 0.915, 0.94, 0.916, 0.912, 0.936, 0.902, 0.906, 0.931, 0.885, 0.9, 0.925, 0.866, 0.893, 0.917, 0.846, 0.887, 0.909, 0.824, 0.88, 0.9, 0.802, 0.873, 0.891, 0.78, 0.867, 0.882, 0.757, 0.86, 0.873, 0.734, 0.854, 0.864, 0.711, 0.848, 0.855, 0.688, 0.842, 0.845, 0.665, 0.836, 0.836, 0.642, 0.83, 0.827, 0.619, 0.824, 0.818, 0.596, 0.819, 0.808, 0.573, 0.814, 0.799, 0.549, 0.808, 0.79, 0.527, 0.803, 0.781, 0.504, 0.798, 0.772, 0.481, 0.793, 0.763, 0.458, 0.788, 0.754, 0.434, 0.783, 0.745, 0.411, 0.779, 0.736, 0.388, 0.774, 0.727, 0.365, 0.769, 0.718, 0.341, 0.765, 0.709, 0.317, 0.76, 0.7, 0.293, 0.756, 0.691, 0.268, 0.751, 0.683, 0.242, 0.747, 0.674, 0.215, 0.581, 0.665, 0.994, 0.592, 0.674, 0.989, 0.603, 0.683, 0.984, 0.614, 0.692, 0.979, 0.625, 0.701, 0.974, 0.636, 0.71, 0.97, 0.647, 0.719, 0.966, 0.658, 0.728, 0.963, 0.669, 0.737, 0.959, 0.681, 0.746, 0.956, 0.692, 0.755, 0.953, 0.703, 0.765, 0.951, 0.715, 0.774, 0.948, 0.727, 0.783, 0.946, 0.738, 0.792, 0.944, 0.75, 0.801, 0.943, 0.762, 0.81, 0.941, 0.774, 0.82, 0.94, 0.786, 0.829, 0.939, 0.798, 0.839, 0.939, 0.81, 0.848, 0.938, 0.822, 0.858, 0.938, 0.834, 0.867, 0.939, 0.847, 0.877, 0.939, 0.859, 0.887, 0.94, 0.871, 0.897, 0.94, 0.883, 0.906, 0.942, 0.896, 0.916, 0.943, 0.907, 0.925, 0.944, 0.918, 0.933, 0.945, 0.927, 0.941, 0.945, 0.934, 0.946, 0.943, 0.937, 0.949, 0.937, 0.935, 0.948, 0.927, 0.93, 0.943, 0.912, 0.924, 0.937, 0.893, 0.916, 0.929, 0.872, 0.909, 0.92, 0.85, 0.902, 0.911, 0.828, 0.895, 0.901, 0.805, 0.888, 0.892, 0.782, 0.881, 0.882, 0.759, 0.874, 0.872, 0.735, 0.868, 0.863, 0.712, 0.861, 0.853, 0.689, 0.855, 0.844, 0.665, 0.849, 0.834, 0.642, 0.843, 0.825, 0.619, 0.838, 0.815, 0.596, 0.832, 0.806, 0.572, 0.826, 0.797, 0.549, 0.821, 0.787, 0.526, 0.816, 0.778, 0.503, 0.811, 0.769, 0.48, 0.805, 0.76, 0.457, 0.8, 0.751, 0.434, 0.795, 0.742, 0.411, 0.791, 0.733, 0.387, 0.786, 0.724, 0.364, 0.781, 0.715, 0.34, 0.776, 0.706, 0.316, 0.772, 0.697, 0.292, 0.767, 0.688, 0.267, 0.762, 0.679, 0.241, 0.758, 0.67, 0.215, 0.593, 0.662, 0.995, 0.603, 0.671, 0.99, 0.614, 0.68, 0.985, 0.625, 0.689, 0.98, 0.636, 0.699, 0.975, 0.647, 0.708, 0.971, 0.658, 0.717, 0.967, 0.669, 0.726, 0.964, 0.68, 0.735, 0.96, 0.691, 0.744, 0.957, 0.702, 0.753, 0.955, 0.714, 0.762, 0.952, 0.725, 0.771, 0.95, 0.737, 0.781, 0.948, 0.748, 0.79, 0.946, 0.76, 0.799, 0.944, 0.772, 0.809, 0.943, 0.784, 0.818, 0.942, 0.796, 0.828, 0.941, 0.808, 0.837, 0.941, 0.82, 0.847, 0.94, 0.832, 0.857, 0.941, 0.844, 0.867, 0.941, 0.857, 0.877, 0.942, 0.869, 0.887, 0.943, 0.882, 0.897, 0.944, 0.895, 0.908, 0.945, 0.908, 0.918, 0.947, 0.92, 0.928, 0.949, 0.933, 0.938, 0.951, 0.944, 0.947, 0.953, 0.953, 0.955, 0.954, 0.957, 0.958, 0.95, 0.954, 0.956, 0.938, 0.948, 0.949, 0.92, 0.94, 0.941, 0.899, 0.932, 0.931, 0.877, 0.924, 0.921, 0.854, 0.916, 0.911, 0.83, 0.909, 0.901, 0.807, 0.901, 0.891, 0.783, 0.894, 0.881, 0.759, 0.887, 0.871, 0.736, 0.881, 0.861, 0.712, 0.874, 0.851, 0.688, 0.868, 0.841, 0.665, 0.862, 0.832, 0.642, 0.856, 0.822, 0.618, 0.85, 0.812, 0.595, 0.844, 0.803, 0.572, 0.839, 0.793, 0.549, 0.833, 0.784, 0.525, 0.828, 0.775, 0.502, 0.822, 0.766, 0.479, 0.817, 0.756, 0.456, 0.812, 0.747, 0.433, 0.807, 0.738, 0.41, 0.802, 0.729, 0.387, 0.797, 0.72, 0.363, 0.792, 0.711, 0.339, 0.787, 0.702, 0.315, 0.782, 0.693, 0.291, 0.778, 0.684, 0.266, 0.773, 0.675, 0.24, 0.768, 0.666, 0.214, 0.604, 0.659, 0.996, 0.614, 0.668, 0.99, 0.625, 0.677, 0.985, 0.636, 0.686, 0.981, 0.646, 0.695, 0.976, 0.657, 0.704, 0.972, 0.668, 0.714, 0.968, 0.679, 0.723, 0.965, 0.69, 0.732, 0.961, 0.701, 0.741, 0.958, 0.712, 0.75, 0.956, 0.723, 0.759, 0.953, 0.735, 0.769, 0.951, 0.746, 0.778, 0.949, 0.758, 0.787, 0.947, 0.769, 0.797, 0.945, 0.781, 0.806, 0.944, 0.793, 0.816, 0.943, 0.805, 0.826, 0.943, 0.817, 0.836, 0.942, 0.829, 0.845, 0.942, 0.841, 0.855, 0.942, 0.853, 0.866, 0.943, 0.866, 0.876, 0.943, 0.879, 0.886, 0.945, 0.892, 0.897, 0.946, 0.905, 0.907, 0.948, 0.918, 0.918, 0.95, 0.931, 0.93, 0.953, 0.945, 0.941, 0.956, 0.958, 0.952, 0.96, 0.971, 0.963, 0.963, 0.978, 0.968, 0.963, 0.972, 0.963, 0.948, 0.963, 0.954, 0.926, 0.954, 0.943, 0.903, 0.945, 0.931, 0.879, 0.937, 0.921, 0.855, 0.929, 0.91, 0.831, 0.921, 0.899, 0.807, 0.914, 0.889, 0.783, 0.907, 0.878, 0.759, 0.9, 0.868, 0.735, 0.893, 0.858, 0.711, 0.887, 0.848, 0.688, 0.88, 0.838, 0.664, 0.874, 0.828, 0.641, 0.868, 0.818, 0.617, 0.862, 0.809, 0.594, 0.856, 0.799, 0.571, 0.85, 0.79, 0.547, 0.845, 0.78, 0.524, 0.839, 0.771, 0.501, 0.834, 0.762, 0.478, 0.828, 0.752, 0.455, 0.823, 0.743, 0.432, 0.818, 0.734, 0.409, 0.813, 0.725, 0.385, 0.808, 0.716, 0.362, 0.803, 0.707, 0.338, 0.798, 0.698, 0.314, 0.793, 0.689, 0.29, 0.788, 0.68, 0.265, 0.783, 0.671, 0.239, 0.778, 0.662, 0.213, 0.615, 0.655, 0.996, 0.625, 0.664, 0.991, 0.635, 0.673, 0.986, 0.646, 0.683, 0.982, 0.656, 0.692, 0.977, 0.667, 0.701, 0.973, 0.678, 0.71, 0.969, 0.688, 0.719, 0.966, 0.699, 0.729, 0.962, 0.71, 0.738, 0.959, 0.721, 0.747, 0.956, 0.732, 0.756, 0.954, 0.744, 0.766, 0.952, 0.755, 0.775, 0.95, 0.766, 0.784, 0.948, 0.778, 0.794, 0.946, 0.789, 0.804, 0.945, 0.801, 0.813, 0.944, 0.813, 0.823, 0.943, 0.825, 0.833, 0.943, 0.837, 0.843, 0.943, 0.849, 0.853, 0.943, 0.861, 0.863, 0.944, 0.874, 0.873, 0.944, 0.886, 0.884, 0.946, 0.899, 0.895, 0.947, 0.912, 0.906, 0.949, 0.926, 0.917, 0.952, 0.939, 0.928, 0.955, 0.953, 0.94, 0.958, 0.967, 0.953, 0.963, 0.982, 0.966, 0.969, 0.994, 0.976, 0.972, 0.986, 0.966, 0.952, 0.976, 0.953, 0.928, 0.966, 0.941, 0.903, 0.957, 0.929, 0.878, 0.949, 0.918, 0.854, 0.941, 0.906, 0.83, 0.933, 0.896, 0.806, 0.926, 0.885, 0.782, 0.918, 0.874, 0.758, 0.911, 0.864, 0.734, 0.905, 0.854, 0.71, 0.898, 0.844, 0.686, 0.892, 0.834, 0.663, 0.885, 0.824, 0.639, 0.879, 0.814, 0.616, 0.873, 0.804, 0.592, 0.867, 0.795, 0.569, 0.861, 0.785, 0.546, 0.856, 0.776, 0.523, 0.85, 0.766, 0.5, 0.845, 0.757, 0.477, 0.839, 0.748, 0.454, 0.834, 0.739, 0.43, 0.829, 0.729, 0.407, 0.823, 0.72, 0.384, 0.818, 0.711, 0.361, 0.813, 0.702, 0.337, 0.808, 0.693, 0.313, 0.803, 0.684, 0.289, 0.798, 0.675, 0.264, 0.793, 0.666, 0.238, 0.788, 0.657, 0.211, 0.625, 0.651, 0.997, 0.635, 0.66, 0.992, 0.645, 0.669, 0.987, 0.656, 0.679, 0.982, 0.666, 0.688, 0.978, 0.676, 0.697, 0.974, 0.687, 0.706, 0.97, 0.698, 0.716, 0.966, 0.708, 0.725, 0.963, 0.719, 0.734, 0.96, 0.73, 0.743, 0.957, 0.741, 0.753, 0.954, 0.752, 0.762, 0.952, 0.763, 0.771, 0.95, 0.774, 0.781, 0.948, 0.786, 0.79, 0.947, 0.797, 0.8, 0.945, 0.809, 0.81, 0.945, 0.82, 0.819, 0.944, 0.832, 0.829, 0.943, 0.844, 0.839, 0.943, 0.856, 0.849, 0.943, 0.868, 0.86, 0.944, 0.88, 0.87, 0.945, 0.893, 0.88, 0.946, 0.905, 0.891, 0.947, 0.918, 0.902, 0.949, 0.931, 0.913, 0.951, 0.944, 0.924, 0.954, 0.957, 0.936, 0.957, 0.971, 0.947, 0.961, 0.983, 0.958, 0.964, 0.991, 0.963, 0.962, 0.99, 0.957, 0.946, 0.983, 0.946, 0.924, 0.975, 0.935, 0.9, 0.967, 0.923, 0.876, 0.959, 0.912, 0.851, 0.951, 0.901, 0.827, 0.943, 0.89, 0.803, 0.936, 0.88, 0.779, 0.929, 0.869, 0.755, 0.922, 0.859, 0.732, 0.915, 0.849, 0.708, 0.909, 0.839, 0.684, 0.902, 0.829, 0.661, 0.896, 0.819, 0.637, 0.89, 0.809, 0.614, 0.884, 0.8, 0.591, 0.878, 0.79, 0.567, 0.872, 0.78, 0.544, 0.866, 0.771, 0.521, 0.861, 0.762, 0.498, 0.855, 0.752, 0.475, 0.85, 0.743, 0.452, 0.844, 0.734, 0.429, 0.839, 0.725, 0.406, 0.834, 0.715, 0.382, 0.828, 0.706, 0.359, 0.823, 0.697, 0.335, 0.818, 0.688, 0.311, 0.813, 0.679, 0.287, 0.808, 0.67, 0.262, 0.803, 0.662, 0.236, 0.798, 0.653, 0.21, 0.635, 0.646, 0.998, 0.645, 0.656, 0.992, 0.655, 0.665, 0.987, 0.665, 0.674, 0.983, 0.675, 0.684, 0.978, 0.685, 0.693, 0.974, 0.696, 0.702, 0.97, 0.706, 0.711, 0.966, 0.717, 0.721, 0.963, 0.727, 0.73, 0.96, 0.738, 0.739, 0.957, 0.749, 0.748, 0.955, 0.76, 0.758, 0.952, 0.771, 0.767, 0.95, 0.782, 0.777, 0.948, 0.793, 0.786, 0.947, 0.804, 0.796, 0.946, 0.816, 0.805, 0.945, 0.827, 0.815, 0.944, 0.839, 0.825, 0.943, 0.85, 0.835, 0.943, 0.862, 0.845, 0.943, 0.874, 0.855, 0.943, 0.886, 0.865, 0.944, 0.898, 0.875, 0.945, 0.91, 0.886, 0.946, 0.923, 0.896, 0.948, 0.935, 0.907, 0.949, 0.947, 0.917, 0.951, 0.959, 0.927, 0.953, 0.97, 0.937, 0.955, 0.98, 0.944, 0.955, 0.987, 0.946, 0.949, 0.989, 0.942, 0.936, 0.985, 0.935, 0.916, 0.98, 0.925, 0.894, 0.973, 0.915, 0.871, 0.966, 0.904, 0.847, 0.959, 0.894, 0.824, 0.952, 0.883, 0.8, 0.945, 0.873, 0.776, 0.938, 0.863, 0.752, 0.932, 0.853, 0.729, 0.925, 0.843, 0.705, 0.919, 0.833, 0.682, 0.912, 0.823, 0.658, 0.906, 0.813, 0.635, 0.9, 0.803, 0.611, 0.894, 0.794, 0.588, 0.888, 0.784, 0.565, 0.882, 0.775, 0.542, 0.876, 0.765, 0.519, 0.871, 0.756, 0.496, 0.865, 0.747, 0.473, 0.859, 0.738, 0.45, 0.854, 0.728, 0.427, 0.848, 0.719, 0.404, 0.843, 0.71, 0.38, 0.838, 0.701, 0.357, 0.833, 0.692, 0.333, 0.827, 0.683, 0.31, 0.822, 0.674, 0.285, 0.817, 0.665, 0.26, 0.812, 0.656, 0.235, 0.807, 0.648, 0.208, 0.644, 0.642, 0.998, 0.654, 0.651, 0.993, 0.664, 0.66, 0.988, 0.674, 0.67, 0.983, 0.684, 0.679, 0.978, 0.694, 0.688, 0.974, 0.704, 0.697, 0.97, 0.715, 0.707, 0.967, 0.725, 0.716, 0.963, 0.735, 0.725, 0.96, 0.746, 0.735, 0.957, 0.757, 0.744, 0.955, 0.767, 0.753, 0.952, 0.778, 0.763, 0.95, 0.789, 0.772, 0.948, 0.8, 0.781, 0.947, 0.811, 0.791, 0.945, 0.822, 0.801, 0.944, 0.833, 0.81, 0.943, 0.845, 0.82, 0.943, 0.856, 0.83, 0.942, 0.868, 0.839, 0.942, 0.879, 0.849, 0.942, 0.891, 0.859, 0.943, 0.902, 0.869, 0.943, 0.914, 0.879, 0.944, 0.926, 0.889, 0.945, 0.937, 0.899, 0.946, 0.949, 0.908, 0.947, 0.959, 0.917, 0.948, 0.969, 0.924, 0.947, 0.978, 0.929, 0.944, 0.984, 0.93, 0.937, 0.986, 0.927, 0.924, 0.986, 0.921, 0.907, 0.982, 0.913, 0.887, 0.978, 0.904, 0.865, 0.972, 0.895, 0.842, 0.966, 0.885, 0.819, 0.959, 0.875, 0.795, 0.953, 0.865, 0.772, 0.946, 0.855, 0.749, 0.94, 0.846, 0.725, 0.934, 0.836, 0.702, 0.927, 0.826, 0.678, 0.921, 0.816, 0.655, 0.915, 0.807, 0.632, 0.909, 0.797, 0.609, 0.903, 0.788, 0.586, 0.897, 0.778, 0.562, 0.891, 0.769, 0.539, 0.886, 0.759, 0.516, 0.88, 0.75, 0.493, 0.874, 0.741, 0.471, 0.869, 0.732, 0.448, 0.863, 0.723, 0.425, 0.858, 0.713, 0.402, 0.852, 0.704, 0.378, 0.847, 0.695, 0.355, 0.842, 0.686, 0.331, 0.836, 0.677, 0.308, 0.831, 0.669, 0.283, 0.826, 0.66, 0.258, 0.821, 0.651, 0.233, 0.815, 0.642, 0.206, 0.653, 0.636, 0.998, 0.663, 0.646, 0.993, 0.673, 0.655, 0.988, 0.682, 0.665, 0.983, 0.692, 0.674, 0.979, 0.702, 0.683, 0.974, 0.712, 0.692, 0.97, 0.722, 0.702, 0.967, 0.733, 0.711, 0.963, 0.743, 0.72, 0.96, 0.753, 0.73, 0.957, 0.764, 0.739, 0.954, 0.774, 0.748, 0.952, 0.785, 0.757, 0.95, 0.796, 0.767, 0.948, 0.806, 0.776, 0.946, 0.817, 0.786, 0.945, 0.828, 0.795, 0.943, 0.839, 0.804, 0.942, 0.85, 0.814, 0.941, 0.861, 0.824, 0.941, 0.872, 0.833, 0.94, 0.884, 0.843, 0.94, 0.895, 0.852, 0.94, 0.906, 0.862, 0.94, 0.917, 0.871, 0.941, 0.928, 0.88, 0.941, 0.939, 0.889, 0.941, 0.949, 0.897, 0.941, 0.959, 0.904, 0.94, 0.968, 0.91, 0.938, 0.975, 0.914, 0.933, 0.981, 0.914, 0.925, 0.984, 0.912, 0.913, 0.985, 0.907, 0.897, 0.983, 0.9, 0.878, 0.98, 0.893, 0.857, 0.976, 0.884, 0.836, 0.971, 0.875, 0.813, 0.965, 0.866, 0.79, 0.959, 0.856, 0.767, 0.954, 0.847, 0.744, 0.947, 0.837, 0.721, 0.941, 0.828, 0.698, 0.935, 0.818, 0.675, 0.929, 0.809, 0.652, 0.923, 0.8, 0.629, 0.917, 0.79, 0.605, 0.912, 0.781, 0.582, 0.906, 0.771, 0.56, 0.9, 0.762, 0.537, 0.894, 0.753, 0.514, 0.889, 0.744, 0.491, 0.883, 0.735, 0.468, 0.877, 0.725, 0.445, 0.872, 0.716, 0.422, 0.866, 0.707, 0.399, 0.861, 0.698, 0.376, 0.856, 0.689, 0.353, 0.85, 0.68, 0.329, 0.845, 0.672, 0.305, 0.84, 0.663, 0.281, 0.834, 0.654, 0.256, 0.829, 0.645, 0.231, 0.824, 0.636, 0.204, 0.662, 0.631, 0.998, 0.672, 0.641, 0.993, 0.681, 0.65, 0.988, 0.691, 0.659, 0.983, 0.7, 0.669, 0.979, 0.71, 0.678, 0.974, 0.72, 0.687, 0.97, 0.73, 0.696, 0.966, 0.74, 0.706, 0.963, 0.75, 0.715, 0.96, 0.76, 0.724, 0.957, 0.771, 0.733, 0.954, 0.781, 0.742, 0.951, 0.791, 0.752, 0.949, 0.802, 0.761, 0.947, 0.812, 0.77, 0.945, 0.823, 0.779, 0.943, 0.834, 0.789, 0.942, 0.844, 0.798, 0.941, 0.855, 0.807, 0.94, 0.866, 0.817, 0.939, 0.877, 0.826, 0.938, 0.887, 0.835, 0.938, 0.898, 0.844, 0.937, 0.909, 0.853, 0.937, 0.919, 0.862, 0.937, 0.93, 0.87, 0.936, 0.94, 0.878, 0.936, 0.95, 0.885, 0.934, 0.958, 0.891, 0.932, 0.967, 0.896, 0.928, 0.974, 0.898, 0.922, 0.979, 0.899, 0.914, 0.982, 0.897, 0.902, 0.984, 0.893, 0.886, 0.984, 0.887, 0.869, 0.982, 0.88, 0.849, 0.979, 0.872, 0.828, 0.975, 0.864, 0.807, 0.97, 0.856, 0.785, 0.965, 0.847, 0.762, 0.959, 0.838, 0.739, 0.954, 0.829, 0.717, 0.948, 0.819, 0.694, 0.943, 0.81, 0.671, 0.937, 0.801, 0.648, 0.931, 0.792, 0.625, 0.925, 0.782, 0.602, 0.919, 0.773, 0.579, 0.914, 0.764, 0.556, 0.908, 0.755, 0.533, 0.902, 0.746, 0.511, 0.897, 0.737, 0.488, 0.891, 0.728, 0.465, 0.886, 0.719, 0.442, 0.88, 0.71, 0.42, 0.875, 0.701, 0.397, 0.869, 0.692, 0.374, 0.864, 0.683, 0.35, 0.858, 0.674, 0.327, 0.853, 0.665, 0.303, 0.848, 0.657, 0.279, 0.842, 0.648, 0.254, 0.837, 0.639, 0.229, 0.832, 0.63, 0.202, 0.671, 0.625, 0.998, 0.68, 0.635, 0.993, 0.689, 0.644, 0.988, 0.698, 0.654, 0.983, 0.708, 0.663, 0.978, 0.718, 0.672, 0.974, 0.727, 0.681, 0.97, 0.737, 0.691, 0.966, 0.747, 0.7, 0.962, 0.757, 0.709, 0.959, 0.767, 0.718, 0.956, 0.777, 0.727, 0.953, 0.787, 0.736, 0.95, 0.797, 0.745, 0.948, 0.807, 0.755, 0.946, 0.818, 0.764, 0.944, 0.828, 0.773, 0.942, 0.839, 0.782, 0.94, 0.849, 0.791, 0.939, 0.859, 0.8, 0.938, 0.87, 0.809, 0.937, 0.88, 0.818, 0.936, 0.891, 0.827, 0.935, 0.901, 0.835, 0.934, 0.911, 0.844, 0.933, 0.921, 0.852, 0.932, 0.931, 0.859, 0.931, 0.941, 0.866, 0.929, 0.95, 0.873, 0.927, 0.958, 0.878, 0.923, 0.966, 0.881, 0.919, 0.972, 0.883, 0.912, 0.977, 0.883, 0.903, 0.981, 0.882, 0.891, 0.983, 0.878, 0.876, 0.984, 0.873, 0.859, 0.983, 0.867, 0.841, 0.98, 0.86, 0.821, 0.977, 0.853, 0.8, 0.974, 0.845, 0.778, 0.969, 0.836, 0.756, 0.964, 0.828, 0.734, 0.959, 0.819, 0.712, 0.954, 0.81, 0.689, 0.949, 0.801, 0.666, 0.943, 0.792, 0.644, 0.938, 0.783, 0.621, 0.932, 0.774, 0.598, 0.927, 0.765, 0.575, 0.921, 0.756, 0.553, 0.916, 0.747, 0.53, 0.91, 0.738, 0.507, 0.904, 0.729, 0.485, 0.899, 0.721, 0.462, 0.893, 0.712, 0.439, 0.888, 0.703, 0.417, 0.882, 0.694, 0.394, 0.877, 0.685, 0.371, 0.871, 0.676, 0.348, 0.866, 0.668, 0.324, 0.861, 0.659, 0.301, 0.855, 0.65, 0.277, 0.85, 0.641, 0.252, 0.845, 0.633, 0.226, 0.839, 0.624, 0.2, 0.679, 0.619, 0.998, 0.688, 0.629, 0.993, 0.697, 0.638, 0.988, 0.706, 0.648, 0.983, 0.715, 0.657, 0.978, 0.725, 0.666, 0.974, 0.734, 0.675, 0.969, 0.744, 0.684, 0.965, 0.754, 0.693, 0.962, 0.763, 0.703, 0.958, 0.773, 0.712, 0.955, 0.783, 0.721, 0.952, 0.793, 0.73, 0.949, 0.803, 0.739, 0.947, 0.813, 0.748, 0.944, 0.823, 0.757, 0.942, 0.833, 0.766, 0.94, 0.843, 0.774, 0.938, 0.853, 0.783, 0.937, 0.863, 0.792, 0.935, 0.874, 0.801, 0.934, 0.884, 0.809, 0.932, 0.894, 0.818, 0.931, 0.904, 0.826, 0.93, 0.913, 0.833, 0.928, 0.923, 0.841, 0.927, 0.932, 0.848, 0.925, 0.941, 0.854, 0.922, 0.95, 0.859, 0.919, 0.957, 0.864, 0.915, 0.965, 0.867, 0.909, 0.971, 0.868, 0.901, 0.976, 0.868, 0.892, 0.98, 0.867, 0.88, 0.982, 0.863, 0.866, 0.983, 0.859, 0.849, 0.983, 0.854, 0.832, 0.982, 0.847, 0.812, 0.979, 0.84, 0.792, 0.976, 0.833, 0.771, 0.973, 0.825, 0.75, 0.969, 0.817, 0.728, 0.964, 0.809, 0.706, 0.959, 0.8, 0.684, 0.954, 0.792, 0.661, 0.949, 0.783, 0.639, 0.944, 0.774, 0.617, 0.939, 0.766, 0.594, 0.933, 0.757, 0.572, 0.928, 0.748, 0.549, 0.922, 0.739, 0.527, 0.917, 0.731, 0.504, 0.911, 0.722, 0.481, 0.906, 0.713, 0.459, 0.901, 0.704, 0.436, 0.895, 0.695, 0.414, 0.89, 0.687, 0.391, 0.884, 0.678, 0.368, 0.879, 0.669, 0.345, 0.873, 0.661, 0.322, 0.868, 0.652, 0.298, 0.863, 0.643, 0.274, 0.857, 0.635, 0.249, 0.852, 0.626, 0.224, 0.846, 0.617, 0.197, 0.686, 0.613, 0.998, 0.695, 0.622, 0.993, 0.704, 0.632, 0.987, 0.713, 0.641, 0.982, 0.722, 0.65, 0.977, 0.732, 0.66, 0.973, 0.741, 0.669, 0.969, 0.75, 0.678, 0.965, 0.76, 0.687, 0.961, 0.769, 0.696, 0.957, 0.779, 0.705, 0.954, 0.789, 0.714, 0.951, 0.798, 0.723, 0.948, 0.808, 0.731, 0.945, 0.818, 0.74, 0.943, 0.828, 0.749, 0.94, 0.838, 0.758, 0.938, 0.847, 0.766, 0.936, 0.857, 0.775, 0.934, 0.867, 0.783, 0.932, 0.877, 0.792, 0.93, 0.887, 0.8, 0.929, 0.896, 0.808, 0.927, 0.906, 0.815, 0.925, 0.915, 0.823, 0.923, 0.924, 0.829, 0.921, 0.933, 0.836, 0.918, 0.942, 0.841, 0.915, 0.95, 0.846, 0.911, 0.957, 0.85, 0.906, 0.964, 0.852, 0.899, 0.97, 0.853, 0.891, 0.975, 0.853, 0.881, 0.979, 0.852, 0.869, 0.981, 0.849, 0.855, 0.983, 0.845, 0.84, 0.983, 0.84, 0.822, 0.982, 0.834, 0.804, 0.981, 0.828, 0.784, 0.978, 0.821, 0.764, 0.975, 0.814, 0.743, 0.972, 0.806, 0.722, 0.968, 0.798, 0.7, 0.964, 0.79, 0.678, 0.959, 0.782, 0.656, 0.954, 0.773, 0.634, 0.949, 0.765, 0.612, 0.944, 0.757, 0.59, 0.939, 0.748, 0.567, 0.934, 0.739, 0.545, 0.929, 0.731, 0.523, 0.923, 0.722, 0.5, 0.918, 0.714, 0.478, 0.913, 0.705, 0.456, 0.907, 0.696, 0.433, 0.902, 0.688, 0.411, 0.896, 0.679, 0.388, 0.891, 0.67, 0.365, 0.886, 0.662, 0.342, 0.88, 0.653, 0.319, 0.875, 0.645, 0.295, 0.869, 0.636, 0.271, 0.864, 0.628, 0.247, 0.859, 0.619, 0.221, 0.853, 0.611, 0.195, 0.694, 0.606, 0.998, 0.703, 0.616, 0.992, 0.711, 0.625, 0.987, 0.72, 0.634, 0.982, 0.729, 0.644, 0.977, 0.738, 0.653, 0.972, 0.747, 0.662, 0.968, 0.757, 0.671, 0.964, 0.766, 0.68, 0.96, 0.775, 0.689, 0.956, 0.785, 0.698, 0.953, 0.794, 0.706, 0.949, 0.804, 0.715, 0.946, 0.813, 0.724, 0.943, 0.823, 0.732, 0.941, 0.832, 0.741, 0.938, 0.842, 0.749, 0.936, 0.851, 0.758, 0.933, 0.861, 0.766, 0.931, 0.87, 0.774, 0.929, 0.88, 0.782, 0.927, 0.889, 0.79, 0.924, 0.899, 0.797, 0.922, 0.908, 0.805, 0.92, 0.917, 0.811, 0.917, 0.925, 0.818, 0.914, 0.934, 0.823, 0.911, 0.942, 0.828, 0.907, 0.95, 0.832, 0.902, 0.957, 0.836, 0.896, 0.963, 0.838, 0.889, 0.969, 0.839, 0.881, 0.974, 0.838, 0.871, 0.978, 0.837, 0.859, 0.98, 0.834, 0.845, 0.982, 0.831, 0.83, 0.983, 0.826, 0.813, 0.983, 0.821, 0.795, 0.982, 0.815, 0.776, 0.98, 0.809, 0.757, 0.978, 0.802, 0.736, 0.975, 0.794, 0.715, 0.971, 0.787, 0.694, 0.967, 0.779, 0.673, 0.963, 0.771, 0.651, 0.959, 0.763, 0.629, 0.954, 0.755, 0.607, 0.949, 0.747, 0.585, 0.944, 0.739, 0.563, 0.939, 0.73, 0.541, 0.934, 0.722, 0.519, 0.929, 0.714, 0.496, 0.924, 0.705, 0.474, 0.919, 0.697, 0.452, 0.913, 0.688, 0.43, 0.908, 0.68, 0.407, 0.903, 0.671, 0.385, 0.897, 0.663, 0.362, 0.892, 0.654, 0.339, 0.887, 0.646, 0.316, 0.881, 0.637, 0.293, 0.876, 0.629, 0.269, 0.87, 0.62, 0.244, 0.865, 0.612, 0.219, 0.86, 0.604, 0.192, 0.701, 0.599, 0.997, 0.71, 0.609, 0.992, 0.718, 0.618, 0.986, 0.727, 0.627, 0.981, 0.736, 0.636, 0.976, 0.745, 0.645, 0.971, 0.754, 0.655, 0.967, 0.763, 0.663, 0.963, 0.772, 0.672, 0.959, 0.781, 0.681, 0.955, 0.79, 0.69, 0.951, 0.799, 0.699, 0.948, 0.808, 0.707, 0.944, 0.818, 0.716, 0.941, 0.827, 0.724, 0.938, 0.836, 0.732, 0.935, 0.846, 0.741, 0.933, 0.855, 0.749, 0.93, 0.864, 0.757, 0.928, 0.874, 0.765, 0.925, 0.883, 0.772, 0.923, 0.892, 0.78, 0.92, 0.901, 0.787, 0.917, 0.91, 0.793, 0.914, 0.918, 0.8, 0.911, 0.927, 0.805, 0.908, 0.935, 0.811, 0.904, 0.942, 0.815, 0.899, 0.95, 0.819, 0.894, 0.956, 0.821, 0.887, 0.963, 0.823, 0.88, 0.968, 0.824, 0.871, 0.973, 0.824, 0.86, 0.977, 0.822, 0.849, 0.98, 0.82, 0.835, 0.982, 0.817, 0.82, 0.983, 0.812, 0.804, 0.983, 0.808, 0.786, 0.983, 0.802, 0.768, 0.981, 0.796, 0.749, 0.979, 0.789, 0.729, 0.977, 0.783, 0.709, 0.974, 0.776, 0.688, 0.97, 0.768, 0.667, 0.967, 0.761, 0.645, 0.963, 0.753, 0.624, 0.958, 0.745, 0.602, 0.954, 0.737, 0.58, 0.949, 0.729, 0.558, 0.944, 0.721, 0.536, 0.939, 0.713, 0.514, 0.934, 0.704, 0.492, 0.929, 0.696, 0.47, 0.924, 0.688, 0.448, 0.919, 0.68, 0.426, 0.914, 0.671, 0.404, 0.908, 0.663, 0.381, 0.903, 0.655, 0.359, 0.898, 0.646, 0.336, 0.893, 0.638, 0.313, 0.887, 0.629, 0.29, 0.882, 0.621, 0.266, 0.876, 0.613, 0.241, 0.871, 0.604, 0.216, 0.866, 0.596, 0.189, 0.708, 0.592, 0.997, 0.716, 0.601, 0.991, 0.725, 0.611, 0.985, 0.733, 0.62, 0.98, 0.742, 0.629, 0.975, 0.751, 0.638, 0.97, 0.759, 0.647, 0.966, 0.768, 0.656, 0.961, 0.777, 0.665, 0.957, 0.786, 0.673, 0.953, 0.795, 0.682, 0.949, 0.804, 0.69, 0.946, 0.813, 0.699, 0.942, 0.822, 0.707, 0.939, 0.831, 0.715, 0.936, 0.84, 0.723, 0.933, 0.849, 0.731, 0.93, 0.859, 0.739, 0.927, 0.868, 0.747, 0.924, 0.876, 0.754, 0.921, 0.885, 0.762, 0.918, 0.894, 0.769, 0.915, 0.903, 0.775, 0.912, 0.911, 0.782, 0.909, 0.92, 0.787, 0.905, 0.928, 0.793, 0.901, 0.935, 0.798, 0.896, 0.943, 0.802, 0.891, 0.95, 0.805, 0.885, 0.956, 0.807, 0.878, 0.962, 0.809, 0.87, 0.967, 0.809, 0.861, 0.972, 0.809, 0.85, 0.976, 0.808, 0.838, 0.979, 0.805, 0.825, 0.981, 0.802, 0.81, 0.983, 0.799, 0.795, 0.983, 0.794, 0.778, 0.983, 0.789, 0.76, 0.982, 0.783, 0.741, 0.981, 0.777, 0.721, 0.979, 0.771, 0.701, 0.976, 0.764, 0.681, 0.973, 0.757, 0.66, 0.97, 0.75, 0.639, 0.966, 0.742, 0.618, 0.962, 0.735, 0.597, 0.958, 0.727, 0.575, 0.953, 0.719, 0.553, 0.949, 0.711, 0.532, 0.944, 0.703, 0.51, 0.939, 0.695, 0.488, 0.934, 0.687, 0.466, 0.929, 0.679, 0.444, 0.924, 0.671, 0.422, 0.919, 0.663, 0.4, 0.914, 0.654, 0.378, 0.909, 0.646, 0.355, 0.903, 0.638, 0.333, 0.898, 0.63, 0.31, 0.893, 0.621, 0.287, 0.887, 0.613, 0.263, 0.882, 0.605, 0.238, 0.877, 0.597, 0.213, 0.871, 0.589, 0.186, 0.715, 0.584, 0.996, 0.723, 0.593, 0.99, 0.731, 0.603, 0.984, 0.739, 0.612, 0.979, 0.748, 0.621, 0.974, 0.756, 0.63, 0.969, 0.765, 0.639, 0.964, 0.774, 0.648, 0.96, 0.782, 0.656, 0.955, 0.791, 0.665, 0.951, 0.8, 0.673, 0.947, 0.809, 0.682, 0.943, 0.818, 0.69, 0.94, 0.826, 0.698, 0.936, 0.835, 0.706, 0.933, 0.844, 0.714, 0.93, 0.853, 0.722, 0.926, 0.862, 0.729, 0.923, 0.871, 0.737, 0.92, 0.879, 0.744, 0.917, 0.888, 0.751, 0.913, 0.896, 0.758, 0.91, 0.905, 0.764, 0.906, 0.913, 0.77, 0.903, 0.921, 0.775, 0.898, 0.929, 0.78, 0.894, 0.936, 0.784, 0.889, 0.943, 0.788, 0.883, 0.95, 0.791, 0.877, 0.956, 0.793, 0.869, 0.962, 0.794, 0.861, 0.967, 0.795, 0.851, 0.971, 0.794, 0.841, 0.975, 0.793, 0.829, 0.978, 0.791, 0.815, 0.981, 0.788, 0.801, 0.982, 0.785, 0.785, 0.983, 0.78, 0.769, 0.983, 0.776, 0.751, 0.983, 0.77, 0.733, 0.982, 0.764, 0.714, 0.98, 0.758, 0.694, 0.978, 0.752, 0.674, 0.975, 0.745, 0.654, 0.972, 0.738, 0.633, 0.969, 0.731, 0.612, 0.965, 0.724, 0.591, 0.961, 0.716, 0.57, 0.957, 0.709, 0.548, 0.953, 0.701, 0.527, 0.948, 0.693, 0.505, 0.943, 0.685, 0.484, 0.939, 0.678, 0.462, 0.934, 0.67, 0.44, 0.929, 0.662, 0.418, 0.924, 0.654, 0.396, 0.919, 0.646, 0.374, 0.914, 0.637, 0.352, 0.908, 0.629, 0.329, 0.903, 0.621, 0.307, 0.898, 0.613, 0.283, 0.893, 0.605, 0.26, 0.887, 0.597, 0.235, 0.882, 0.589, 0.21, 0.876, 0.581, 0.183, 0.721, 0.576, 0.995, 0.729, 0.585, 0.989, 0.737, 0.595, 0.983, 0.745, 0.604, 0.978, 0.754, 0.613, 0.973, 0.762, 0.622, 0.968, 0.77, 0.631, 0.963, 0.779, 0.639, 0.958, 0.787, 0.648, 0.954, 0.796, 0.656, 0.949, 0.805, 0.665, 0.945, 0.813, 0.673, 0.941, 0.822, 0.681, 0.937, 0.83, 0.689, 0.933, 0.839, 0.697, 0.93, 0.848, 0.704, 0.926, 0.856, 0.712, 0.923, 0.865, 0.719, 0.919, 0.873, 0.726, 0.916, 0.882, 0.733, 0.912, 0.89, 0.74, 0.908, 0.898, 0.746, 0.905, 0.906, 0.752, 0.901, 0.914, 0.757, 0.896, 0.922, 0.762, 0.892, 0.929, 0.767, 0.887, 0.937, 0.771, 0.881, 0.943, 0.774, 0.875, 0.95, 0.777, 0.868, 0.956, 0.779, 0.86, 0.961, 0.78, 0.851, 0.966, 0.78, 0.842, 0.971, 0.78, 0.831, 0.975, 0.779, 0.819, 0.978, 0.777, 0.806, 0.98, 0.774, 0.791, 0.982, 0.771, 0.776, 0.983, 0.767, 0.76, 0.984, 0.762, 0.742, 0.983, 0.757, 0.725, 0.983, 0.752, 0.706, 0.981, 0.746, 0.687, 0.979, 0.74, 0.667, 0.977, 0.733, 0.647, 0.974, 0.727, 0.627, 0.971, 0.72, 0.606, 0.968, 0.713, 0.585, 0.964, 0.706, 0.564, 0.96, 0.698, 0.543, 0.956, 0.691, 0.522, 0.952, 0.683, 0.501, 0.947, 0.676, 0.479, 0.943, 0.668, 0.458, 0.938, 0.66, 0.436, 0.933, 0.652, 0.414, 0.928, 0.644, 0.392, 0.923, 0.636, 0.37, 0.918, 0.629, 0.348, 0.913, 0.621, 0.326, 0.908, 0.613, 0.303, 0.903, 0.605, 0.28, 0.897, 0.597, 0.257, 0.892, 0.589, 0.232, 0.887, 0.581, 0.207, 0.881, 0.573, 0.18, 0.727, 0.568, 0.994, 0.735, 0.577, 0.988, 0.743, 0.586, 0.982, 0.751, 0.595, 0.977, 0.759, 0.604, 0.971, 0.767, 0.613, 0.966, 0.776, 0.622, 0.961, 0.784, 0.63, 0.956, 0.792, 0.639, 0.951, 0.801, 0.647, 0.947, 0.809, 0.655, 0.943, 0.817, 0.663, 0.938, 0.826, 0.671, 0.934, 0.834, 0.679, 0.93, 0.843, 0.687, 0.927, 0.851, 0.694, 0.923, 0.859, 0.702, 0.919, 0.868, 0.709, 0.915, 0.876, 0.715, 0.911, 0.884, 0.722, 0.907, 0.892, 0.728, 0.903, 0.9, 0.734, 0.899, 0.908, 0.74, 0.895, 0.916, 0.745, 0.89, 0.923, 0.75, 0.885, 0.93, 0.754, 0.879, 0.937, 0.758, 0.873, 0.944, 0.761, 0.867, 0.95, 0.763, 0.859, 0.956, 0.765, 0.851, 0.961, 0.766, 0.842, 0.966, 0.766, 0.832, 0.97, 0.766, 0.821, 0.974, 0.764, 0.809, 0.977, 0.762, 0.796, 0.98, 0.76, 0.782, 0.982, 0.757, 0.767, 0.983, 0.753, 0.751, 0.984, 0.749, 0.734, 0.984, 0.744, 0.716, 0.983, 0.739, 0.698, 0.982, 0.733, 0.679, 0.98, 0.727, 0.66, 0.978, 0.721, 0.64, 0.976, 0.715, 0.62, 0.973, 0.708, 0.6, 0.97, 0.701, 0.579, 0.967, 0.694, 0.559, 0.963, 0.687, 0.538, 0.959, 0.68, 0.517, 0.955, 0.673, 0.496, 0.951, 0.665, 0.474, 0.946, 0.658, 0.453, 0.942, 0.65, 0.432, 0.937, 0.643, 0.41, 0.932, 0.635, 0.388, 0.927, 0.627, 0.367, 0.922, 0.619, 0.345, 0.917, 0.612, 0.322, 0.912, 0.604, 0.3, 0.907, 0.596, 0.277, 0.902, 0.588, 0.253, 0.897, 0.58, 0.229, 0.891, 0.572, 0.204, 0.886, 0.564, 0.177, 0.733, 0.559, 0.993, 0.741, 0.568, 0.987, 0.749, 0.577, 0.981, 0.757, 0.587, 0.975, 0.765, 0.595, 0.97, 0.773, 0.604, 0.964, 0.781, 0.613, 0.959, 0.789, 0.621, 0.954, 0.797, 0.63, 0.949, 0.805, 0.638, 0.945, 0.813, 0.646, 0.94, 0.821, 0.654, 0.936, 0.83, 0.662, 0.931, 0.838, 0.669, 0.927, 0.846, 0.677, 0.923, 0.854, 0.684, 0.919, 0.862, 0.691, 0.915, 0.87, 0.698, 0.911, 0.879, 0.704, 0.907, 0.886, 0.711, 0.902, 0.894, 0.717, 0.898, 0.902, 0.722, 0.893, 0.91, 0.727, 0.889, 0.917, 0.732, 0.883, 0.924, 0.737, 0.878, 0.931, 0.741, 0.872, 0.938, 0.744, 0.866, 0.944, 0.747, 0.859, 0.95, 0.749, 0.851, 0.956, 0.751, 0.842, 0.961, 0.751, 0.833, 0.966, 0.752, 0.823, 0.97, 0.751, 0.812, 0.974, 0.75, 0.8, 0.977, 0.748, 0.787, 0.979, 0.746, 0.773, 0.981, 0.743, 0.758, 0.983, 0.739, 0.742, 0.984, 0.735, 0.725, 0.984, 0.731, 0.708, 0.983, 0.726, 0.69, 0.983, 0.721, 0.672, 0.981, 0.715, 0.653, 0.98, 0.709, 0.633, 0.977, 0.703, 0.614, 0.975, 0.697, 0.594, 0.972, 0.69, 0.573, 0.969, 0.683, 0.553, 0.965, 0.676, 0.532, 0.962, 0.669, 0.512, 0.958, 0.662, 0.491, 0.954, 0.655, 0.47, 0.949, 0.648, 0.448, 0.945, 0.64, 0.427, 0.941, 0.633, 0.406, 0.936, 0.625, 0.384, 0.931, 0.618, 0.363, 0.926, 0.61, 0.341, 0.921, 0.602, 0.319, 0.916, 0.595, 0.296, 0.911, 0.587, 0.273, 0.906, 0.579, 0.25, 0.901, 0.571, 0.226, 0.896, 0.563, 0.201, 0.89, 0.556, 0.174, 0.739, 0.55, 0.992, 0.747, 0.559, 0.986, 0.754, 0.568, 0.98, 0.762, 0.577, 0.974, 0.77, 0.586, 0.968, 0.778, 0.595, 0.962, 0.785, 0.603, 0.957, 0.793, 0.612, 0.952, 0.801, 0.62, 0.947, 0.809, 0.628, 0.942, 0.817, 0.636, 0.937, 0.825, 0.644, 0.933, 0.833, 0.651, 0.928, 0.841, 0.659, 0.924, 0.849, 0.666, 0.919, 0.857, 0.673, 0.915, 0.865, 0.68, 0.911, 0.873, 0.686, 0.906, 0.881, 0.693, 0.902, 0.889, 0.699, 0.897, 0.896, 0.705, 0.892, 0.904, 0.71, 0.887, 0.911, 0.715, 0.882, 0.918, 0.72, 0.877, 0.925, 0.724, 0.871, 0.932, 0.727, 0.865, 0.938, 0.73, 0.858, 0.944, 0.733, 0.85, 0.95, 0.735, 0.842, 0.956, 0.736, 0.834, 0.961, 0.737, 0.824, 0.965, 0.737, 0.814, 0.97, 0.737, 0.802, 0.973, 0.736, 0.79, 0.976, 0.734, 0.777, 0.979, 0.732, 0.763, 0.981, 0.729, 0.749, 0.982, 0.726, 0.733, 0.983, 0.722, 0.717, 0.984, 0.717, 0.7, 0.984, 0.713, 0.682, 0.983, 0.708, 0.664, 0.982, 0.702, 0.645, 0.98, 0.697, 0.626, 0.979, 0.691, 0.607, 0.976, 0.685, 0.587, 0.974, 0.678, 0.567, 0.971, 0.672, 0.547, 0.967, 0.665, 0.527, 0.964, 0.658, 0.506, 0.96, 0.651, 0.485, 0.956, 0.644, 0.465, 0.952, 0.637, 0.444, 0.948, 0.63, 0.423, 0.944, 0.623, 0.401, 0.939, 0.615, 0.38, 0.934, 0.608, 0.358, 0.93, 0.6, 0.337, 0.925, 0.593, 0.315, 0.92, 0.585, 0.292, 0.915, 0.578, 0.27, 0.91, 0.57, 0.246, 0.905, 0.562, 0.222, 0.899, 0.555, 0.197, 0.894, 0.547, 0.171, 0.745, 0.54, 0.991, 0.752, 0.55, 0.984, 0.76, 0.559, 0.978, 0.767, 0.568, 0.972, 0.775, 0.577, 0.966, 0.782, 0.585, 0.96, 0.79, 0.594, 0.955, 0.798, 0.602, 0.95, 0.806, 0.61, 0.944, 0.813, 0.618, 0.939, 0.821, 0.626, 0.934, 0.829, 0.634, 0.93, 0.837, 0.641, 0.925, 0.845, 0.648, 0.92, 0.852, 0.655, 0.915, 0.86, 0.662, 0.911, 0.868, 0.669, 0.906, 0.876, 0.675, 0.901, 0.883, 0.681, 0.897, 0.891, 0.687, 0.892, 0.898, 0.692, 0.887, 0.905, 0.697, 0.881, 0.912, 0.702, 0.876, 0.919, 0.707, 0.87, 0.926, 0.71, 0.864, 0.932, 0.714, 0.857, 0.939, 0.717, 0.85, 0.945, 0.719, 0.842, 0.95, 0.721, 0.834, 0.956, 0.722, 0.825, 0.961, 0.723, 0.815, 0.965, 0.723, 0.804, 0.969, 0.723, 0.793, 0.973, 0.722, 0.781, 0.976, 0.72, 0.768, 0.978, 0.718, 0.754, 0.981, 0.715, 0.739, 0.982, 0.712, 0.724, 0.983, 0.708, 0.708, 0.984, 0.704, 0.691, 0.984, 0.7, 0.674, 0.983, 0.695, 0.656, 0.982, 0.69, 0.638, 0.981, 0.684, 0.619, 0.979, 0.679, 0.6, 0.977, 0.673, 0.581, 0.975, 0.666, 0.561, 0.972, 0.66, 0.541, 0.969, 0.654, 0.521, 0.966, 0.647, 0.501, 0.962, 0.64, 0.48, 0.959, 0.634, 0.459, 0.955, 0.627, 0.439, 0.951, 0.62, 0.418, 0.946, 0.612, 0.397, 0.942, 0.605, 0.376, 0.937, 0.598, 0.354, 0.933, 0.591, 0.333, 0.928, 0.583, 0.311, 0.923, 0.576, 0.289, 0.918, 0.568, 0.266, 0.913, 0.561, 0.243, 0.908, 0.553, 0.219, 0.903, 0.546, 0.194, 0.898, 0.538, 0.167, 0.75, 0.531, 0.989, 0.757, 0.54, 0.983, 0.765, 0.549, 0.976, 0.772, 0.558, 0.97, 0.779, 0.567, 0.964, 0.787, 0.575, 0.958, 0.794, 0.584, 0.953, 0.802, 0.592, 0.947, 0.81, 0.6, 0.942, 0.817, 0.608, 0.936, 0.825, 0.615, 0.931, 0.833, 0.623, 0.926, 0.84, 0.63, 0.921, 0.848, 0.637, 0.916, 0.855, 0.644, 0.911, 0.863, 0.651, 0.907, 0.87, 0.657, 0.902, 0.878, 0.663, 0.897, 0.885, 0.669, 0.891, 0.893, 0.675, 0.886, 0.9, 0.68, 0.881, 0.907, 0.685, 0.875, 0.914, 0.689, 0.869, 0.92, 0.693, 0.863, 0.927, 0.697, 0.857, 0.933, 0.7, 0.85, 0.939, 0.703, 0.842, 0.945, 0.705, 0.834, 0.95, 0.707, 0.825, 0.956, 0.708, 0.816, 0.96, 0.709, 0.806, 0.965, 0.709, 0.795, 0.969, 0.708, 0.784, 0.972, 0.707, 0.772, 0.975, 0.706, 0.759, 0.978, 0.704, 0.745, 0.98, 0.701, 0.731, 0.982, 0.698, 0.715, 0.983, 0.694, 0.699, 0.984, 0.691, 0.683, 0.984, 0.686, 0.666, 0.983, 0.682, 0.648, 0.983, 0.677, 0.63, 0.982, 0.672, 0.612, 0.98, 0.666, 0.593, 0.978, 0.66, 0.574, 0.976, 0.655, 0.554, 0.973, 0.648, 0.535, 0.971, 0.642, 0.515, 0.967, 0.636, 0.495, 0.964, 0.629, 0.475, 0.961, 0.623, 0.454, 0.957, 0.616, 0.434, 0.953, 0.609, 0.413, 0.949, 0.602, 0.392, 0.944, 0.595, 0.371, 0.94, 0.588, 0.35, 0.936, 0.58, 0.328, 0.931, 0.573, 0.307, 0.926, 0.566, 0.285, 0.921, 0.559, 0.262, 0.916, 0.551, 0.239, 0.911, 0.544, 0.215, 0.906, 0.536, 0.19, 0.901, 0.529, 0.164, 0.755, 0.521, 0.988, 0.762, 0.53, 0.981, 0.77, 0.539, 0.975, 0.777, 0.548, 0.968, 0.784, 0.557, 0.962, 0.791, 0.565, 0.956, 0.799, 0.573, 0.95, 0.806, 0.582, 0.944, 0.814, 0.589, 0.939, 0.821, 0.597, 0.933, 0.828, 0.605, 0.928, 0.836, 0.612, 0.923, 0.843, 0.619, 0.918, 0.851, 0.626, 0.912, 0.858, 0.633, 0.907, 0.866, 0.639, 0.902, 0.873, 0.645, 0.897, 0.88, 0.651, 0.892, 0.887, 0.657, 0.886, 0.894, 0.662, 0.881, 0.901, 0.667, 0.875, 0.908, 0.672, 0.869, 0.915, 0.676, 0.863, 0.921, 0.68, 0.856, 0.928, 0.684, 0.849, 0.934, 0.687, 0.842, 0.94, 0.689, 0.834, 0.945, 0.691, 0.826, 0.951, 0.693, 0.817, 0.956, 0.694, 0.807, 0.96, 0.695, 0.797, 0.964, 0.695, 0.787, 0.968, 0.694, 0.775, 0.972, 0.693, 0.763, 0.975, 0.692, 0.75, 0.977, 0.69, 0.736, 0.98, 0.687, 0.722, 0.981, 0.684, 0.707, 0.982, 0.681, 0.691, 0.983, 0.677, 0.675, 0.984, 0.673, 0.658, 0.983, 0.669, 0.641, 0.983, 0.664, 0.623, 0.982, 0.659, 0.605, 0.98, 0.654, 0.586, 0.979, 0.648, 0.567, 0.977, 0.642, 0.548, 0.974, 0.637, 0.529, 0.972, 0.63, 0.509, 0.969, 0.624, 0.489, 0.966, 0.618, 0.469, 0.962, 0.611, 0.449, 0.959, 0.605, 0.429, 0.955, 0.598, 0.408, 0.951, 0.591, 0.387, 0.947, 0.584, 0.367, 0.942, 0.577, 0.346, 0.938, 0.57, 0.324, 0.933, 0.563, 0.303, 0.929, 0.556, 0.281, 0.924, 0.549, 0.258, 0.919, 0.541, 0.235, 0.914, 0.534, 0.212, 0.909, 0.527, 0.187, 0.904, 0.519, 0.16, 0.76, 0.51, 0.986, 0.767, 0.52, 0.979, 0.774, 0.529, 0.973, 0.781, 0.538, 0.966, 0.788, 0.546, 0.96, 0.796, 0.555, 0.954, 0.803, 0.563, 0.948, 0.81, 0.571, 0.942, 0.817, 0.579, 0.936, 0.825, 0.586, 0.93, 0.832, 0.594, 0.925, 0.839, 0.601, 0.919, 0.846, 0.608, 0.914, 0.854, 0.615, 0.908, 0.861, 0.621, 0.903, 0.868, 0.627, 0.897, 0.875, 0.633, 0.892, 0.882, 0.639, 0.886, 0.889, 0.645, 0.881, 0.896, 0.65, 0.875, 0.903, 0.655, 0.869, 0.909, 0.659, 0.863, 0.916, 0.663, 0.856, 0.922, 0.667, 0.849, 0.928, 0.67, 0.842, 0.934, 0.673, 0.834, 0.94, 0.675, 0.826, 0.945, 0.677, 0.818, 0.951, 0.679, 0.809, 0.955, 0.68, 0.799, 0.96, 0.68, 0.789, 0.964, 0.68, 0.778, 0.968, 0.68, 0.766, 0.971, 0.679, 0.754, 0.974, 0.677, 0.741, 0.977, 0.676, 0.727, 0.979, 0.673, 0.713, 0.981, 0.67, 0.698, 0.982, 0.667, 0.682, 0.983, 0.664, 0.666, 0.983, 0.66, 0.65, 0.983, 0.655, 0.633, 0.983, 0.651, 0.615, 0.982, 0.646, 0.597, 0.981, 0.641, 0.579, 0.979, 0.636, 0.56, 0.977, 0.63, 0.541, 0.975, 0.625, 0.522, 0.973, 0.619, 0.503, 0.97, 0.613, 0.483, 0.967, 0.606, 0.463, 0.964, 0.6, 0.443, 0.96, 0.594, 0.423, 0.956, 0.587, 0.403, 0.953, 0.58, 0.383, 0.949, 0.574, 0.362, 0.944, 0.567, 0.341, 0.94, 0.56, 0.32, 0.936, 0.553, 0.298, 0.931, 0.546, 0.277, 0.926, 0.539, 0.254, 0.922, 0.532, 0.232, 0.917, 0.524, 0.208, 0.912, 0.517, 0.183, 0.906, 0.51, 0.156, 0.765, 0.499, 0.985, 0.772, 0.509, 0.978, 0.779, 0.518, 0.971, 0.786, 0.527, 0.964, 0.793, 0.535, 0.957, 0.8, 0.544, 0.951, 0.807, 0.552, 0.945, 0.814, 0.56, 0.939, 0.821, 0.568, 0.933, 0.828, 0.575, 0.927, 0.835, 0.582, 0.921, 0.842, 0.589, 0.915, 0.849, 0.596, 0.91, 0.856, 0.603, 0.904, 0.863, 0.609, 0.898, 0.87, 0.615, 0.893, 0.877, 0.621, 0.887, 0.884, 0.627, 0.881, 0.891, 0.632, 0.875, 0.898, 0.637, 0.869, 0.904, 0.642, 0.863, 0.911, 0.646, 0.856, 0.917, 0.65, 0.849, 0.923, 0.653, 0.842, 0.929, 0.657, 0.835, 0.935, 0.659, 0.827, 0.94, 0.662, 0.818, 0.946, 0.663, 0.81, 0.951, 0.665, 0.8, 0.955, 0.666, 0.79, 0.96, 0.666, 0.78, 0.964, 0.666, 0.769, 0.967, 0.666, 0.757, 0.971, 0.665, 0.745, 0.974, 0.663, 0.732, 0.976, 0.662, 0.718, 0.978, 0.659, 0.704, 0.98, 0.657, 0.689, 0.981, 0.654, 0.674, 0.982, 0.65, 0.658, 0.983, 0.646, 0.642, 0.983, 0.642, 0.625, 0.983, 0.638, 0.608, 0.982, 0.633, 0.59, 0.981, 0.628, 0.572, 0.979, 0.623, 0.553, 0.978, 0.618, 0.535, 0.976, 0.612, 0.516, 0.973, 0.607, 0.497, 0.971, 0.601, 0.477, 0.968, 0.595, 0.458, 0.965, 0.589, 0.438, 0.961, 0.582, 0.418, 0.958, 0.576, 0.398, 0.954, 0.569, 0.378, 0.95, 0.563, 0.357, 0.946, 0.556, 0.336, 0.942, 0.549, 0.315, 0.938, 0.542, 0.294, 0.933, 0.536, 0.273, 0.928, 0.529, 0.25, 0.924, 0.522, 0.228, 0.919, 0.514, 0.204, 0.914, 0.507, 0.179, 0.909, 0.5, 0.153, 0.77, 0.488, 0.983, 0.777, 0.498, 0.976, 0.783, 0.507, 0.969, 0.79, 0.516, 0.962, 0.797, 0.524, 0.955, 0.804, 0.533, 0.948, 0.811, 0.541, 0.942, 0.817, 0.549, 0.936, 0.824, 0.556, 0.93, 0.831, 0.564, 0.924, 0.838, 0.571, 0.918, 0.845, 0.578, 0.912, 0.852, 0.584, 0.906, 0.859, 0.591, 0.9, 0.866, 0.597, 0.894, 0.873, 0.603, 0.888, 0.879, 0.609, 0.882, 0.886, 0.614, 0.876, 0.893, 0.619, 0.869, 0.899, 0.624, 0.863, 0.906, 0.629, 0.856, 0.912, 0.633, 0.85, 0.918, 0.637, 0.843, 0.924, 0.64, 0.835, 0.93, 0.643, 0.827, 0.935, 0.646, 0.819, 0.941, 0.648, 0.811, 0.946, 0.649, 0.802, 0.951, 0.651, 0.792, 0.955, 0.652, 0.782, 0.959, 0.652, 0.771, 0.963, 0.652, 0.76, 0.967, 0.652, 0.749, 0.97, 0.651, 0.736, 0.973, 0.649, 0.723, 0.976, 0.647, 0.71, 0.978, 0.645, 0.696, 0.98, 0.643, 0.681, 0.981, 0.64, 0.666, 0.982, 0.637, 0.65, 0.982, 0.633, 0.634, 0.983, 0.629, 0.617, 0.982, 0.625, 0.6, 0.982, 0.62, 0.582, 0.981, 0.616, 0.565, 0.979, 0.611, 0.546, 0.978, 0.605, 0.528, 0.976, 0.6, 0.509, 0.974, 0.595, 0.49, 0.971, 0.589, 0.471, 0.969, 0.583, 0.452, 0.966, 0.577, 0.432, 0.962, 0.571, 0.413, 0.959, 0.565, 0.393, 0.955, 0.558, 0.373, 0.952, 0.552, 0.352, 0.948, 0.545, 0.332, 0.943, 0.539, 0.311, 0.939, 0.532, 0.29, 0.935, 0.525, 0.268, 0.93, 0.518, 0.246, 0.926, 0.511, 0.224, 0.921, 0.504, 0.2, 0.916, 0.497, 0.175, 0.911, 0.49, 0.149, 0.775, 0.477, 0.981, 0.781, 0.486, 0.974, 0.788, 0.495, 0.966, 0.794, 0.504, 0.959, 0.801, 0.513, 0.952, 0.808, 0.521, 0.946, 0.814, 0.529, 0.939, 0.821, 0.537, 0.933, 0.828, 0.545, 0.926, 0.835, 0.552, 0.92, 0.841, 0.559, 0.914, 0.848, 0.566, 0.908, 0.855, 0.572, 0.901, 0.862, 0.579, 0.895, 0.868, 0.585, 0.889, 0.875, 0.591, 0.883, 0.881, 0.596, 0.877, 0.888, 0.601, 0.87, 0.894, 0.606, 0.864, 0.901, 0.611, 0.857, 0.907, 0.615, 0.85, 0.913, 0.619, 0.843, 0.919, 0.623, 0.836, 0.925, 0.626, 0.828, 0.93, 0.629, 0.82, 0.936, 0.632, 0.812, 0.941, 0.634, 0.803, 0.946, 0.635, 0.794, 0.951, 0.637, 0.784, 0.955, 0.637, 0.774, 0.959, 0.638, 0.763, 0.963, 0.638, 0.752, 0.967, 0.637, 0.74, 0.97, 0.636, 0.728, 0.973, 0.635, 0.715, 0.975, 0.633, 0.701, 0.977, 0.631, 0.687, 0.979, 0.629, 0.672, 0.98, 0.626, 0.657, 0.981, 0.623, 0.642, 0.982, 0.619, 0.626, 0.982, 0.616, 0.609, 0.982, 0.612, 0.592, 0.981, 0.607, 0.575, 0.981, 0.603, 0.557, 0.979, 0.598, 0.54, 0.978, 0.593, 0.521, 0.976, 0.588, 0.503, 0.974, 0.582, 0.484, 0.972, 0.577, 0.465, 0.969, 0.571, 0.446, 0.966, 0.565, 0.427, 0.963, 0.559, 0.407, 0.96, 0.553, 0.387, 0.956, 0.547, 0.368, 0.953, 0.541, 0.347, 0.949, 0.534, 0.327, 0.945, 0.528, 0.306, 0.941, 0.521, 0.285, 0.936, 0.514, 0.264, 0.932, 0.508, 0.242, 0.927, 0.501, 0.22, 0.922, 0.494, 0.196, 0.918, 0.487, 0.172, 0.913, 0.48, 0.145, 0.779, 0.465, 0.979, 0.785, 0.474, 0.971, 0.792, 0.484, 0.964, 0.798, 0.492, 0.957, 0.805, 0.501, 0.95, 0.811, 0.509, 0.943, 0.818, 0.517, 0.936, 0.824, 0.525, 0.929, 0.831, 0.533, 0.923, 0.838, 0.54, 0.916, 0.844, 0.547, 0.91, 0.851, 0.554, 0.904, 0.857, 0.56, 0.897, 0.864, 0.566, 0.891, 0.87, 0.572, 0.884, 0.877, 0.578, 0.878, 0.883, 0.583, 0.871, 0.89, 0.589, 0.865, 0.896, 0.593, 0.858, 0.902, 0.598, 0.851, 0.908, 0.602, 0.844, 0.914, 0.606, 0.837, 0.92, 0.609, 0.829, 0.925, 0.613, 0.821, 0.931, 0.615, 0.813, 0.936, 0.618, 0.804, 0.941, 0.62, 0.795, 0.946, 0.621, 0.786, 0.95, 0.622, 0.776, 0.955, 0.623, 0.765, 0.959, 0.624, 0.755, 0.963, 0.624, 0.743, 0.966, 0.623, 0.731, 0.969, 0.622, 0.719, 0.972, 0.621, 0.706, 0.974, 0.619, 0.693, 0.976, 0.617, 0.679, 0.978, 0.615, 0.664, 0.979, 0.612, 0.649, 0.98, 0.609, 0.634, 0.981, 0.606, 0.618, 0.981, 0.602, 0.601, 0.981, 0.598, 0.585, 0.981, 0.594, 0.568, 0.98, 0.59, 0.55, 0.979, 0.585, 0.533, 0.978, 0.58, 0.515, 0.976, 0.575, 0.496, 0.974, 0.57, 0.478, 0.972, 0.565, 0.459, 0.969, 0.559, 0.44, 0.967, 0.553, 0.421, 0.964, 0.547, 0.402, 0.96, 0.542, 0.382, 0.957, 0.535, 0.362, 0.953, 0.529, 0.342, 0.95, 0.523, 0.322, 0.946, 0.517, 0.302, 0.942, 0.51, 0.281, 0.937, 0.504, 0.26, 0.933, 0.497, 0.238, 0.929, 0.49, 0.216, 0.924, 0.484, 0.192, 0.919, 0.477, 0.168, 0.914, 0.47, 0.141, 0.783, 0.453, 0.977, 0.789, 0.462, 0.969, 0.796, 0.471, 0.962, 0.802, 0.48, 0.954, 0.808, 0.489, 0.947, 0.815, 0.497, 0.94, 0.821, 0.505, 0.933, 0.828, 0.513, 0.926, 0.834, 0.52, 0.919, 0.84, 0.527, 0.913, 0.847, 0.534, 0.906, 0.853, 0.541, 0.899, 0.86, 0.548, 0.893, 0.866, 0.554, 0.886, 0.873, 0.56, 0.88, 0.879, 0.565, 0.873, 0.885, 0.57, 0.866, 0.891, 0.575, 0.859, 0.897, 0.58, 0.852, 0.903, 0.585, 0.845, 0.909, 0.589, 0.838, 0.915, 0.592, 0.83, 0.921, 0.596, 0.822, 0.926, 0.599, 0.814, 0.931, 0.601, 0.805, 0.936, 0.604, 0.797, 0.941, 0.606, 0.787, 0.946, 0.607, 0.778, 0.95, 0.608, 0.768, 0.955, 0.609, 0.757, 0.958, 0.609, 0.746, 0.962, 0.609, 0.735, 0.965, 0.609, 0.723, 0.968, 0.608, 0.71, 0.971, 0.607, 0.698, 0.974, 0.605, 0.684, 0.976, 0.603, 0.67, 0.977, 0.601, 0.656, 0.979, 0.598, 0.641, 0.98, 0.596, 0.626, 0.98, 0.592, 0.61, 0.981, 0.589, 0.594, 0.981, 0.585, 0.577, 0.98, 0.581, 0.56, 0.98, 0.577, 0.543, 0.979, 0.572, 0.526, 0.977, 0.568, 0.508, 0.976, 0.563, 0.49, 0.974, 0.558, 0.471, 0.972, 0.552, 0.453, 0.969, 0.547, 0.434, 0.967, 0.541, 0.415, 0.964, 0.536, 0.396, 0.961, 0.53, 0.377, 0.958, 0.524, 0.357, 0.954, 0.518, 0.337, 0.95, 0.512, 0.317, 0.947, 0.505, 0.297, 0.943, 0.499, 0.276, 0.938, 0.493, 0.255, 0.934, 0.486, 0.234, 0.93, 0.48, 0.211, 0.925, 0.473, 0.188, 0.92, 0.466, 0.164, 0.916, 0.459, 0.137, 0.787, 0.44, 0.975, 0.793, 0.45, 0.967, 0.799, 0.459, 0.959, 0.806, 0.468, 0.952, 0.812, 0.476, 0.944, 0.818, 0.485, 0.937, 0.824, 0.493, 0.93, 0.831, 0.5, 0.923, 0.837, 0.508, 0.916, 0.843, 0.515, 0.909, 0.85, 0.522, 0.902, 0.856, 0.528, 0.895, 0.862, 0.535, 0.888, 0.868, 0.541, 0.881, 0.874, 0.547, 0.875, 0.881, 0.552, 0.868, 0.887, 0.557, 0.861, 0.893, 0.562, 0.853, 0.899, 0.567, 0.846, 0.904, 0.571, 0.839, 0.91, 0.575, 0.831, 0.916, 0.579, 0.823, 0.921, 0.582, 0.815, 0.926, 0.585, 0.807, 0.932, 0.587, 0.798, 0.937, 0.59, 0.789, 0.941, 0.591, 0.78, 0.946, 0.593, 0.77, 0.95, 0.594, 0.76, 0.954, 0.595, 0.749, 0.958, 0.595, 0.738, 0.962, 0.595, 0.727, 0.965, 0.595, 0.715, 0.968, 0.594, 0.702, 0.97, 0.593, 0.689, 0.973, 0.591, 0.676, 0.975, 0.589, 0.662, 0.976, 0.587, 0.648, 0.978, 0.585, 0.633, 0.979, 0.582, 0.618, 0.98, 0.579, 0.602, 0.98, 0.575, 0.586, 0.98, 0.572, 0.57, 0.98, 0.568, 0.553, 0.979, 0.564, 0.536, 0.978, 0.559, 0.518, 0.977, 0.555, 0.501, 0.975, 0.55, 0.483, 0.974, 0.545, 0.465, 0.972, 0.54, 0.447, 0.969, 0.535, 0.428, 0.967, 0.529, 0.409, 0.964, 0.524, 0.39, 0.961, 0.518, 0.371, 0.958, 0.512, 0.352, 0.954, 0.506, 0.332, 0.951, 0.5, 0.312, 0.947, 0.494, 0.292, 0.943, 0.488, 0.272, 0.939, 0.481, 0.251, 0.935, 0.475, 0.229, 0.931, 0.469, 0.207, 0.926, 0.462, 0.184, 0.921, 0.455, 0.159, 0.917, 0.449, 0.133, 0.791, 0.427, 0.973, 0.797, 0.437, 0.964, 0.803, 0.446, 0.957, 0.809, 0.455, 0.949, 0.815, 0.464, 0.941, 0.821, 0.472, 0.934, 0.827, 0.48, 0.926, 0.834, 0.488, 0.919, 0.84, 0.495, 0.912, 0.846, 0.502, 0.905, 0.852, 0.509, 0.898, 0.858, 0.515, 0.891, 0.864, 0.522, 0.884, 0.87, 0.528, 0.877, 0.876, 0.533, 0.87, 0.882, 0.539, 0.862, 0.888, 0.544, 0.855, 0.894, 0.549, 0.848, 0.9, 0.553, 0.84, 0.906, 0.557, 0.833, 0.911, 0.561, 0.825, 0.916, 0.565, 0.817, 0.922, 0.568, 0.808, 0.927, 0.571, 0.8, 0.932, 0.573, 0.791, 0.937, 0.575, 0.782, 0.941, 0.577, 0.772, 0.946, 0.579, 0.762, 0.95, 0.58, 0.752, 0.954, 0.58, 0.741, 0.958, 0.581, 0.73, 0.961, 0.581, 0.718, 0.964, 0.58, 0.706, 0.967, 0.58, 0.694, 0.97, 0.578, 0.681, 0.972, 0.577, 0.667, 0.974, 0.575, 0.654, 0.976, 0.573, 0.639, 0.977, 0.571, 0.625, 0.978, 0.568, 0.61, 0.979, 0.565, 0.594, 0.979, 0.562, 0.578, 0.979, 0.558, 0.562, 0.979, 0.554, 0.545, 0.978, 0.55, 0.529, 0.977, 0.546, 0.511, 0.976, 0.542, 0.494, 0.975, 0.537, 0.476, 0.973, 0.532, 0.458, 0.971, 0.527, 0.44, 0.969, 0.522, 0.422, 0.967, 0.517, 0.403, 0.964, 0.511, 0.385, 0.961, 0.506, 0.366, 0.958, 0.5, 0.347, 0.955, 0.494, 0.327, 0.951, 0.488, 0.307, 0.947, 0.482, 0.287, 0.944, 0.476, 0.267, 0.94, 0.47, 0.246, 0.935, 0.464, 0.225, 0.931, 0.458, 0.203, 0.927, 0.451, 0.18, 0.922, 0.445, 0.155, 0.917, 0.438, 0.129, 0.795, 0.413, 0.97, 0.801, 0.423, 0.962, 0.807, 0.433, 0.954, 0.813, 0.442, 0.946, 0.818, 0.45, 0.938, 0.824, 0.459, 0.93, 0.83, 0.467, 0.923, 0.836, 0.474, 0.915, 0.842, 0.482, 0.908, 0.848, 0.489, 0.901, 0.854, 0.496, 0.894, 0.86, 0.502, 0.886, 0.866, 0.508, 0.879, 0.872, 0.514, 0.872, 0.878, 0.52, 0.864, 0.884, 0.525, 0.857, 0.89, 0.53, 0.85, 0.895, 0.535, 0.842, 0.901, 0.539, 0.834, 0.906, 0.543, 0.826, 0.912, 0.547, 0.818, 0.917, 0.551, 0.81, 0.922, 0.554, 0.801, 0.927, 0.557, 0.793, 0.932, 0.559, 0.783, 0.937, 0.561, 0.774, 0.941, 0.563, 0.764, 0.946, 0.564, 0.754, 0.95, 0.565, 0.744, 0.953, 0.566, 0.733, 0.957, 0.566, 0.722, 0.96, 0.566, 0.71, 0.963, 0.566, 0.698, 0.966, 0.565, 0.685, 0.969, 0.564, 0.673, 0.971, 0.563, 0.659, 0.973, 0.561, 0.645, 0.975, 0.559, 0.631, 0.976, 0.557, 0.617, 0.977, 0.554, 0.602, 0.978, 0.551, 0.586, 0.978, 0.548, 0.571, 0.978, 0.545, 0.554, 0.978, 0.541, 0.538, 0.977, 0.537, 0.521, 0.977, 0.533, 0.504, 0.976, 0.529, 0.487, 0.974, 0.524, 0.47, 0.973, 0.519, 0.452, 0.971, 0.515, 0.434, 0.969, 0.51, 0.416, 0.966, 0.504, 0.398, 0.964, 0.499, 0.379, 0.961, 0.494, 0.36, 0.958, 0.488, 0.341, 0.955, 0.482, 0.322, 0.951, 0.477, 0.302, 0.948, 0.471, 0.283, 0.944, 0.465, 0.262, 0.94, 0.459, 0.242, 0.936, 0.452, 0.22, 0.932, 0.446, 0.198, 0.927, 0.44, 0.175, 0.923, 0.434, 0.151, 0.918, 0.427, 0.124, 0.799, 0.399, 0.968, 0.804, 0.409, 0.959, 0.81, 0.419, 0.951, 0.816, 0.428, 0.943, 0.822, 0.437, 0.935, 0.827, 0.445, 0.927, 0.833, 0.453, 0.919, 0.839, 0.461, 0.912, 0.845, 0.468, 0.904, 0.851, 0.475, 0.897, 0.857, 0.482, 0.889, 0.862, 0.489, 0.882, 0.868, 0.495, 0.874, 0.874, 0.501, 0.867, 0.88, 0.506, 0.859, 0.885, 0.511, 0.852, 0.891, 0.516, 0.844, 0.897, 0.521, 0.836, 0.902, 0.525, 0.828, 0.907, 0.529, 0.82, 0.913, 0.533, 0.812, 0.918, 0.537, 0.803, 0.923, 0.54, 0.794, 0.928, 0.542, 0.785, 0.932, 0.545, 0.776, 0.937, 0.547, 0.767, 0.941, 0.549, 0.757, 0.945, 0.55, 0.747, 0.949, 0.551, 0.736, 0.953, 0.552, 0.725, 0.956, 0.552, 0.714, 0.96, 0.552, 0.702, 0.963, 0.552, 0.69, 0.965, 0.551, 0.677, 0.968, 0.55, 0.664, 0.97, 0.549, 0.651, 0.972, 0.547, 0.637, 0.974, 0.545, 0.623, 0.975, 0.543, 0.609, 0.976, 0.54, 0.594, 0.977, 0.537, 0.578, 0.977, 0.534, 0.563, 0.977, 0.531, 0.547, 0.977, 0.527, 0.531, 0.976, 0.524, 0.514, 0.976, 0.52, 0.497, 0.975, 0.516, 0.48, 0.973, 0.511, 0.463, 0.972, 0.507, 0.446, 0.97, 0.502, 0.428, 0.968, 0.497, 0.41, 0.966, 0.492, 0.392, 0.963, 0.487, 0.373, 0.96, 0.481, 0.355, 0.957, 0.476, 0.336, 0.954, 0.47, 0.317, 0.951, 0.465, 0.297, 0.947, 0.459, 0.278, 0.944, 0.453, 0.258, 0.94, 0.447, 0.237, 0.936, 0.441, 0.216, 0.932, 0.435, 0.194, 0.927, 0.429, 0.171, 0.923, 0.422, 0.147, 0.918, 0.416, 0.12, 0.802, 0.385, 0.965, 0.808, 0.395, 0.957, 0.813, 0.405, 0.948, 0.819, 0.414, 0.94, 0.825, 0.423, 0.932, 0.83, 0.431, 0.924, 0.836, 0.439, 0.916, 0.842, 0.447, 0.908, 0.847, 0.454, 0.9, 0.853, 0.462, 0.892, 0.859, 0.468, 0.885, 0.864, 0.475, 0.877, 0.87, 0.481, 0.869, 0.876, 0.487, 0.862, 0.881, 0.492, 0.854, 0.887, 0.498, 0.846, 0.892, 0.502, 0.838, 0.898, 0.507, 0.83, 0.903, 0.511, 0.822, 0.908, 0.515, 0.814, 0.913, 0.519, 0.805, 0.918, 0.522, 0.797, 0.923, 0.525, 0.788, 0.928, 0.528, 0.778, 0.932, 0.53, 0.769, 0.937, 0.532, 0.759, 0.941, 0.534, 0.749, 0.945, 0.535, 0.739, 0.949, 0.536, 0.728, 0.952, 0.537, 0.717, 0.956, 0.537, 0.706, 0.959, 0.537, 0.694, 0.962, 0.537, 0.682, 0.964, 0.536, 0.669, 0.967, 0.536, 0.656, 0.969, 0.534, 0.643, 0.971, 0.533, 0.629, 0.972, 0.531, 0.615, 0.974, 0.529, 0.601, 0.975, 0.526, 0.586, 0.975, 0.523, 0.571, 0.976, 0.521, 0.555, 0.976, 0.517, 0.54, 0.976, 0.514, 0.523, 0.975, 0.51, 0.507, 0.975, 0.506, 0.49, 0.974, 0.502, 0.474, 0.972, 0.498, 0.456, 0.971, 0.494, 0.439, 0.969, 0.489, 0.421, 0.967, 0.484, 0.404, 0.965, 0.479, 0.386, 0.963, 0.474, 0.367, 0.96, 0.469, 0.349, 0.957, 0.464, 0.33, 0.954, 0.458, 0.311, 0.951, 0.453, 0.292, 0.947, 0.447, 0.273, 0.944, 0.441, 0.253, 0.94, 0.435, 0.232, 0.936, 0.429, 0.211, 0.932, 0.423, 0.19, 0.927, 0.417, 0.167, 0.923, 0.411, 0.142, 0.919, 0.405, 0.116, 0.806, 0.37, 0.963, 0.811, 0.38, 0.954, 0.816, 0.39, 0.945, 0.822, 0.399, 0.937, 0.827, 0.408, 0.929, 0.833, 0.417, 0.92, 0.838, 0.425, 0.912, 0.844, 0.433, 0.904, 0.85, 0.44, 0.896, 0.855, 0.447, 0.888, 0.861, 0.454, 0.88, 0.866, 0.461, 0.872, 0.872, 0.467, 0.865, 0.877, 0.473, 0.857, 0.883, 0.478, 0.849, 0.888, 0.483, 0.841, 0.893, 0.488, 0.833, 0.899, 0.493, 0.824, 0.904, 0.497, 0.816, 0.909, 0.501, 0.807, 0.914, 0.505, 0.799, 0.919, 0.508, 0.79, 0.923, 0.511, 0.781, 0.928, 0.514, 0.771, 0.932, 0.516, 0.762, 0.937, 0.518, 0.752, 0.941, 0.52, 0.742, 0.945, 0.521, 0.731, 0.948, 0.522, 0.72, 0.952, 0.523, 0.709, 0.955, 0.523, 0.698, 0.958, 0.523, 0.686, 0.961, 0.523, 0.674, 0.964, 0.522, 0.661, 0.966, 0.521, 0.648, 0.968, 0.52, 0.635, 0.97, 0.518, 0.621, 0.971, 0.517, 0.607, 0.972, 0.514, 0.593, 0.973, 0.512, 0.578, 0.974, 0.509, 0.563, 0.975, 0.507, 0.548, 0.975, 0.503, 0.532, 0.975, 0.5, 0.516, 0.974, 0.497, 0.5, 0.974, 0.493, 0.483, 0.973, 0.489, 0.467, 0.971, 0.485, 0.45, 0.97, 0.48, 0.433, 0.968, 0.476, 0.415, 0.966, 0.471, 0.397, 0.964, 0.466, 0.38, 0.962, 0.461, 0.362, 0.959, 0.456, 0.343, 0.956, 0.451, 0.325, 0.953, 0.446, 0.306, 0.95, 0.44, 0.287, 0.947, 0.435, 0.268, 0.943, 0.429, 0.248, 0.939, 0.423, 0.228, 0.936, 0.417, 0.207, 0.931, 0.411, 0.185, 0.927, 0.405, 0.162, 0.923, 0.399, 0.138, 0.918, 0.393, 0.111, 0.809, 0.354, 0.96, 0.814, 0.364, 0.951, 0.819, 0.375, 0.942, 0.825, 0.384, 0.934, 0.83, 0.393, 0.925, 0.835, 0.402, 0.917, 0.841, 0.41, 0.908, 0.846, 0.418, 0.9, 0.852, 0.426, 0.892, 0.857, 0.433, 0.884, 0.863, 0.44, 0.876, 0.868, 0.446, 0.868, 0.873, 0.452, 0.86, 0.879, 0.458, 0.852, 0.884, 0.464, 0.843, 0.889, 0.469, 0.835, 0.894, 0.474, 0.827, 0.899, 0.478, 0.818, 0.904, 0.483, 0.81, 0.909, 0.486, 0.801, 0.914, 0.49, 0.792, 0.919, 0.493, 0.783, 0.923, 0.496, 0.774, 0.928, 0.499, 0.764, 0.932, 0.501, 0.755, 0.936, 0.503, 0.745, 0.94, 0.505, 0.734, 0.944, 0.506, 0.724, 0.948, 0.507, 0.713, 0.951, 0.508, 0.701, 0.954, 0.508, 0.69, 0.957, 0.508, 0.678, 0.96, 0.508, 0.666, 0.962, 0.507, 0.653, 0.965, 0.507, 0.64, 0.967, 0.505, 0.627, 0.968, 0.504, 0.613, 0.97, 0.502, 0.599, 0.971, 0.5, 0.585, 0.972, 0.498, 0.57, 0.973, 0.495, 0.555, 0.973, 0.493, 0.54, 0.973, 0.49, 0.525, 0.973, 0.486, 0.509, 0.973, 0.483, 0.493, 0.972, 0.479, 0.476, 0.971, 0.475, 0.46, 0.97, 0.471, 0.443, 0.969, 0.467, 0.426, 0.967, 0.463, 0.409, 0.965, 0.458, 0.391, 0.963, 0.453, 0.374, 0.961, 0.449, 0.356, 0.958, 0.444, 0.338, 0.956, 0.438, 0.319, 0.953, 0.433, 0.301, 0.949, 0.428, 0.282, 0.946, 0.422, 0.263, 0.943, 0.417, 0.243, 0.939, 0.411, 0.223, 0.935, 0.405, 0.202, 0.931, 0.399, 0.181, 0.927, 0.393, 0.158, 0.923, 0.387, 0.134, 0.918, 0.381, 0.107]).reshape((65, 65, 3)) BiOrangeBlue = np.array([0.0, 0.0, 0.0, 0.0, 0.062, 0.125, 0.0, 0.125, 0.25, 0.0, 0.188, 0.375, 0.0, 0.25, 0.5, 0.0, 0.312, 0.625, 0.0, 0.375, 0.75, 0.0, 0.438, 0.875, 0.0, 0.5, 1.0, 0.125, 0.062, 0.0, 0.125, 0.125, 0.125, 0.125, 0.188, 0.25, 0.125, 0.25, 0.375, 0.125, 0.312, 0.5, 0.125, 0.375, 0.625, 0.125, 0.438, 0.75, 0.125, 0.5, 0.875, 0.125, 0.562, 1.0, 0.25, 0.125, 0.0, 0.25, 0.188, 0.125, 0.25, 0.25, 0.25, 0.25, 0.312, 0.375, 0.25, 0.375, 0.5, 0.25, 0.438, 0.625, 0.25, 0.5, 0.75, 0.25, 0.562, 0.875, 0.25, 0.625, 1.0, 0.375, 0.188, 0.0, 0.375, 0.25, 0.125, 0.375, 0.312, 0.25, 0.375, 0.375, 0.375, 0.375, 0.438, 0.5, 0.375, 0.5, 0.625, 0.375, 0.562, 0.75, 0.375, 0.625, 0.875, 0.375, 0.688, 1.0, 0.5, 0.25, 0.0, 0.5, 0.312, 0.125, 0.5, 0.375, 0.25, 0.5, 0.438, 0.375, 0.5, 0.5, 0.5, 0.5, 0.562, 0.625, 0.5, 0.625, 0.75, 0.5, 0.688, 0.875, 0.5, 0.75, 1.0, 0.625, 0.312, 0.0, 0.625, 0.375, 0.125, 0.625, 0.438, 0.25, 0.625, 0.5, 0.375, 0.625, 0.562, 0.5, 0.625, 0.625, 0.625, 0.625, 0.688, 0.75, 0.625, 0.75, 0.875, 0.625, 0.812, 1.0, 0.75, 0.375, 0.0, 0.75, 0.438, 0.125, 0.75, 0.5, 0.25, 0.75, 0.562, 0.375, 0.75, 0.625, 0.5, 0.75, 0.688, 0.625, 0.75, 0.75, 0.75, 0.75, 0.812, 0.875, 0.75, 0.875, 1.0, 0.875, 0.438, 0.0, 0.875, 0.5, 0.125, 0.875, 0.562, 0.25, 0.875, 0.625, 0.375, 0.875, 0.688, 0.5, 0.875, 0.75, 0.625, 0.875, 0.812, 0.75, 0.875, 0.875, 0.875, 0.875, 0.938, 1.0, 1.0, 0.5, 0.0, 1.0, 0.562, 0.125, 1.0, 0.625, 0.25, 1.0, 0.688, 0.375, 1.0, 0.75, 0.5, 1.0, 0.812, 0.625, 1.0, 0.875, 0.75, 1.0, 0.938, 0.875, 1.0, 1.0, 1.0]).reshape((9, 9, 3)) cmaps = {'BiPeak': SegmentedBivarColormap(BiPeak, 256, 'square', (0.5, 0.5), name='BiPeak'), 'BiOrangeBlue': SegmentedBivarColormap(BiOrangeBlue, 256, 'square', (0, 0), name='BiOrangeBlue'), 'BiCone': SegmentedBivarColormap(BiPeak, 256, 'circle', (0.5, 0.5), name='BiCone')} # File: matplotlib-main/lib/matplotlib/_cm_listed.py from .colors import ListedColormap _magma_data = [[0.001462, 0.000466, 0.013866], [0.002258, 0.001295, 0.018331], [0.003279, 0.002305, 0.023708], [0.004512, 0.00349, 0.029965], [0.00595, 0.004843, 0.03713], [0.007588, 0.006356, 0.044973], [0.009426, 0.008022, 0.052844], [0.011465, 0.009828, 0.06075], [0.013708, 0.011771, 0.068667], [0.016156, 0.01384, 0.076603], [0.018815, 0.016026, 0.084584], [0.021692, 0.01832, 0.09261], [0.024792, 0.020715, 0.100676], [0.028123, 0.023201, 0.108787], [0.031696, 0.025765, 0.116965], [0.03552, 0.028397, 0.125209], [0.039608, 0.03109, 0.133515], [0.04383, 0.03383, 0.141886], [0.048062, 0.036607, 0.150327], [0.05232, 0.039407, 0.158841], [0.056615, 0.04216, 0.167446], [0.060949, 0.044794, 0.176129], [0.06533, 0.047318, 0.184892], [0.069764, 0.049726, 0.193735], [0.074257, 0.052017, 0.20266], [0.078815, 0.054184, 0.211667], [0.083446, 0.056225, 0.220755], [0.088155, 0.058133, 0.229922], [0.092949, 0.059904, 0.239164], [0.097833, 0.061531, 0.248477], [0.102815, 0.06301, 0.257854], [0.107899, 0.064335, 0.267289], [0.113094, 0.065492, 0.276784], [0.118405, 0.066479, 0.286321], [0.123833, 0.067295, 0.295879], [0.12938, 0.067935, 0.305443], [0.135053, 0.068391, 0.315], [0.140858, 0.068654, 0.324538], [0.146785, 0.068738, 0.334011], [0.152839, 0.068637, 0.343404], [0.159018, 0.068354, 0.352688], [0.165308, 0.067911, 0.361816], [0.171713, 0.067305, 0.370771], [0.178212, 0.066576, 0.379497], [0.184801, 0.065732, 0.387973], [0.19146, 0.064818, 0.396152], [0.198177, 0.063862, 0.404009], [0.204935, 0.062907, 0.411514], [0.211718, 0.061992, 0.418647], [0.218512, 0.061158, 0.425392], [0.225302, 0.060445, 0.431742], [0.232077, 0.059889, 0.437695], [0.238826, 0.059517, 0.443256], [0.245543, 0.059352, 0.448436], [0.25222, 0.059415, 0.453248], [0.258857, 0.059706, 0.45771], [0.265447, 0.060237, 0.46184], [0.271994, 0.060994, 0.46566], [0.278493, 0.061978, 0.46919], [0.284951, 0.063168, 0.472451], [0.291366, 0.064553, 0.475462], [0.29774, 0.066117, 0.478243], [0.304081, 0.067835, 0.480812], [0.310382, 0.069702, 0.483186], [0.316654, 0.07169, 0.48538], [0.322899, 0.073782, 0.487408], [0.329114, 0.075972, 0.489287], [0.335308, 0.078236, 0.491024], [0.341482, 0.080564, 0.492631], [0.347636, 0.082946, 0.494121], [0.353773, 0.085373, 0.495501], [0.359898, 0.087831, 0.496778], [0.366012, 0.090314, 0.49796], [0.372116, 0.092816, 0.499053], [0.378211, 0.095332, 0.500067], [0.384299, 0.097855, 0.501002], [0.390384, 0.100379, 0.501864], [0.396467, 0.102902, 0.502658], [0.402548, 0.10542, 0.503386], [0.408629, 0.10793, 0.504052], [0.414709, 0.110431, 0.504662], [0.420791, 0.11292, 0.505215], [0.426877, 0.115395, 0.505714], [0.432967, 0.117855, 0.50616], [0.439062, 0.120298, 0.506555], [0.445163, 0.122724, 0.506901], [0.451271, 0.125132, 0.507198], [0.457386, 0.127522, 0.507448], [0.463508, 0.129893, 0.507652], [0.46964, 0.132245, 0.507809], [0.47578, 0.134577, 0.507921], [0.481929, 0.136891, 0.507989], [0.488088, 0.139186, 0.508011], [0.494258, 0.141462, 0.507988], [0.500438, 0.143719, 0.50792], [0.506629, 0.145958, 0.507806], [0.512831, 0.148179, 0.507648], [0.519045, 0.150383, 0.507443], [0.52527, 0.152569, 0.507192], [0.531507, 0.154739, 0.506895], [0.537755, 0.156894, 0.506551], [0.544015, 0.159033, 0.506159], [0.550287, 0.161158, 0.505719], [0.556571, 0.163269, 0.50523], [0.562866, 0.165368, 0.504692], [0.569172, 0.167454, 0.504105], [0.57549, 0.16953, 0.503466], [0.581819, 0.171596, 0.502777], [0.588158, 0.173652, 0.502035], [0.594508, 0.175701, 0.501241], [0.600868, 0.177743, 0.500394], [0.607238, 0.179779, 0.499492], [0.613617, 0.181811, 0.498536], [0.620005, 0.18384, 0.497524], [0.626401, 0.185867, 0.496456], [0.632805, 0.187893, 0.495332], [0.639216, 0.189921, 0.49415], [0.645633, 0.191952, 0.49291], [0.652056, 0.193986, 0.491611], [0.658483, 0.196027, 0.490253], [0.664915, 0.198075, 0.488836], [0.671349, 0.200133, 0.487358], [0.677786, 0.202203, 0.485819], [0.684224, 0.204286, 0.484219], [0.690661, 0.206384, 0.482558], [0.697098, 0.208501, 0.480835], [0.703532, 0.210638, 0.479049], [0.709962, 0.212797, 0.477201], [0.716387, 0.214982, 0.47529], [0.722805, 0.217194, 0.473316], [0.729216, 0.219437, 0.471279], [0.735616, 0.221713, 0.46918], [0.742004, 0.224025, 0.467018], [0.748378, 0.226377, 0.464794], [0.754737, 0.228772, 0.462509], [0.761077, 0.231214, 0.460162], [0.767398, 0.233705, 0.457755], [0.773695, 0.236249, 0.455289], [0.779968, 0.238851, 0.452765], [0.786212, 0.241514, 0.450184], [0.792427, 0.244242, 0.447543], [0.798608, 0.24704, 0.444848], [0.804752, 0.249911, 0.442102], [0.810855, 0.252861, 0.439305], [0.816914, 0.255895, 0.436461], [0.822926, 0.259016, 0.433573], [0.828886, 0.262229, 0.430644], [0.834791, 0.26554, 0.427671], [0.840636, 0.268953, 0.424666], [0.846416, 0.272473, 0.421631], [0.852126, 0.276106, 0.418573], [0.857763, 0.279857, 0.415496], [0.86332, 0.283729, 0.412403], [0.868793, 0.287728, 0.409303], [0.874176, 0.291859, 0.406205], [0.879464, 0.296125, 0.403118], [0.884651, 0.30053, 0.400047], [0.889731, 0.305079, 0.397002], [0.8947, 0.309773, 0.393995], [0.899552, 0.314616, 0.391037], [0.904281, 0.31961, 0.388137], [0.908884, 0.324755, 0.385308], [0.913354, 0.330052, 0.382563], [0.917689, 0.3355, 0.379915], [0.921884, 0.341098, 0.377376], [0.925937, 0.346844, 0.374959], [0.929845, 0.352734, 0.372677], [0.933606, 0.358764, 0.370541], [0.937221, 0.364929, 0.368567], [0.940687, 0.371224, 0.366762], [0.944006, 0.377643, 0.365136], [0.94718, 0.384178, 0.363701], [0.95021, 0.39082, 0.362468], [0.953099, 0.397563, 0.361438], [0.955849, 0.4044, 0.360619], [0.958464, 0.411324, 0.360014], [0.960949, 0.418323, 0.35963], [0.96331, 0.42539, 0.359469], [0.965549, 0.432519, 0.359529], [0.967671, 0.439703, 0.35981], [0.96968, 0.446936, 0.360311], [0.971582, 0.45421, 0.36103], [0.973381, 0.46152, 0.361965], [0.975082, 0.468861, 0.363111], [0.97669, 0.476226, 0.364466], [0.97821, 0.483612, 0.366025], [0.979645, 0.491014, 0.367783], [0.981, 0.498428, 0.369734], [0.982279, 0.505851, 0.371874], [0.983485, 0.51328, 0.374198], [0.984622, 0.520713, 0.376698], [0.985693, 0.528148, 0.379371], [0.9867, 0.535582, 0.38221], [0.987646, 0.543015, 0.38521], [0.988533, 0.550446, 0.388365], [0.989363, 0.557873, 0.391671], [0.990138, 0.565296, 0.395122], [0.990871, 0.572706, 0.398714], [0.991558, 0.580107, 0.402441], [0.992196, 0.587502, 0.406299], [0.992785, 0.594891, 0.410283], [0.993326, 0.602275, 0.41439], [0.993834, 0.609644, 0.418613], [0.994309, 0.616999, 0.42295], [0.994738, 0.62435, 0.427397], [0.995122, 0.631696, 0.431951], [0.99548, 0.639027, 0.436607], [0.99581, 0.646344, 0.441361], [0.996096, 0.653659, 0.446213], [0.996341, 0.660969, 0.45116], [0.99658, 0.668256, 0.456192], [0.996775, 0.675541, 0.461314], [0.996925, 0.682828, 0.466526], [0.997077, 0.690088, 0.471811], [0.997186, 0.697349, 0.477182], [0.997254, 0.704611, 0.482635], [0.997325, 0.711848, 0.488154], [0.997351, 0.719089, 0.493755], [0.997351, 0.726324, 0.499428], [0.997341, 0.733545, 0.505167], [0.997285, 0.740772, 0.510983], [0.997228, 0.747981, 0.516859], [0.997138, 0.75519, 0.522806], [0.997019, 0.762398, 0.528821], [0.996898, 0.769591, 0.534892], [0.996727, 0.776795, 0.541039], [0.996571, 0.783977, 0.547233], [0.996369, 0.791167, 0.553499], [0.996162, 0.798348, 0.55982], [0.995932, 0.805527, 0.566202], [0.99568, 0.812706, 0.572645], [0.995424, 0.819875, 0.57914], [0.995131, 0.827052, 0.585701], [0.994851, 0.834213, 0.592307], [0.994524, 0.841387, 0.598983], [0.994222, 0.84854, 0.605696], [0.993866, 0.855711, 0.612482], [0.993545, 0.862859, 0.619299], [0.99317, 0.870024, 0.626189], [0.992831, 0.877168, 0.633109], [0.99244, 0.88433, 0.640099], [0.992089, 0.89147, 0.647116], [0.991688, 0.898627, 0.654202], [0.991332, 0.905763, 0.661309], [0.99093, 0.912915, 0.668481], [0.99057, 0.920049, 0.675675], [0.990175, 0.927196, 0.682926], [0.989815, 0.934329, 0.690198], [0.989434, 0.94147, 0.697519], [0.989077, 0.948604, 0.704863], [0.988717, 0.955742, 0.712242], [0.988367, 0.962878, 0.719649], [0.988033, 0.970012, 0.727077], [0.987691, 0.977154, 0.734536], [0.987387, 0.984288, 0.742002], [0.987053, 0.991438, 0.749504]] _inferno_data = [[0.001462, 0.000466, 0.013866], [0.002267, 0.00127, 0.01857], [0.003299, 0.002249, 0.024239], [0.004547, 0.003392, 0.030909], [0.006006, 0.004692, 0.038558], [0.007676, 0.006136, 0.046836], [0.009561, 0.007713, 0.055143], [0.011663, 0.009417, 0.06346], [0.013995, 0.011225, 0.071862], [0.016561, 0.013136, 0.080282], [0.019373, 0.015133, 0.088767], [0.022447, 0.017199, 0.097327], [0.025793, 0.019331, 0.10593], [0.029432, 0.021503, 0.114621], [0.033385, 0.023702, 0.123397], [0.037668, 0.025921, 0.132232], [0.042253, 0.028139, 0.141141], [0.046915, 0.030324, 0.150164], [0.051644, 0.032474, 0.159254], [0.056449, 0.034569, 0.168414], [0.06134, 0.03659, 0.177642], [0.066331, 0.038504, 0.186962], [0.071429, 0.040294, 0.196354], [0.076637, 0.041905, 0.205799], [0.081962, 0.043328, 0.215289], [0.087411, 0.044556, 0.224813], [0.09299, 0.045583, 0.234358], [0.098702, 0.046402, 0.243904], [0.104551, 0.047008, 0.25343], [0.110536, 0.047399, 0.262912], [0.116656, 0.047574, 0.272321], [0.122908, 0.047536, 0.281624], [0.129285, 0.047293, 0.290788], [0.135778, 0.046856, 0.299776], [0.142378, 0.046242, 0.308553], [0.149073, 0.045468, 0.317085], [0.15585, 0.044559, 0.325338], [0.162689, 0.043554, 0.333277], [0.169575, 0.042489, 0.340874], [0.176493, 0.041402, 0.348111], [0.183429, 0.040329, 0.354971], [0.190367, 0.039309, 0.361447], [0.197297, 0.0384, 0.367535], [0.204209, 0.037632, 0.373238], [0.211095, 0.03703, 0.378563], [0.217949, 0.036615, 0.383522], [0.224763, 0.036405, 0.388129], [0.231538, 0.036405, 0.3924], [0.238273, 0.036621, 0.396353], [0.244967, 0.037055, 0.400007], [0.25162, 0.037705, 0.403378], [0.258234, 0.038571, 0.406485], [0.26481, 0.039647, 0.409345], [0.271347, 0.040922, 0.411976], [0.27785, 0.042353, 0.414392], [0.284321, 0.043933, 0.416608], [0.290763, 0.045644, 0.418637], [0.297178, 0.04747, 0.420491], [0.303568, 0.049396, 0.422182], [0.309935, 0.051407, 0.423721], [0.316282, 0.05349, 0.425116], [0.32261, 0.055634, 0.426377], [0.328921, 0.057827, 0.427511], [0.335217, 0.06006, 0.428524], [0.3415, 0.062325, 0.429425], [0.347771, 0.064616, 0.430217], [0.354032, 0.066925, 0.430906], [0.360284, 0.069247, 0.431497], [0.366529, 0.071579, 0.431994], [0.372768, 0.073915, 0.4324], [0.379001, 0.076253, 0.432719], [0.385228, 0.078591, 0.432955], [0.391453, 0.080927, 0.433109], [0.397674, 0.083257, 0.433183], [0.403894, 0.08558, 0.433179], [0.410113, 0.087896, 0.433098], [0.416331, 0.090203, 0.432943], [0.422549, 0.092501, 0.432714], [0.428768, 0.09479, 0.432412], [0.434987, 0.097069, 0.432039], [0.441207, 0.099338, 0.431594], [0.447428, 0.101597, 0.43108], [0.453651, 0.103848, 0.430498], [0.459875, 0.106089, 0.429846], [0.4661, 0.108322, 0.429125], [0.472328, 0.110547, 0.428334], [0.478558, 0.112764, 0.427475], [0.484789, 0.114974, 0.426548], [0.491022, 0.117179, 0.425552], [0.497257, 0.119379, 0.424488], [0.503493, 0.121575, 0.423356], [0.50973, 0.123769, 0.422156], [0.515967, 0.12596, 0.420887], [0.522206, 0.12815, 0.419549], [0.528444, 0.130341, 0.418142], [0.534683, 0.132534, 0.416667], [0.54092, 0.134729, 0.415123], [0.547157, 0.136929, 0.413511], [0.553392, 0.139134, 0.411829], [0.559624, 0.141346, 0.410078], [0.565854, 0.143567, 0.408258], [0.572081, 0.145797, 0.406369], [0.578304, 0.148039, 0.404411], [0.584521, 0.150294, 0.402385], [0.590734, 0.152563, 0.40029], [0.59694, 0.154848, 0.398125], [0.603139, 0.157151, 0.395891], [0.60933, 0.159474, 0.393589], [0.615513, 0.161817, 0.391219], [0.621685, 0.164184, 0.388781], [0.627847, 0.166575, 0.386276], [0.633998, 0.168992, 0.383704], [0.640135, 0.171438, 0.381065], [0.64626, 0.173914, 0.378359], [0.652369, 0.176421, 0.375586], [0.658463, 0.178962, 0.372748], [0.66454, 0.181539, 0.369846], [0.670599, 0.184153, 0.366879], [0.676638, 0.186807, 0.363849], [0.682656, 0.189501, 0.360757], [0.688653, 0.192239, 0.357603], [0.694627, 0.195021, 0.354388], [0.700576, 0.197851, 0.351113], [0.7065, 0.200728, 0.347777], [0.712396, 0.203656, 0.344383], [0.718264, 0.206636, 0.340931], [0.724103, 0.20967, 0.337424], [0.729909, 0.212759, 0.333861], [0.735683, 0.215906, 0.330245], [0.741423, 0.219112, 0.326576], [0.747127, 0.222378, 0.322856], [0.752794, 0.225706, 0.319085], [0.758422, 0.229097, 0.315266], [0.76401, 0.232554, 0.311399], [0.769556, 0.236077, 0.307485], [0.775059, 0.239667, 0.303526], [0.780517, 0.243327, 0.299523], [0.785929, 0.247056, 0.295477], [0.791293, 0.250856, 0.29139], [0.796607, 0.254728, 0.287264], [0.801871, 0.258674, 0.283099], [0.807082, 0.262692, 0.278898], [0.812239, 0.266786, 0.274661], [0.817341, 0.270954, 0.27039], [0.822386, 0.275197, 0.266085], [0.827372, 0.279517, 0.26175], [0.832299, 0.283913, 0.257383], [0.837165, 0.288385, 0.252988], [0.841969, 0.292933, 0.248564], [0.846709, 0.297559, 0.244113], [0.851384, 0.30226, 0.239636], [0.855992, 0.307038, 0.235133], [0.860533, 0.311892, 0.230606], [0.865006, 0.316822, 0.226055], [0.869409, 0.321827, 0.221482], [0.873741, 0.326906, 0.216886], [0.878001, 0.33206, 0.212268], [0.882188, 0.337287, 0.207628], [0.886302, 0.342586, 0.202968], [0.890341, 0.347957, 0.198286], [0.894305, 0.353399, 0.193584], [0.898192, 0.358911, 0.18886], [0.902003, 0.364492, 0.184116], [0.905735, 0.37014, 0.17935], [0.90939, 0.375856, 0.174563], [0.912966, 0.381636, 0.169755], [0.916462, 0.387481, 0.164924], [0.919879, 0.393389, 0.16007], [0.923215, 0.399359, 0.155193], [0.92647, 0.405389, 0.150292], [0.929644, 0.411479, 0.145367], [0.932737, 0.417627, 0.140417], [0.935747, 0.423831, 0.13544], [0.938675, 0.430091, 0.130438], [0.941521, 0.436405, 0.125409], [0.944285, 0.442772, 0.120354], [0.946965, 0.449191, 0.115272], [0.949562, 0.45566, 0.110164], [0.952075, 0.462178, 0.105031], [0.954506, 0.468744, 0.099874], [0.956852, 0.475356, 0.094695], [0.959114, 0.482014, 0.089499], [0.961293, 0.488716, 0.084289], [0.963387, 0.495462, 0.079073], [0.965397, 0.502249, 0.073859], [0.967322, 0.509078, 0.068659], [0.969163, 0.515946, 0.063488], [0.970919, 0.522853, 0.058367], [0.97259, 0.529798, 0.053324], [0.974176, 0.53678, 0.048392], [0.975677, 0.543798, 0.043618], [0.977092, 0.55085, 0.03905], [0.978422, 0.557937, 0.034931], [0.979666, 0.565057, 0.031409], [0.980824, 0.572209, 0.028508], [0.981895, 0.579392, 0.02625], [0.982881, 0.586606, 0.024661], [0.983779, 0.593849, 0.02377], [0.984591, 0.601122, 0.023606], [0.985315, 0.608422, 0.024202], [0.985952, 0.61575, 0.025592], [0.986502, 0.623105, 0.027814], [0.986964, 0.630485, 0.030908], [0.987337, 0.63789, 0.034916], [0.987622, 0.64532, 0.039886], [0.987819, 0.652773, 0.045581], [0.987926, 0.66025, 0.05175], [0.987945, 0.667748, 0.058329], [0.987874, 0.675267, 0.065257], [0.987714, 0.682807, 0.072489], [0.987464, 0.690366, 0.07999], [0.987124, 0.697944, 0.087731], [0.986694, 0.70554, 0.095694], [0.986175, 0.713153, 0.103863], [0.985566, 0.720782, 0.112229], [0.984865, 0.728427, 0.120785], [0.984075, 0.736087, 0.129527], [0.983196, 0.743758, 0.138453], [0.982228, 0.751442, 0.147565], [0.981173, 0.759135, 0.156863], [0.980032, 0.766837, 0.166353], [0.978806, 0.774545, 0.176037], [0.977497, 0.782258, 0.185923], [0.976108, 0.789974, 0.196018], [0.974638, 0.797692, 0.206332], [0.973088, 0.805409, 0.216877], [0.971468, 0.813122, 0.227658], [0.969783, 0.820825, 0.238686], [0.968041, 0.828515, 0.249972], [0.966243, 0.836191, 0.261534], [0.964394, 0.843848, 0.273391], [0.962517, 0.851476, 0.285546], [0.960626, 0.859069, 0.29801], [0.95872, 0.866624, 0.31082], [0.956834, 0.874129, 0.323974], [0.954997, 0.881569, 0.337475], [0.953215, 0.888942, 0.351369], [0.951546, 0.896226, 0.365627], [0.950018, 0.903409, 0.380271], [0.948683, 0.910473, 0.395289], [0.947594, 0.917399, 0.410665], [0.946809, 0.924168, 0.426373], [0.946392, 0.930761, 0.442367], [0.946403, 0.937159, 0.458592], [0.946903, 0.943348, 0.47497], [0.947937, 0.949318, 0.491426], [0.949545, 0.955063, 0.50786], [0.95174, 0.960587, 0.524203], [0.954529, 0.965896, 0.540361], [0.957896, 0.971003, 0.556275], [0.961812, 0.975924, 0.571925], [0.966249, 0.980678, 0.587206], [0.971162, 0.985282, 0.602154], [0.976511, 0.989753, 0.61676], [0.982257, 0.994109, 0.631017], [0.988362, 0.998364, 0.644924]] _plasma_data = [[0.050383, 0.029803, 0.527975], [0.063536, 0.028426, 0.533124], [0.075353, 0.027206, 0.538007], [0.086222, 0.026125, 0.542658], [0.096379, 0.025165, 0.547103], [0.10598, 0.024309, 0.551368], [0.115124, 0.023556, 0.555468], [0.123903, 0.022878, 0.559423], [0.132381, 0.022258, 0.56325], [0.140603, 0.021687, 0.566959], [0.148607, 0.021154, 0.570562], [0.156421, 0.020651, 0.574065], [0.16407, 0.020171, 0.577478], [0.171574, 0.019706, 0.580806], [0.17895, 0.019252, 0.584054], [0.186213, 0.018803, 0.587228], [0.193374, 0.018354, 0.59033], [0.200445, 0.017902, 0.593364], [0.207435, 0.017442, 0.596333], [0.21435, 0.016973, 0.599239], [0.221197, 0.016497, 0.602083], [0.227983, 0.016007, 0.604867], [0.234715, 0.015502, 0.607592], [0.241396, 0.014979, 0.610259], [0.248032, 0.014439, 0.612868], [0.254627, 0.013882, 0.615419], [0.261183, 0.013308, 0.617911], [0.267703, 0.012716, 0.620346], [0.274191, 0.012109, 0.622722], [0.280648, 0.011488, 0.625038], [0.287076, 0.010855, 0.627295], [0.293478, 0.010213, 0.62949], [0.299855, 0.009561, 0.631624], [0.30621, 0.008902, 0.633694], [0.312543, 0.008239, 0.6357], [0.318856, 0.007576, 0.63764], [0.32515, 0.006915, 0.639512], [0.331426, 0.006261, 0.641316], [0.337683, 0.005618, 0.643049], [0.343925, 0.004991, 0.64471], [0.35015, 0.004382, 0.646298], [0.356359, 0.003798, 0.64781], [0.362553, 0.003243, 0.649245], [0.368733, 0.002724, 0.650601], [0.374897, 0.002245, 0.651876], [0.381047, 0.001814, 0.653068], [0.387183, 0.001434, 0.654177], [0.393304, 0.001114, 0.655199], [0.399411, 0.000859, 0.656133], [0.405503, 0.000678, 0.656977], [0.41158, 0.000577, 0.65773], [0.417642, 0.000564, 0.65839], [0.423689, 0.000646, 0.658956], [0.429719, 0.000831, 0.659425], [0.435734, 0.001127, 0.659797], [0.441732, 0.00154, 0.660069], [0.447714, 0.00208, 0.66024], [0.453677, 0.002755, 0.66031], [0.459623, 0.003574, 0.660277], [0.46555, 0.004545, 0.660139], [0.471457, 0.005678, 0.659897], [0.477344, 0.00698, 0.659549], [0.48321, 0.00846, 0.659095], [0.489055, 0.010127, 0.658534], [0.494877, 0.01199, 0.657865], [0.500678, 0.014055, 0.657088], [0.506454, 0.016333, 0.656202], [0.512206, 0.018833, 0.655209], [0.517933, 0.021563, 0.654109], [0.523633, 0.024532, 0.652901], [0.529306, 0.027747, 0.651586], [0.534952, 0.031217, 0.650165], [0.54057, 0.03495, 0.64864], [0.546157, 0.038954, 0.64701], [0.551715, 0.043136, 0.645277], [0.557243, 0.047331, 0.643443], [0.562738, 0.051545, 0.641509], [0.568201, 0.055778, 0.639477], [0.573632, 0.060028, 0.637349], [0.579029, 0.064296, 0.635126], [0.584391, 0.068579, 0.632812], [0.589719, 0.072878, 0.630408], [0.595011, 0.07719, 0.627917], [0.600266, 0.081516, 0.625342], [0.605485, 0.085854, 0.622686], [0.610667, 0.090204, 0.619951], [0.615812, 0.094564, 0.61714], [0.620919, 0.098934, 0.614257], [0.625987, 0.103312, 0.611305], [0.631017, 0.107699, 0.608287], [0.636008, 0.112092, 0.605205], [0.640959, 0.116492, 0.602065], [0.645872, 0.120898, 0.598867], [0.650746, 0.125309, 0.595617], [0.65558, 0.129725, 0.592317], [0.660374, 0.134144, 0.588971], [0.665129, 0.138566, 0.585582], [0.669845, 0.142992, 0.582154], [0.674522, 0.147419, 0.578688], [0.67916, 0.151848, 0.575189], [0.683758, 0.156278, 0.57166], [0.688318, 0.160709, 0.568103], [0.69284, 0.165141, 0.564522], [0.697324, 0.169573, 0.560919], [0.701769, 0.174005, 0.557296], [0.706178, 0.178437, 0.553657], [0.710549, 0.182868, 0.550004], [0.714883, 0.187299, 0.546338], [0.719181, 0.191729, 0.542663], [0.723444, 0.196158, 0.538981], [0.72767, 0.200586, 0.535293], [0.731862, 0.205013, 0.531601], [0.736019, 0.209439, 0.527908], [0.740143, 0.213864, 0.524216], [0.744232, 0.218288, 0.520524], [0.748289, 0.222711, 0.516834], [0.752312, 0.227133, 0.513149], [0.756304, 0.231555, 0.509468], [0.760264, 0.235976, 0.505794], [0.764193, 0.240396, 0.502126], [0.76809, 0.244817, 0.498465], [0.771958, 0.249237, 0.494813], [0.775796, 0.253658, 0.491171], [0.779604, 0.258078, 0.487539], [0.783383, 0.2625, 0.483918], [0.787133, 0.266922, 0.480307], [0.790855, 0.271345, 0.476706], [0.794549, 0.27577, 0.473117], [0.798216, 0.280197, 0.469538], [0.801855, 0.284626, 0.465971], [0.805467, 0.289057, 0.462415], [0.809052, 0.293491, 0.45887], [0.812612, 0.297928, 0.455338], [0.816144, 0.302368, 0.451816], [0.819651, 0.306812, 0.448306], [0.823132, 0.311261, 0.444806], [0.826588, 0.315714, 0.441316], [0.830018, 0.320172, 0.437836], [0.833422, 0.324635, 0.434366], [0.836801, 0.329105, 0.430905], [0.840155, 0.33358, 0.427455], [0.843484, 0.338062, 0.424013], [0.846788, 0.342551, 0.420579], [0.850066, 0.347048, 0.417153], [0.853319, 0.351553, 0.413734], [0.856547, 0.356066, 0.410322], [0.85975, 0.360588, 0.406917], [0.862927, 0.365119, 0.403519], [0.866078, 0.36966, 0.400126], [0.869203, 0.374212, 0.396738], [0.872303, 0.378774, 0.393355], [0.875376, 0.383347, 0.389976], [0.878423, 0.387932, 0.3866], [0.881443, 0.392529, 0.383229], [0.884436, 0.397139, 0.37986], [0.887402, 0.401762, 0.376494], [0.89034, 0.406398, 0.37313], [0.89325, 0.411048, 0.369768], [0.896131, 0.415712, 0.366407], [0.898984, 0.420392, 0.363047], [0.901807, 0.425087, 0.359688], [0.904601, 0.429797, 0.356329], [0.907365, 0.434524, 0.35297], [0.910098, 0.439268, 0.34961], [0.9128, 0.444029, 0.346251], [0.915471, 0.448807, 0.34289], [0.918109, 0.453603, 0.339529], [0.920714, 0.458417, 0.336166], [0.923287, 0.463251, 0.332801], [0.925825, 0.468103, 0.329435], [0.928329, 0.472975, 0.326067], [0.930798, 0.477867, 0.322697], [0.933232, 0.48278, 0.319325], [0.93563, 0.487712, 0.315952], [0.93799, 0.492667, 0.312575], [0.940313, 0.497642, 0.309197], [0.942598, 0.502639, 0.305816], [0.944844, 0.507658, 0.302433], [0.947051, 0.512699, 0.299049], [0.949217, 0.517763, 0.295662], [0.951344, 0.52285, 0.292275], [0.953428, 0.52796, 0.288883], [0.95547, 0.533093, 0.28549], [0.957469, 0.53825, 0.282096], [0.959424, 0.543431, 0.278701], [0.961336, 0.548636, 0.275305], [0.963203, 0.553865, 0.271909], [0.965024, 0.559118, 0.268513], [0.966798, 0.564396, 0.265118], [0.968526, 0.5697, 0.261721], [0.970205, 0.575028, 0.258325], [0.971835, 0.580382, 0.254931], [0.973416, 0.585761, 0.25154], [0.974947, 0.591165, 0.248151], [0.976428, 0.596595, 0.244767], [0.977856, 0.602051, 0.241387], [0.979233, 0.607532, 0.238013], [0.980556, 0.613039, 0.234646], [0.981826, 0.618572, 0.231287], [0.983041, 0.624131, 0.227937], [0.984199, 0.629718, 0.224595], [0.985301, 0.63533, 0.221265], [0.986345, 0.640969, 0.217948], [0.987332, 0.646633, 0.214648], [0.98826, 0.652325, 0.211364], [0.989128, 0.658043, 0.2081], [0.989935, 0.663787, 0.204859], [0.990681, 0.669558, 0.201642], [0.991365, 0.675355, 0.198453], [0.991985, 0.681179, 0.195295], [0.992541, 0.68703, 0.19217], [0.993032, 0.692907, 0.189084], [0.993456, 0.69881, 0.186041], [0.993814, 0.704741, 0.183043], [0.994103, 0.710698, 0.180097], [0.994324, 0.716681, 0.177208], [0.994474, 0.722691, 0.174381], [0.994553, 0.728728, 0.171622], [0.994561, 0.734791, 0.168938], [0.994495, 0.74088, 0.166335], [0.994355, 0.746995, 0.163821], [0.994141, 0.753137, 0.161404], [0.993851, 0.759304, 0.159092], [0.993482, 0.765499, 0.156891], [0.993033, 0.77172, 0.154808], [0.992505, 0.777967, 0.152855], [0.991897, 0.784239, 0.151042], [0.991209, 0.790537, 0.149377], [0.990439, 0.796859, 0.14787], [0.989587, 0.803205, 0.146529], [0.988648, 0.809579, 0.145357], [0.987621, 0.815978, 0.144363], [0.986509, 0.822401, 0.143557], [0.985314, 0.828846, 0.142945], [0.984031, 0.835315, 0.142528], [0.982653, 0.841812, 0.142303], [0.98119, 0.848329, 0.142279], [0.979644, 0.854866, 0.142453], [0.977995, 0.861432, 0.142808], [0.976265, 0.868016, 0.143351], [0.974443, 0.874622, 0.144061], [0.97253, 0.88125, 0.144923], [0.970533, 0.887896, 0.145919], [0.968443, 0.894564, 0.147014], [0.966271, 0.901249, 0.14818], [0.964021, 0.90795, 0.14937], [0.961681, 0.914672, 0.15052], [0.959276, 0.921407, 0.151566], [0.956808, 0.928152, 0.152409], [0.954287, 0.934908, 0.152921], [0.951726, 0.941671, 0.152925], [0.949151, 0.948435, 0.152178], [0.946602, 0.95519, 0.150328], [0.944152, 0.961916, 0.146861], [0.941896, 0.96859, 0.140956], [0.940015, 0.975158, 0.131326]] _viridis_data = [[0.267004, 0.004874, 0.329415], [0.26851, 0.009605, 0.335427], [0.269944, 0.014625, 0.341379], [0.271305, 0.019942, 0.347269], [0.272594, 0.025563, 0.353093], [0.273809, 0.031497, 0.358853], [0.274952, 0.037752, 0.364543], [0.276022, 0.044167, 0.370164], [0.277018, 0.050344, 0.375715], [0.277941, 0.056324, 0.381191], [0.278791, 0.062145, 0.386592], [0.279566, 0.067836, 0.391917], [0.280267, 0.073417, 0.397163], [0.280894, 0.078907, 0.402329], [0.281446, 0.08432, 0.407414], [0.281924, 0.089666, 0.412415], [0.282327, 0.094955, 0.417331], [0.282656, 0.100196, 0.42216], [0.28291, 0.105393, 0.426902], [0.283091, 0.110553, 0.431554], [0.283197, 0.11568, 0.436115], [0.283229, 0.120777, 0.440584], [0.283187, 0.125848, 0.44496], [0.283072, 0.130895, 0.449241], [0.282884, 0.13592, 0.453427], [0.282623, 0.140926, 0.457517], [0.28229, 0.145912, 0.46151], [0.281887, 0.150881, 0.465405], [0.281412, 0.155834, 0.469201], [0.280868, 0.160771, 0.472899], [0.280255, 0.165693, 0.476498], [0.279574, 0.170599, 0.479997], [0.278826, 0.17549, 0.483397], [0.278012, 0.180367, 0.486697], [0.277134, 0.185228, 0.489898], [0.276194, 0.190074, 0.493001], [0.275191, 0.194905, 0.496005], [0.274128, 0.199721, 0.498911], [0.273006, 0.20452, 0.501721], [0.271828, 0.209303, 0.504434], [0.270595, 0.214069, 0.507052], [0.269308, 0.218818, 0.509577], [0.267968, 0.223549, 0.512008], [0.26658, 0.228262, 0.514349], [0.265145, 0.232956, 0.516599], [0.263663, 0.237631, 0.518762], [0.262138, 0.242286, 0.520837], [0.260571, 0.246922, 0.522828], [0.258965, 0.251537, 0.524736], [0.257322, 0.25613, 0.526563], [0.255645, 0.260703, 0.528312], [0.253935, 0.265254, 0.529983], [0.252194, 0.269783, 0.531579], [0.250425, 0.27429, 0.533103], [0.248629, 0.278775, 0.534556], [0.246811, 0.283237, 0.535941], [0.244972, 0.287675, 0.53726], [0.243113, 0.292092, 0.538516], [0.241237, 0.296485, 0.539709], [0.239346, 0.300855, 0.540844], [0.237441, 0.305202, 0.541921], [0.235526, 0.309527, 0.542944], [0.233603, 0.313828, 0.543914], [0.231674, 0.318106, 0.544834], [0.229739, 0.322361, 0.545706], [0.227802, 0.326594, 0.546532], [0.225863, 0.330805, 0.547314], [0.223925, 0.334994, 0.548053], [0.221989, 0.339161, 0.548752], [0.220057, 0.343307, 0.549413], [0.21813, 0.347432, 0.550038], [0.21621, 0.351535, 0.550627], [0.214298, 0.355619, 0.551184], [0.212395, 0.359683, 0.55171], [0.210503, 0.363727, 0.552206], [0.208623, 0.367752, 0.552675], [0.206756, 0.371758, 0.553117], [0.204903, 0.375746, 0.553533], [0.203063, 0.379716, 0.553925], [0.201239, 0.38367, 0.554294], [0.19943, 0.387607, 0.554642], [0.197636, 0.391528, 0.554969], [0.19586, 0.395433, 0.555276], [0.1941, 0.399323, 0.555565], [0.192357, 0.403199, 0.555836], [0.190631, 0.407061, 0.556089], [0.188923, 0.41091, 0.556326], [0.187231, 0.414746, 0.556547], [0.185556, 0.41857, 0.556753], [0.183898, 0.422383, 0.556944], [0.182256, 0.426184, 0.55712], [0.180629, 0.429975, 0.557282], [0.179019, 0.433756, 0.55743], [0.177423, 0.437527, 0.557565], [0.175841, 0.44129, 0.557685], [0.174274, 0.445044, 0.557792], [0.172719, 0.448791, 0.557885], [0.171176, 0.45253, 0.557965], [0.169646, 0.456262, 0.55803], [0.168126, 0.459988, 0.558082], [0.166617, 0.463708, 0.558119], [0.165117, 0.467423, 0.558141], [0.163625, 0.471133, 0.558148], [0.162142, 0.474838, 0.55814], [0.160665, 0.47854, 0.558115], [0.159194, 0.482237, 0.558073], [0.157729, 0.485932, 0.558013], [0.15627, 0.489624, 0.557936], [0.154815, 0.493313, 0.55784], [0.153364, 0.497, 0.557724], [0.151918, 0.500685, 0.557587], [0.150476, 0.504369, 0.55743], [0.149039, 0.508051, 0.55725], [0.147607, 0.511733, 0.557049], [0.14618, 0.515413, 0.556823], [0.144759, 0.519093, 0.556572], [0.143343, 0.522773, 0.556295], [0.141935, 0.526453, 0.555991], [0.140536, 0.530132, 0.555659], [0.139147, 0.533812, 0.555298], [0.13777, 0.537492, 0.554906], [0.136408, 0.541173, 0.554483], [0.135066, 0.544853, 0.554029], [0.133743, 0.548535, 0.553541], [0.132444, 0.552216, 0.553018], [0.131172, 0.555899, 0.552459], [0.129933, 0.559582, 0.551864], [0.128729, 0.563265, 0.551229], [0.127568, 0.566949, 0.550556], [0.126453, 0.570633, 0.549841], [0.125394, 0.574318, 0.549086], [0.124395, 0.578002, 0.548287], [0.123463, 0.581687, 0.547445], [0.122606, 0.585371, 0.546557], [0.121831, 0.589055, 0.545623], [0.121148, 0.592739, 0.544641], [0.120565, 0.596422, 0.543611], [0.120092, 0.600104, 0.54253], [0.119738, 0.603785, 0.5414], [0.119512, 0.607464, 0.540218], [0.119423, 0.611141, 0.538982], [0.119483, 0.614817, 0.537692], [0.119699, 0.61849, 0.536347], [0.120081, 0.622161, 0.534946], [0.120638, 0.625828, 0.533488], [0.12138, 0.629492, 0.531973], [0.122312, 0.633153, 0.530398], [0.123444, 0.636809, 0.528763], [0.12478, 0.640461, 0.527068], [0.126326, 0.644107, 0.525311], [0.128087, 0.647749, 0.523491], [0.130067, 0.651384, 0.521608], [0.132268, 0.655014, 0.519661], [0.134692, 0.658636, 0.517649], [0.137339, 0.662252, 0.515571], [0.14021, 0.665859, 0.513427], [0.143303, 0.669459, 0.511215], [0.146616, 0.67305, 0.508936], [0.150148, 0.676631, 0.506589], [0.153894, 0.680203, 0.504172], [0.157851, 0.683765, 0.501686], [0.162016, 0.687316, 0.499129], [0.166383, 0.690856, 0.496502], [0.170948, 0.694384, 0.493803], [0.175707, 0.6979, 0.491033], [0.180653, 0.701402, 0.488189], [0.185783, 0.704891, 0.485273], [0.19109, 0.708366, 0.482284], [0.196571, 0.711827, 0.479221], [0.202219, 0.715272, 0.476084], [0.20803, 0.718701, 0.472873], [0.214, 0.722114, 0.469588], [0.220124, 0.725509, 0.466226], [0.226397, 0.728888, 0.462789], [0.232815, 0.732247, 0.459277], [0.239374, 0.735588, 0.455688], [0.24607, 0.73891, 0.452024], [0.252899, 0.742211, 0.448284], [0.259857, 0.745492, 0.444467], [0.266941, 0.748751, 0.440573], [0.274149, 0.751988, 0.436601], [0.281477, 0.755203, 0.432552], [0.288921, 0.758394, 0.428426], [0.296479, 0.761561, 0.424223], [0.304148, 0.764704, 0.419943], [0.311925, 0.767822, 0.415586], [0.319809, 0.770914, 0.411152], [0.327796, 0.77398, 0.40664], [0.335885, 0.777018, 0.402049], [0.344074, 0.780029, 0.397381], [0.35236, 0.783011, 0.392636], [0.360741, 0.785964, 0.387814], [0.369214, 0.788888, 0.382914], [0.377779, 0.791781, 0.377939], [0.386433, 0.794644, 0.372886], [0.395174, 0.797475, 0.367757], [0.404001, 0.800275, 0.362552], [0.412913, 0.803041, 0.357269], [0.421908, 0.805774, 0.35191], [0.430983, 0.808473, 0.346476], [0.440137, 0.811138, 0.340967], [0.449368, 0.813768, 0.335384], [0.458674, 0.816363, 0.329727], [0.468053, 0.818921, 0.323998], [0.477504, 0.821444, 0.318195], [0.487026, 0.823929, 0.312321], [0.496615, 0.826376, 0.306377], [0.506271, 0.828786, 0.300362], [0.515992, 0.831158, 0.294279], [0.525776, 0.833491, 0.288127], [0.535621, 0.835785, 0.281908], [0.545524, 0.838039, 0.275626], [0.555484, 0.840254, 0.269281], [0.565498, 0.84243, 0.262877], [0.575563, 0.844566, 0.256415], [0.585678, 0.846661, 0.249897], [0.595839, 0.848717, 0.243329], [0.606045, 0.850733, 0.236712], [0.616293, 0.852709, 0.230052], [0.626579, 0.854645, 0.223353], [0.636902, 0.856542, 0.21662], [0.647257, 0.8584, 0.209861], [0.657642, 0.860219, 0.203082], [0.668054, 0.861999, 0.196293], [0.678489, 0.863742, 0.189503], [0.688944, 0.865448, 0.182725], [0.699415, 0.867117, 0.175971], [0.709898, 0.868751, 0.169257], [0.720391, 0.87035, 0.162603], [0.730889, 0.871916, 0.156029], [0.741388, 0.873449, 0.149561], [0.751884, 0.874951, 0.143228], [0.762373, 0.876424, 0.137064], [0.772852, 0.877868, 0.131109], [0.783315, 0.879285, 0.125405], [0.79376, 0.880678, 0.120005], [0.804182, 0.882046, 0.114965], [0.814576, 0.883393, 0.110347], [0.82494, 0.88472, 0.106217], [0.83527, 0.886029, 0.102646], [0.845561, 0.887322, 0.099702], [0.85581, 0.888601, 0.097452], [0.866013, 0.889868, 0.095953], [0.876168, 0.891125, 0.09525], [0.886271, 0.892374, 0.095374], [0.89632, 0.893616, 0.096335], [0.906311, 0.894855, 0.098125], [0.916242, 0.896091, 0.100717], [0.926106, 0.89733, 0.104071], [0.935904, 0.89857, 0.108131], [0.945636, 0.899815, 0.112838], [0.9553, 0.901065, 0.118128], [0.964894, 0.902323, 0.123941], [0.974417, 0.90359, 0.130215], [0.983868, 0.904867, 0.136897], [0.993248, 0.906157, 0.143936]] _cividis_data = [[0.0, 0.135112, 0.304751], [0.0, 0.138068, 0.311105], [0.0, 0.141013, 0.317579], [0.0, 0.143951, 0.323982], [0.0, 0.146877, 0.330479], [0.0, 0.149791, 0.337065], [0.0, 0.152673, 0.343704], [0.0, 0.155377, 0.3505], [0.0, 0.157932, 0.357521], [0.0, 0.160495, 0.364534], [0.0, 0.163058, 0.371608], [0.0, 0.165621, 0.378769], [0.0, 0.168204, 0.385902], [0.0, 0.1708, 0.3931], [0.0, 0.17342, 0.400353], [0.0, 0.176082, 0.407577], [0.0, 0.178802, 0.414764], [0.0, 0.18161, 0.421859], [0.0, 0.18455, 0.428802], [0.0, 0.186915, 0.435532], [0.0, 0.188769, 0.439563], [0.0, 0.19095, 0.441085], [0.0, 0.193366, 0.441561], [0.003602, 0.195911, 0.441564], [0.017852, 0.198528, 0.441248], [0.03211, 0.201199, 0.440785], [0.046205, 0.203903, 0.440196], [0.058378, 0.206629, 0.439531], [0.068968, 0.209372, 0.438863], [0.078624, 0.212122, 0.438105], [0.087465, 0.214879, 0.437342], [0.095645, 0.217643, 0.436593], [0.103401, 0.220406, 0.43579], [0.110658, 0.22317, 0.435067], [0.117612, 0.225935, 0.434308], [0.124291, 0.228697, 0.433547], [0.130669, 0.231458, 0.43284], [0.13683, 0.234216, 0.432148], [0.142852, 0.236972, 0.431404], [0.148638, 0.239724, 0.430752], [0.154261, 0.242475, 0.43012], [0.159733, 0.245221, 0.429528], [0.165113, 0.247965, 0.428908], [0.170362, 0.250707, 0.428325], [0.17549, 0.253444, 0.42779], [0.180503, 0.25618, 0.427299], [0.185453, 0.258914, 0.426788], [0.190303, 0.261644, 0.426329], [0.195057, 0.264372, 0.425924], [0.199764, 0.267099, 0.425497], [0.204385, 0.269823, 0.425126], [0.208926, 0.272546, 0.424809], [0.213431, 0.275266, 0.42448], [0.217863, 0.277985, 0.424206], [0.222264, 0.280702, 0.423914], [0.226598, 0.283419, 0.423678], [0.230871, 0.286134, 0.423498], [0.23512, 0.288848, 0.423304], [0.239312, 0.291562, 0.423167], [0.243485, 0.294274, 0.423014], [0.247605, 0.296986, 0.422917], [0.251675, 0.299698, 0.422873], [0.255731, 0.302409, 0.422814], [0.25974, 0.30512, 0.42281], [0.263738, 0.307831, 0.422789], [0.267693, 0.310542, 0.422821], [0.271639, 0.313253, 0.422837], [0.275513, 0.315965, 0.422979], [0.279411, 0.318677, 0.423031], [0.28324, 0.32139, 0.423211], [0.287065, 0.324103, 0.423373], [0.290884, 0.326816, 0.423517], [0.294669, 0.329531, 0.423716], [0.298421, 0.332247, 0.423973], [0.302169, 0.334963, 0.424213], [0.305886, 0.337681, 0.424512], [0.309601, 0.340399, 0.42479], [0.313287, 0.34312, 0.42512], [0.316941, 0.345842, 0.425512], [0.320595, 0.348565, 0.425889], [0.32425, 0.351289, 0.42625], [0.327875, 0.354016, 0.42667], [0.331474, 0.356744, 0.427144], [0.335073, 0.359474, 0.427605], [0.338673, 0.362206, 0.428053], [0.342246, 0.364939, 0.428559], [0.345793, 0.367676, 0.429127], [0.349341, 0.370414, 0.429685], [0.352892, 0.373153, 0.430226], [0.356418, 0.375896, 0.430823], [0.359916, 0.378641, 0.431501], [0.363446, 0.381388, 0.432075], [0.366923, 0.384139, 0.432796], [0.37043, 0.38689, 0.433428], [0.373884, 0.389646, 0.434209], [0.377371, 0.392404, 0.43489], [0.38083, 0.395164, 0.435653], [0.384268, 0.397928, 0.436475], [0.387705, 0.400694, 0.437305], [0.391151, 0.403464, 0.438096], [0.394568, 0.406236, 0.438986], [0.397991, 0.409011, 0.439848], [0.401418, 0.41179, 0.440708], [0.40482, 0.414572, 0.441642], [0.408226, 0.417357, 0.44257], [0.411607, 0.420145, 0.443577], [0.414992, 0.422937, 0.444578], [0.418383, 0.425733, 0.44556], [0.421748, 0.428531, 0.44664], [0.42512, 0.431334, 0.447692], [0.428462, 0.43414, 0.448864], [0.431817, 0.43695, 0.449982], [0.435168, 0.439763, 0.451134], [0.438504, 0.44258, 0.452341], [0.44181, 0.445402, 0.453659], [0.445148, 0.448226, 0.454885], [0.448447, 0.451053, 0.456264], [0.451759, 0.453887, 0.457582], [0.455072, 0.456718, 0.458976], [0.458366, 0.459552, 0.460457], [0.461616, 0.462405, 0.461969], [0.464947, 0.465241, 0.463395], [0.468254, 0.468083, 0.464908], [0.471501, 0.47096, 0.466357], [0.474812, 0.473832, 0.467681], [0.478186, 0.476699, 0.468845], [0.481622, 0.479573, 0.469767], [0.485141, 0.482451, 0.470384], [0.488697, 0.485318, 0.471008], [0.492278, 0.488198, 0.471453], [0.495913, 0.491076, 0.471751], [0.499552, 0.49396, 0.472032], [0.503185, 0.496851, 0.472305], [0.506866, 0.499743, 0.472432], [0.51054, 0.502643, 0.47255], [0.514226, 0.505546, 0.47264], [0.51792, 0.508454, 0.472707], [0.521643, 0.511367, 0.472639], [0.525348, 0.514285, 0.47266], [0.529086, 0.517207, 0.472543], [0.532829, 0.520135, 0.472401], [0.536553, 0.523067, 0.472352], [0.540307, 0.526005, 0.472163], [0.544069, 0.528948, 0.471947], [0.54784, 0.531895, 0.471704], [0.551612, 0.534849, 0.471439], [0.555393, 0.537807, 0.471147], [0.559181, 0.540771, 0.470829], [0.562972, 0.543741, 0.470488], [0.566802, 0.546715, 0.469988], [0.570607, 0.549695, 0.469593], [0.574417, 0.552682, 0.469172], [0.578236, 0.555673, 0.468724], [0.582087, 0.55867, 0.468118], [0.585916, 0.561674, 0.467618], [0.589753, 0.564682, 0.46709], [0.593622, 0.567697, 0.466401], [0.597469, 0.570718, 0.465821], [0.601354, 0.573743, 0.465074], [0.605211, 0.576777, 0.464441], [0.609105, 0.579816, 0.463638], [0.612977, 0.582861, 0.46295], [0.616852, 0.585913, 0.462237], [0.620765, 0.58897, 0.461351], [0.624654, 0.592034, 0.460583], [0.628576, 0.595104, 0.459641], [0.632506, 0.59818, 0.458668], [0.636412, 0.601264, 0.457818], [0.640352, 0.604354, 0.456791], [0.64427, 0.60745, 0.455886], [0.648222, 0.610553, 0.454801], [0.652178, 0.613664, 0.453689], [0.656114, 0.61678, 0.452702], [0.660082, 0.619904, 0.451534], [0.664055, 0.623034, 0.450338], [0.668008, 0.626171, 0.44927], [0.671991, 0.629316, 0.448018], [0.675981, 0.632468, 0.446736], [0.679979, 0.635626, 0.445424], [0.68395, 0.638793, 0.444251], [0.687957, 0.641966, 0.442886], [0.691971, 0.645145, 0.441491], [0.695985, 0.648334, 0.440072], [0.700008, 0.651529, 0.438624], [0.704037, 0.654731, 0.437147], [0.708067, 0.657942, 0.435647], [0.712105, 0.66116, 0.434117], [0.716177, 0.664384, 0.432386], [0.720222, 0.667618, 0.430805], [0.724274, 0.670859, 0.429194], [0.728334, 0.674107, 0.427554], [0.732422, 0.677364, 0.425717], [0.736488, 0.680629, 0.424028], [0.740589, 0.6839, 0.422131], [0.744664, 0.687181, 0.420393], [0.748772, 0.69047, 0.418448], [0.752886, 0.693766, 0.416472], [0.756975, 0.697071, 0.414659], [0.761096, 0.700384, 0.412638], [0.765223, 0.703705, 0.410587], [0.769353, 0.707035, 0.408516], [0.773486, 0.710373, 0.406422], [0.777651, 0.713719, 0.404112], [0.781795, 0.717074, 0.401966], [0.785965, 0.720438, 0.399613], [0.790116, 0.72381, 0.397423], [0.794298, 0.72719, 0.395016], [0.79848, 0.73058, 0.392597], [0.802667, 0.733978, 0.390153], [0.806859, 0.737385, 0.387684], [0.811054, 0.740801, 0.385198], [0.815274, 0.744226, 0.382504], [0.819499, 0.747659, 0.379785], [0.823729, 0.751101, 0.377043], [0.827959, 0.754553, 0.374292], [0.832192, 0.758014, 0.371529], [0.836429, 0.761483, 0.368747], [0.840693, 0.764962, 0.365746], [0.844957, 0.76845, 0.362741], [0.849223, 0.771947, 0.359729], [0.853515, 0.775454, 0.3565], [0.857809, 0.778969, 0.353259], [0.862105, 0.782494, 0.350011], [0.866421, 0.786028, 0.346571], [0.870717, 0.789572, 0.343333], [0.875057, 0.793125, 0.339685], [0.879378, 0.796687, 0.336241], [0.88372, 0.800258, 0.332599], [0.888081, 0.803839, 0.32877], [0.89244, 0.80743, 0.324968], [0.896818, 0.81103, 0.320982], [0.901195, 0.814639, 0.317021], [0.905589, 0.818257, 0.312889], [0.91, 0.821885, 0.308594], [0.914407, 0.825522, 0.304348], [0.918828, 0.829168, 0.29996], [0.923279, 0.832822, 0.295244], [0.927724, 0.836486, 0.290611], [0.93218, 0.840159, 0.28588], [0.93666, 0.843841, 0.280876], [0.941147, 0.84753, 0.275815], [0.945654, 0.851228, 0.270532], [0.950178, 0.854933, 0.265085], [0.954725, 0.858646, 0.259365], [0.959284, 0.862365, 0.253563], [0.963872, 0.866089, 0.247445], [0.968469, 0.869819, 0.24131], [0.973114, 0.87355, 0.234677], [0.97778, 0.877281, 0.227954], [0.982497, 0.881008, 0.220878], [0.987293, 0.884718, 0.213336], [0.992218, 0.888385, 0.205468], [0.994847, 0.892954, 0.203445], [0.995249, 0.898384, 0.207561], [0.995503, 0.903866, 0.21237], [0.995737, 0.909344, 0.217772]] _twilight_data = [[0.8857501584075443, 0.8500092494306783, 0.8879736506427196], [0.8837852019553906, 0.8507294054031063, 0.8872322209694989], [0.8817223105928579, 0.8512759407765347, 0.8863805692551482], [0.8795410528270573, 0.8516567540749572, 0.8854143767924102], [0.8772488085896548, 0.8518702833887027, 0.8843412038131143], [0.8748534750857597, 0.8519152612302319, 0.8831692696761383], [0.8723313408512408, 0.8518016547808089, 0.8818970435500162], [0.8697047485350982, 0.8515240300479789, 0.8805388339000336], [0.8669601550533358, 0.8510896085314068, 0.8790976697717334], [0.86408985081464, 0.8505039116750779, 0.8775792578489263], [0.8611024543689985, 0.8497675485700126, 0.8759924292343957], [0.8579825924567037, 0.8488893481028184, 0.8743403855344628], [0.8547259318925698, 0.8478748812467282, 0.8726282980930582], [0.8513371457085719, 0.8467273579611647, 0.8708608165735044], [0.8478071070257792, 0.8454546229209523, 0.8690403678369444], [0.8441261828674842, 0.8440648271103739, 0.8671697332269007], [0.8403042080595778, 0.8425605950855084, 0.865250882410458], [0.8363403180919118, 0.8409479651895194, 0.8632852800107016], [0.8322270571293441, 0.8392349062775448, 0.8612756350042788], [0.8279689431601354, 0.837426007513952, 0.8592239945130679], [0.8235742968025285, 0.8355248776479544, 0.8571319132851495], [0.8190465467793753, 0.8335364929949034, 0.855002062870101], [0.8143898212114309, 0.8314655869419785, 0.8528375906214702], [0.8095999819094809, 0.8293189667350546, 0.8506444160105037], [0.8046916442981458, 0.8270983878056066, 0.8484244929697402], [0.79967075421268, 0.8248078181208093, 0.8461821002957853], [0.7945430508923111, 0.8224511622630462, 0.8439218478682798], [0.7893144556460892, 0.8200321318870201, 0.8416486380471222], [0.7839910104276492, 0.8175542640053343, 0.8393674746403673], [0.7785789200822759, 0.8150208937874255, 0.8370834463093898], [0.7730841659017094, 0.8124352473546601, 0.8348017295057968], [0.7675110850441786, 0.8098007598713145, 0.8325281663805967], [0.7618690793798029, 0.8071194938764749, 0.830266486168872], [0.7561644358438198, 0.8043940873347794, 0.8280213899472], [0.750403467654067, 0.8016269900896532, 0.8257973785108242], [0.7445924777189017, 0.7988204771958325, 0.8235986758615652], [0.7387377170049494, 0.7959766573503101, 0.8214292278043301], [0.7328454364552346, 0.7930974646884407, 0.8192926338423038], [0.726921775128297, 0.7901846863592763, 0.8171921746672638], [0.7209728066553678, 0.7872399592345264, 0.8151307392087926], [0.7150040307625213, 0.7842648709158119, 0.8131111655994991], [0.709020781345393, 0.7812608871607091, 0.8111359185511793], [0.7030297722540817, 0.7782290497335813, 0.8092061884805697], [0.6970365443886174, 0.7751705000806606, 0.8073233538006345], [0.691046410093091, 0.7720862946067809, 0.8054884169067907], [0.6850644615439593, 0.7689774029354699, 0.8037020626717691], [0.6790955449988215, 0.765844721313959, 0.8019646617300199], [0.6731442255942621, 0.7626890873389048, 0.8002762854580953], [0.6672147980375281, 0.7595112803730375, 0.7986367465453776], [0.6613112930078745, 0.7563120270871903, 0.7970456043491897], [0.6554369232645472, 0.7530920875676843, 0.7955027112903105], [0.6495957300425348, 0.7498520122194177, 0.7940067402149911], [0.6437910831099849, 0.7465923800833657, 0.7925565320130605], [0.6380258682854598, 0.7433137671403319, 0.7911510045957317], [0.6323027138710603, 0.740016721601314, 0.7897889276264043], [0.6266240202260459, 0.7367017540369944, 0.7884690131633456], [0.6209919306481755, 0.733369347989232, 0.7871899462469658], [0.6154084641177048, 0.7300199523273969, 0.7859502270675048], [0.6098754317609306, 0.7266539875975829, 0.7847483573269471], [0.6043943420027486, 0.7232718614323369, 0.7835829559353559], [0.5989665814482068, 0.7198739489224673, 0.7824525989934664], [0.5935933569683722, 0.7164606049658685, 0.781355882376401], [0.588275797805555, 0.7130321464645814, 0.7802914140563652], [0.5830148703693241, 0.7095888767699747, 0.7792578182047659], [0.5778116438998202, 0.7061310615715398, 0.7782534512102552], [0.5726668948158774, 0.7026589535425779, 0.7772770268091199], [0.5675811785386197, 0.6991727930264627, 0.776327485342753], [0.5625551535721934, 0.6956727838162965, 0.7754035914230984], [0.5575894041960517, 0.6921591145825405, 0.7745041337932782], [0.5526845058934713, 0.6886319451516638, 0.7736279426902245], [0.5478409815301863, 0.6850914221850988, 0.7727738647344087], [0.5430593242401823, 0.6815376725306588, 0.7719407969783508], [0.5383401557517628, 0.677970811290954, 0.7711273443905772], [0.533683891477284, 0.6743909370521273, 0.7703325054879735], [0.529090861832473, 0.6707981230280622, 0.7695555229231313], [0.5245615147059358, 0.6671924299614223, 0.7687954171423095], [0.5200962739223556, 0.6635739143403039, 0.768051194033441], [0.5156955988596057, 0.65994260812898, 0.7673219148959617], [0.5113599254160193, 0.6562985398183186, 0.7666066378064533], [0.5070896957645166, 0.6526417240314645, 0.7659044566083585], [0.5028853540415561, 0.6489721673409526, 0.7652144671817491], [0.4987473366135607, 0.6452898684900934, 0.7645357873418008], [0.4946761847863938, 0.6415948411950443, 0.7638671900213091], [0.4906722493856122, 0.6378870485884708, 0.7632081276316384], [0.4867359599430568, 0.6341664625110051, 0.7625578008592404], [0.4828677867260272, 0.6304330455306234, 0.761915371498953], [0.47906816236197386, 0.6266867625186013, 0.7612800037566242], [0.47533752394906287, 0.6229275728383581, 0.7606508557181775], [0.4716762951887709, 0.6191554324288464, 0.7600270922788305], [0.46808490970531597, 0.6153702869579029, 0.7594078989109274], [0.4645637671630393, 0.6115720882286415, 0.7587924262302581], [0.4611132664702388, 0.607760777169989, 0.7581798643680714], [0.45773377230160567, 0.6039363004658646, 0.7575693690185916], [0.45442563977552913, 0.6000985950385866, 0.7569601366060649], [0.45118918687617743, 0.5962476205135354, 0.7563512064324664], [0.4480247093358917, 0.5923833145214658, 0.7557417647410792], [0.4449324685421538, 0.5885055998308617, 0.7551311041857901], [0.441912717666964, 0.5846144110017557, 0.7545183888441067], [0.43896563958048396, 0.5807096924109849, 0.7539027620828594], [0.4360913895835637, 0.5767913799818608, 0.7532834105961016], [0.43329008867358393, 0.5728594162560667, 0.7526594653256667], [0.4305617907305757, 0.5689137457245718, 0.752030080993127], [0.42790652284925834, 0.5649543060909209, 0.7513944352191484], [0.42532423665011354, 0.560981049599503, 0.7507516498900512], [0.4228148567577266, 0.5569939212699658, 0.7501008698822764], [0.42037822361396326, 0.5529928715810817, 0.7494412559451894], [0.4180141407923363, 0.5489778542188889, 0.7487719316700112], [0.4157223260454232, 0.544948827153504, 0.7480920445900052], [0.4135024574331473, 0.5409057477109848, 0.7474007329754309], [0.4113541469730457, 0.5368485776500593, 0.7466971285506578], [0.4092768899914751, 0.5327773017713032, 0.7459803063570782], [0.4072701869421907, 0.5286918801105741, 0.7452494263758127], [0.4053334378930318, 0.5245922817498312, 0.7445036583670813], [0.40346600333905397, 0.5204784765384003, 0.7437421522356709], [0.40166714010896104, 0.5163504496968876, 0.7429640345324835], [0.39993606933454834, 0.5122081814321852, 0.7421684457131799], [0.3982719152586337, 0.5080516653927614, 0.7413545091809972], [0.3966737490566561, 0.5038808905384797, 0.7405213858051674], [0.3951405880820763, 0.4996958532637776, 0.7396682021171571], [0.39367135736822567, 0.4954965577745118, 0.738794102296364], [0.39226494876209317, 0.4912830033289926, 0.7378982478447508], [0.390920175719949, 0.4870552025122304, 0.7369797713388125], [0.38963580160340855, 0.48281316715123496, 0.7360378254693274], [0.3884105330084243, 0.47855691131792805, 0.7350715764115726], [0.3872430145933025, 0.4742864593363539, 0.7340801678785439], [0.386131841788921, 0.4700018340988123, 0.7330627749243106], [0.3850755679365139, 0.46570306719930193, 0.732018540336905], [0.38407269378943537, 0.46139018782416635, 0.7309466543290268], [0.3831216808440275, 0.457063235814072, 0.7298462679135326], [0.38222094988570376, 0.45272225034283325, 0.7287165614400378], [0.3813688793045416, 0.4483672766927786, 0.7275567131714135], [0.3805638069656562, 0.4439983720863372, 0.7263658704513531], [0.3798040374484875, 0.4396155882122263, 0.7251432377876109], [0.3790878928311076, 0.43521897612544935, 0.7238879869132313], [0.378413635091359, 0.43080859411413064, 0.7225993199306104], [0.3777794975351373, 0.4263845142616835, 0.7212763999353023], [0.3771837184425123, 0.4219468022345483, 0.7199184152447577], [0.37662448930806297, 0.41749553747893614, 0.7185245473617611], [0.37610001286385814, 0.4130307995247706, 0.7170939691992023], [0.375608469194424, 0.40855267638072096, 0.7156258509158755], [0.37514802505380473, 0.4040612609993941, 0.7141193695725726], [0.3747168601930223, 0.3995566498711684, 0.7125736851650046], [0.3743131319931234, 0.3950389482828331, 0.7109879652237746], [0.3739349933047578, 0.3905082752937583, 0.7093613429347845], [0.3735806215098284, 0.3859647438605754, 0.7076929760731058], [0.37324816143326384, 0.38140848555753937, 0.7059820097480604], [0.3729357864666503, 0.3768396383521984, 0.7042275578058994], [0.37264166757849604, 0.3722583500483685, 0.7024287314570723], [0.37236397858465387, 0.36766477862108266, 0.7005846349652077], [0.3721008970244382, 0.3630590973698238, 0.6986943461507372], [0.3718506155898596, 0.3584414828587522, 0.6967569581025654], [0.3716113323440048, 0.3538121372967869, 0.6947714991938089], [0.37138124223736607, 0.34917126878479027, 0.6927370347192883], [0.37115856636209105, 0.3445191141023017, 0.6906525358646499], [0.3709415155133733, 0.33985591488818123, 0.6885170337950512], [0.3707283327942267, 0.33518193808489577, 0.6863294816960677], [0.37051738634484427, 0.3304974124430785, 0.6840888878885721], [0.37030682071842685, 0.32580269697872455, 0.6817941168448668], [0.37009487130772695, 0.3210981375964933, 0.6794440539905685], [0.3698798032902536, 0.31638410101153364, 0.6770375543809057], [0.36965987626565955, 0.3116609876295197, 0.6745734474341955], [0.3694333459127623, 0.3069292355186234, 0.6720505284912062], [0.36919847837592484, 0.3021893217650707, 0.6694675433161452], [0.3689535530659678, 0.29744175492366276, 0.6668232208982426], [0.3686968223189527, 0.292687098561501, 0.6641162529823691], [0.36842655638020444, 0.2879259643777846, 0.661345269109446], [0.3681410147989972, 0.2831590122118299, 0.6585088880697231], [0.3678384369653108, 0.2783869718129776, 0.655605668384537], [0.36751707094367697, 0.2736106331709098, 0.6526341171161864], [0.36717513650699446, 0.26883085667326956, 0.6495927229789225], [0.3668108554010799, 0.26404857724525643, 0.6464799165290824], [0.3664224325155063, 0.25926481158628106, 0.6432940914076554], [0.36600853966739794, 0.25448043878086224, 0.6400336180336859], [0.3655669837353898, 0.24969683475296395, 0.6366967518748858], [0.3650957984588681, 0.24491536803550484, 0.6332817352005559], [0.3645930889012501, 0.24013747024823828, 0.629786801550261], [0.3640569302208851, 0.23536470386204195, 0.6262101345195302], [0.36348537610385145, 0.2305987621839642, 0.6225498862239288], [0.3628764356004103, 0.2258414929328703, 0.6188041741082302], [0.36222809558295926, 0.22109488427338303, 0.6149711234609613], [0.36153829010998356, 0.21636111429594002, 0.6110488067964093], [0.36080493826624654, 0.21164251793458128, 0.6070353217206471], [0.36002681809096376, 0.20694122817889948, 0.6029284543191687], [0.35920088560930186, 0.20226037920758122, 0.5987265295935138], [0.3583248996661781, 0.197602942459778, 0.5944276851750107], [0.35739663292915563, 0.1929720819784246, 0.5900301125106313], [0.35641381143126327, 0.18837119869242164, 0.5855320765920552], [0.3553741530690672, 0.18380392577704466, 0.580931914318328], [0.3542753496066376, 0.17927413271618647, 0.5762280966066872], [0.35311574421123737, 0.17478570377561287, 0.5714187152355529], [0.3518924860887379, 0.17034320478524959, 0.5665028491121665], [0.3506030444193101, 0.1659512998472086, 0.5614796470399323], [0.34924513554955644, 0.16161477763045118, 0.5563483747416378], [0.3478165323877778, 0.1573386351115298, 0.5511085345270326], [0.3463150717579309, 0.15312802296627787, 0.5457599924248665], [0.34473901574536375, 0.1489882058982641, 0.5403024592040654], [0.34308600291572294, 0.14492465359918028, 0.534737042820671], [0.34135411074506483, 0.1409427920655632, 0.5290650094033675], [0.33954168752669694, 0.1370480189671817, 0.5232879753508524], [0.3376473209067111, 0.13324562282438077, 0.5174080757397947], [0.33566978565015315, 0.12954074251271822, 0.5114280721516895], [0.33360804901486, 0.1259381830100592, 0.505351647966549], [0.33146154891145124, 0.12244245263391232, 0.4991827458843107], [0.3292300520323141, 0.11905764321981127, 0.49292595612342666], [0.3269137124539796, 0.1157873496841953, 0.4865864649569746], [0.32451307931207785, 0.11263459791730848, 0.48017007211645196], [0.3220288227606932, 0.10960114111258401, 0.4736849472572688], [0.31946262395497965, 0.1066887988239266, 0.46713728801395243], [0.316816480890235, 0.10389861387653518, 0.46053414662739794], [0.3140927841475553, 0.10123077676403242, 0.45388335612058467], [0.31129434479712365, 0.0986847719340522, 0.4471931371516162], [0.30842444457210105, 0.09625938534057774, 0.44047194882050544], [0.30548675819945936, 0.09395276484082374, 0.4337284999936111], [0.3024853636457425, 0.0917611873973036, 0.42697404043749887], [0.2994248396021477, 0.08968225371675004, 0.42021619665853854], [0.2963100038890529, 0.08771325096046395, 0.41346259134143476], [0.2931459309698525, 0.08585065688962071, 0.40672178082365834], [0.2899379244517661, 0.08409078829085731, 0.40000214725256295], [0.28669151388283165, 0.08242987384848069, 0.39331182532243375], [0.28341239797185225, 0.08086415336549937, 0.38665868550105914], [0.2801063857697547, 0.07938999480226153, 0.38005028528138707], [0.2767793961581559, 0.07800394103378822, 0.37349382846504675], [0.2734373934245081, 0.07670280023749607, 0.36699616136347685], [0.2700863774911405, 0.07548367558427554, 0.36056376228111864], [0.26673233211995284, 0.0743440180285462, 0.3542027606624096], [0.26338121807151404, 0.07328165793989708, 0.34791888996380105], [0.26003895187439957, 0.0722947810433622, 0.3417175669546984], [0.256711916510839, 0.07138010624208224, 0.3356064898460009], [0.25340685873736807, 0.07053358292685183, 0.3295945757321303], [0.2501284530619938, 0.06975820642910699, 0.32368100685760637], [0.24688226237959, 0.06905363944920445, 0.31786993834254956], [0.24367372557466271, 0.06841985515092269, 0.3121652405088837], [0.2405081333229594, 0.0678571038148556, 0.3065705449367832], [0.23739062429054825, 0.06736588805055552, 0.3010892218406587], [0.23433055727563878, 0.0669355996616394, 0.295740099298676], [0.23132955273021344, 0.06657618693909059, 0.29051361067988485], [0.2283917709422868, 0.06628997924139618, 0.28541074411068496], [0.22552164337737857, 0.0660781731193956, 0.28043398847505197], [0.22272706739121817, 0.06593379067565194, 0.275597146520537], [0.22001251100779617, 0.0658579189189076, 0.2709027999432586], [0.21737845072382705, 0.06585966123356204, 0.2663420934966951], [0.21482843531473683, 0.06594038561377849, 0.26191675992376573], [0.21237411048541005, 0.06608502466175845, 0.2576516509356954], [0.21001214221188125, 0.06630857391894718, 0.2535289048041211], [0.2077442377448806, 0.06661453200418091, 0.24954644291943817], [0.20558051999470117, 0.06699046239786874, 0.24572497420147632], [0.20352007949514977, 0.06744417961242422, 0.24205576625191821], [0.2015613376412984, 0.06798327102620025, 0.23852974228695395], [0.19971571438603364, 0.06859271055370472, 0.23517094067076993], [0.19794834061899208, 0.06931406607166066, 0.23194647381302336], [0.1960826032659409, 0.07032122724242362, 0.22874673279569585], [0.19410351363791453, 0.07160830485689157, 0.22558727307410353], [0.19199449184606268, 0.0731828306492733, 0.22243385243433622], [0.18975853639094634, 0.07501986186214377, 0.2193005075652994], [0.18739228342697645, 0.07710209689958833, 0.21618875376309582], [0.18488035509396164, 0.07942573027972388, 0.21307651648984993], [0.18774482037046955, 0.07725158846803931, 0.21387448578597812], [0.19049578401722037, 0.07531127841678764, 0.2146562337112265], [0.1931548636579131, 0.07360681904011795, 0.21542362939081539], [0.19571853588267552, 0.07215778103960274, 0.21617499187076789], [0.19819343656336558, 0.07097462525273879, 0.21690975060032436], [0.20058760685133747, 0.07006457614998421, 0.21762721310371608], [0.20290365333558247, 0.06943524858045896, 0.21833167885096033], [0.20531725273301316, 0.06891959226639757, 0.21911516689288835], [0.20785704662965598, 0.06848439879702528, 0.22000133917653536], [0.21052882914958676, 0.06812195249816172, 0.22098759107715404], [0.2133313859647627, 0.06783014842602667, 0.2220704321302429], [0.21625279838647882, 0.06761633027051639, 0.22324568672294431], [0.21930503925136402, 0.06746578636294004, 0.22451023616807558], [0.22247308588973624, 0.06738821405309284, 0.22585960379408354], [0.2257539681670791, 0.06738213230014747, 0.22728984778098055], [0.2291562027859284, 0.06743473087115257, 0.22879681433956656], [0.23266299920501882, 0.06755710438847978, 0.23037617493752832], [0.23627495835774248, 0.06774359820987802, 0.23202360805926608], [0.23999586188690308, 0.06798502996477995, 0.23373434258507808], [0.2438114972024792, 0.06828985152901187, 0.23550427698321885], [0.247720929905011, 0.06865333790948652, 0.2373288009471749], [0.25172899728289466, 0.0690646308260355, 0.23920260612763083], [0.2558213554748177, 0.06953231029187984, 0.24112190491594204], [0.25999463887892144, 0.07005385560386188, 0.24308218808684579], [0.2642551220706094, 0.07061659562299544, 0.24507758869355967], [0.2685909594817286, 0.07122671627792246, 0.24710443563450618], [0.272997015188973, 0.07188355544616351, 0.2491584709323293], [0.277471508091428, 0.07258296989925478, 0.2512349399594277], [0.2820174629736694, 0.07331569321404097, 0.25332800295084507], [0.28662309235899847, 0.07408846082680887, 0.2554347867371703], [0.29128515387578635, 0.0748990498474667, 0.25755101595750435], [0.2960004726065818, 0.07574533600095842, 0.25967245030364566], [0.3007727681291869, 0.07661782433616476, 0.2617929409781967], [0.30559226007249934, 0.07752196310753731, 0.2639100669211966], [0.31045520848595526, 0.07845687167618218, 0.2660200572779356], [0.3153587000920581, 0.07942099731524319, 0.2681190407694196], [0.3202998655799406, 0.08041299473755484, 0.2702032289303951], [0.3252788886040126, 0.08142839007654609, 0.27226772884656186], [0.3302917447118144, 0.08246763389003825, 0.27430929404579435], [0.3353335322445545, 0.08353243411900396, 0.2763253435679004], [0.34040164359597463, 0.08462223619170267, 0.27831254595259397], [0.345493557138718, 0.08573665496512634, 0.28026769921081435], [0.3506067824603248, 0.08687555176033529, 0.28218770540182386], [0.35573889947341125, 0.08803897435024335, 0.2840695897279818], [0.36088752387578377, 0.0892271943627452, 0.28591050458531014], [0.36605031412464006, 0.0904406854276979, 0.2877077458811747], [0.3712250843130934, 0.09167999748026273, 0.2894586539763317], [0.3764103053221462, 0.09294519809377791, 0.2911602415731392], [0.38160247377467543, 0.09423873126371218, 0.2928110750626949], [0.3867993907954417, 0.09556181960083443, 0.29440901248173756], [0.39199887556812907, 0.09691583650296684, 0.2959521200550908], [0.39719876876325577, 0.09830232096827862, 0.2974385647628578], [0.40239692379737496, 0.09972293031495055, 0.2988667436973397], [0.4075912039268871, 0.10117945586419633, 0.300235195077286], [0.41277985630360303, 0.1026734006932461, 0.3015422643746897], [0.41796105205173684, 0.10420644885760968, 0.3027865203963184], [0.42313214269556043, 0.10578120994917611, 0.3039675809469457], [0.4282910131578975, 0.1073997763055258, 0.30508479060294547], [0.4334355841041439, 0.1090642347484701, 0.3061376792828915], [0.4385637818793154, 0.11077667828375456, 0.30712600062348083], [0.44367358645071275, 0.11253912421257944, 0.3080497309546545], [0.4487629917317482, 0.1143535557462255, 0.30890905921943196], [0.4538300508699989, 0.11622183788331528, 0.3097044124984492], [0.45887288947308297, 0.11814571137706886, 0.3104363697903881], [0.46389102840284874, 0.12012561256850712, 0.31110343446582983], [0.46888111384598413, 0.12216445576414045, 0.31170911458932665], [0.473841437035254, 0.12426354237989065, 0.31225470169927194], [0.47877034239726296, 0.12642401401409453, 0.3127417273582196], [0.48366628618847957, 0.1286467902201389, 0.31317188565991266], [0.48852847371852987, 0.13093210934893723, 0.31354553695453014], [0.49335504375145617, 0.13328091630401023, 0.31386561956734976], [0.4981443546207415, 0.13569380302451714, 0.314135190862664], [0.5028952497497061, 0.13817086581280427, 0.3143566215383367], [0.5076068118105369, 0.14071192654913128, 0.3145320012008257], [0.5122783510532176, 0.14331656120063752, 0.3146630922831542], [0.5169084880054446, 0.14598463068714407, 0.3147540759228004], [0.5214965286322996, 0.14871544765633712, 0.3148076795453443], [0.5260418962547748, 0.15150818660835483, 0.31482653406646727], [0.5305442048985645, 0.15436183633886777, 0.3148129978918713], [0.5350027976174474, 0.15727540775107324, 0.3147708520739653], [0.5394173664919906, 0.16024769309971934, 0.31470295028655965], [0.5437877131360856, 0.16327738551419116, 0.31461204226295625], [0.5481137003346762, 0.1663630904279047, 0.3145010299091471], [0.5523952157271191, 0.16950338809328983, 0.3143729155461537], [0.5566322903496934, 0.17269677158182117, 0.31423043195101424], [0.5608249903911717, 0.17594170887918095, 0.31407639883970623], [0.564973435290177, 0.17923664950367169, 0.3139136046337036], [0.5690778478401143, 0.18258004462335425, 0.3137444095679653], [0.5731384575410787, 0.18597036007065024, 0.3135712686852], [0.5771555081299204, 0.18940601489760422, 0.3133970433357208], [0.5811293276158656, 0.19288548904692518, 0.3132239939418394], [0.5850602439646688, 0.19640737049066315, 0.3130540116373273], [0.5889486193554471, 0.19997020971775276, 0.31288922211590126], [0.5927948053652026, 0.20357251410079796, 0.3127323483930494], [0.5965991810912237, 0.207212956082026, 0.3125852303112123], [0.6003621301041158, 0.21089030138947745, 0.3124493441041469], [0.6040840169673274, 0.21460331490206347, 0.31232652641170694], [0.6077652399481865, 0.21835070166659282, 0.312219032918702], [0.6114062072731884, 0.22213124697023234, 0.3121288139643524], [0.6150072323639137, 0.22594402043981826, 0.3120568068576574], [0.6185686525887719, 0.2297879924917992, 0.3120046383872893], [0.6220907982108261, 0.2336621873300741, 0.3119738327362739], [0.6255741650043496, 0.23756535071152696, 0.3119669831491227], [0.6290189201698587, 0.24149689191922535, 0.3119844719564572], [0.6324253485421027, 0.24545598775548677, 0.3120276597462445], [0.6357937104834237, 0.24944185818822678, 0.3120979395330059], [0.6391243387840212, 0.2534536546198314, 0.3121968961206398], [0.642417577481186, 0.257490519876798, 0.31232631707560987], [0.6456734938264543, 0.2615520316161528, 0.31248673753935263], [0.6488923016945825, 0.2656375533620908, 0.3126794181957019], [0.652074172902773, 0.269746505252367, 0.3129056060581917], [0.6552193260932713, 0.2738782665241015, 0.3131666792687211], [0.6583280801134499, 0.2780321095766563, 0.3134643447952643], [0.6614003753260178, 0.28220778870555907, 0.3137991292649849], [0.6644363246987884, 0.2864048361425618, 0.31417223403606975], [0.6674360376636913, 0.29062280081258873, 0.31458483752056837], [0.670399595476762, 0.29486126309253047, 0.3150381395687221], [0.6733272556481733, 0.29911962764489264, 0.3155337232398221], [0.6762189792440975, 0.30339762792450425, 0.3160724937230589], [0.6790747402815734, 0.30769497879760166, 0.31665545668946665], [0.6818945715094452, 0.31201133280550686, 0.3172838048924495], [0.6846785094249453, 0.3163463482122221, 0.31795870784057567], [0.6874265643516962, 0.32069970535138104, 0.3186813762227769], [0.6901389321505248, 0.32507091815606004, 0.319453323328983], [0.6928154484676493, 0.32945984647042675, 0.3202754315314667], [0.6954560834689112, 0.33386622163232865, 0.3211488430698579], [0.6980608153581771, 0.3382897632604862, 0.3220747885521809], [0.700629624772421, 0.34273019305341756, 0.32305449047765694], [0.7031624945881415, 0.34718723719598, 0.32408913679491225], [0.7056595112261009, 0.3516605297812094, 0.32518014084085567], [0.7081205956842048, 0.356149855233803, 0.32632861885644465], [0.7105456546582587, 0.36065500290840113, 0.3275357416278876], [0.7129346683977347, 0.36517570519856757, 0.3288027427038317], [0.7152876061484729, 0.3697117022522345, 0.3301308728723546], [0.7176044490813385, 0.3742627271068619, 0.3315213862095893], [0.7198852149054985, 0.37882848839337313, 0.332975552002454], [0.7221299918421461, 0.3834086450896306, 0.33449469983585844], [0.7243386564778159, 0.38800301593162145, 0.3360799596569183], [0.7265112290022755, 0.3926113126792577, 0.3377325942005665], [0.7286477385671655, 0.39723324476747235, 0.33945384341064017], [0.7307482075484517, 0.401868526884681, 0.3412449533046818], [0.7328127050626875, 0.4065168468778026, 0.3431071517341082], [0.7348413359856494, 0.4111778700451951, 0.3450416947080907], [0.7368342217358587, 0.4158512585029011, 0.347049785207584], [0.7387914002459927, 0.4205367299231533, 0.34913260148542435], [0.7407130161950609, 0.4252339389526239, 0.35129130890802607], [0.7425992159973317, 0.42994254036133867, 0.3535270924537459], [0.7444501867657067, 0.4346621718461711, 0.35584108091122535], [0.7462661578916344, 0.439392450449735, 0.3582343914230064], [0.7480473927555956, 0.44413297780351974, 0.36070813602540136], [0.7497942054717047, 0.4488833348154881, 0.3632633755836028], [0.7515068504589166, 0.45364314496866825, 0.36590112443835765], [0.7531856636904657, 0.45841199172949604, 0.3686223664223477], [0.7548310506695954, 0.46318942799460555, 0.3714280448394211], [0.7564434157714071, 0.4679750143794846, 0.37431909037543515], [0.7580232553845584, 0.4727682731566229, 0.3772963553109668], [0.7595711110534006, 0.4775687122205708, 0.380360657784311], [0.7610876378057071, 0.48237579130289127, 0.3835127572385229], [0.7625733355405261, 0.48718906673415824, 0.38675335037837993], [0.7640288560928866, 0.49200802533379656, 0.39008308392311997], [0.7654549259333051, 0.4968321290972723, 0.3935025400011538], [0.7668522895064389, 0.5016608471009063, 0.39701221751773474], [0.768221765997353, 0.5064936237128791, 0.40061257089416885], [0.7695642334401418, 0.5113298901696085, 0.4043039806968248], [0.7708809196230247, 0.516168926434691, 0.40808667584648967], [0.7721725722960555, 0.5210102658711383, 0.4119608998712287], [0.7734402182988989, 0.5258533209345156, 0.41592679539764366], [0.774684947460632, 0.5306974938477673, 0.4199844035696376], [0.775907907306857, 0.5355421788246119, 0.42413367909988375], [0.7771103295521099, 0.5403867491056124, 0.4283745037125848], [0.7782934580763312, 0.545230594884266, 0.432706647838971], [0.7794586273150664, 0.5500730841397727, 0.4371297985644476], [0.7806077474948377, 0.5549133574489061, 0.4416433242636464], [0.7817418047898184, 0.5597509805259486, 0.44624687186865436], [0.7828622526444091, 0.5645853311116688, 0.45093985823706345], [0.7839706083641448, 0.5694157832671042, 0.4557215474289206], [0.7850684501960684, 0.5742417003617839, 0.46059116206904965], [0.7861573713233296, 0.5790624629815756, 0.465547782819184], [0.7872390410818835, 0.5838774374455721, 0.47059039582133383], [0.7883151404562396, 0.5886860017356244, 0.4757179187907608], [0.7893873776625194, 0.5934875421745599, 0.48092913815357724], [0.7904577684772788, 0.5982813427706246, 0.48622257801969754], [0.7915283284347561, 0.603066705931472, 0.49159667021646397], [0.7926003430423745, 0.6078432208703702, 0.4970502062153201], [0.7936755969866496, 0.6126102933407219, 0.5025816129126943], [0.7947558597265404, 0.617367344002207, 0.5081892121310299], [0.7958429237958377, 0.6221137880845115, 0.5138712409190979], [0.7969385471995161, 0.626849056792967, 0.5196258425240281], [0.7980444781513664, 0.6315725822508955, 0.5254510814483478], [0.7991624518501963, 0.6362837937202919, 0.5313449594256143], [0.8002941538975398, 0.6409821330674986, 0.5373053518514104], [0.8014412429256005, 0.6456670345921877, 0.5433300863249918], [0.8026053114611295, 0.6503379374810385, 0.5494169158460365], [0.8037879253107763, 0.6549942654947263, 0.5555635086708381], [0.804990547908103, 0.6596354502756416, 0.5617674511054698], [0.8062146052692706, 0.6642608958528229, 0.5680262917864979], [0.8074614045096935, 0.6688700095398864, 0.5743374637345958], [0.8087321917008969, 0.6734621670219452, 0.5806983480557674], [0.8100280946652069, 0.6780367267397182, 0.5871062690808275], [0.8113501401176333, 0.6825930154624339, 0.5935584890905076], [0.8126992203988149, 0.6871303371461888, 0.600052148204351], [0.8140761104699334, 0.6916479479148213, 0.6065843782630862], [0.8154814662727948, 0.6961450550830809, 0.6131522120932265], [0.8169157577505589, 0.7006208301478398, 0.6197526063725792], [0.8183793116449822, 0.705074381896351, 0.626382454789333], [0.8198723065045529, 0.7095047497878748, 0.6330385704006711], [0.8213947205565636, 0.7139109141951604, 0.6397176669767276], [0.8229463511042843, 0.7182917733129006, 0.6464164243818421], [0.8245268129450285, 0.7226461431208888, 0.653131379154226], [0.8261354971058026, 0.7269727551823826, 0.659859001562165], [0.8277716072353446, 0.7312702332407809, 0.6665957020468297], [0.8294340781648147, 0.7355371221572935, 0.6733377200930191], [0.8311216352909631, 0.7397718464763862, 0.6800812520363146], [0.8328327718577798, 0.7439727181745988, 0.6868223587464855], [0.8345656905566583, 0.7481379479992134, 0.6935569764986385], [0.8363189884473793, 0.7522654895287526, 0.7002799902886496], [0.8380912347613196, 0.7563531486080863, 0.7069856139021298], [0.8398783988412087, 0.7603990719977968, 0.7136714781112923], [0.8416775076684515, 0.7644010120098295, 0.7203329938728462], [0.843485292229337, 0.7683566039987018, 0.7269653699897204], [0.8452981073195511, 0.7722633860104472, 0.7335636824054149], [0.847111955079651, 0.7761188023604716, 0.7401227576280706], [0.8489224556311764, 0.7799202140765015, 0.7466371929366437], [0.8507269702317879, 0.7836645734238389, 0.7530974636118285], [0.8525190720770844, 0.7873493613354844, 0.7594994148789691], [0.8542921961147046, 0.7909719677709199, 0.765838014779141], [0.856040223147254, 0.7945296360155061, 0.7721061003767414], [0.857756629435049, 0.7980196314271393, 0.778295716672475], [0.8594346370300241, 0.8014392309950078, 0.7843978875138392], [0.8610711702756552, 0.8047851790981223, 0.7903952966373629], [0.8626560105112757, 0.8080552380426153, 0.796282666437655], [0.8641834372394103, 0.8112464422465354, 0.8020461269686395], [0.8656493432560532, 0.8143554406751491, 0.8076697232416455], [0.867053149070485, 0.8173780404191124, 0.813134196269114], [0.8683995469581863, 0.8203087551218152, 0.8184163896312899], [0.8696913150261381, 0.8231415885956916, 0.8235047668317317], [0.8709384671729751, 0.8258685788943851, 0.8283849726114961], [0.8721533197845432, 0.8284805282370967, 0.8330486712880828], [0.8733517136091627, 0.8309671525127262, 0.8374885100119709], [0.8745379332026019, 0.8333197294864546, 0.8417192535806901], [0.875714587099614, 0.8355302318472394, 0.8457553751902708], [0.8768784845161469, 0.8375923807118654, 0.8496137354915025], [0.8780229843664901, 0.8395016561854007, 0.8533064535245892], [0.8791324424079277, 0.8412555488447591, 0.8568557229103964], [0.8801929331569581, 0.8428522482477862, 0.8602739992715663], [0.8811916987134195, 0.8442906671771735, 0.8635659516866988], [0.8821154248940161, 0.8455700725455935, 0.8667376504623333], [0.8829516859544853, 0.8466897027569927, 0.8697961704819097], [0.8836912714589804, 0.8476489176151927, 0.8727414710144156], [0.8843271305411354, 0.8484474157205542, 0.8755678522824297], [0.8848513815990857, 0.849084264228938, 0.8782823528537247], [0.8852589797263047, 0.8495589281098921, 0.8808841479402484], [0.8855471481195238, 0.8498717428363158, 0.8833620612117095], [0.8857115512284565, 0.8500218611585632, 0.8857253899008712]] _twilight_shifted_data = _twilight_data[len(_twilight_data) // 2:] + _twilight_data[:len(_twilight_data) // 2] _twilight_shifted_data.reverse() _turbo_data = [[0.18995, 0.07176, 0.23217], [0.19483, 0.08339, 0.26149], [0.19956, 0.09498, 0.29024], [0.20415, 0.10652, 0.31844], [0.2086, 0.11802, 0.34607], [0.21291, 0.12947, 0.37314], [0.21708, 0.14087, 0.39964], [0.22111, 0.15223, 0.42558], [0.225, 0.16354, 0.45096], [0.22875, 0.17481, 0.47578], [0.23236, 0.18603, 0.50004], [0.23582, 0.1972, 0.52373], [0.23915, 0.20833, 0.54686], [0.24234, 0.21941, 0.56942], [0.24539, 0.23044, 0.59142], [0.2483, 0.24143, 0.61286], [0.25107, 0.25237, 0.63374], [0.25369, 0.26327, 0.65406], [0.25618, 0.27412, 0.67381], [0.25853, 0.28492, 0.693], [0.26074, 0.29568, 0.71162], [0.2628, 0.30639, 0.72968], [0.26473, 0.31706, 0.74718], [0.26652, 0.32768, 0.76412], [0.26816, 0.33825, 0.7805], [0.26967, 0.34878, 0.79631], [0.27103, 0.35926, 0.81156], [0.27226, 0.3697, 0.82624], [0.27334, 0.38008, 0.84037], [0.27429, 0.39043, 0.85393], [0.27509, 0.40072, 0.86692], [0.27576, 0.41097, 0.87936], [0.27628, 0.42118, 0.89123], [0.27667, 0.43134, 0.90254], [0.27691, 0.44145, 0.91328], [0.27701, 0.45152, 0.92347], [0.27698, 0.46153, 0.93309], [0.2768, 0.47151, 0.94214], [0.27648, 0.48144, 0.95064], [0.27603, 0.49132, 0.95857], [0.27543, 0.50115, 0.96594], [0.27469, 0.51094, 0.97275], [0.27381, 0.52069, 0.97899], [0.27273, 0.5304, 0.98461], [0.27106, 0.54015, 0.9893], [0.26878, 0.54995, 0.99303], [0.26592, 0.55979, 0.99583], [0.26252, 0.56967, 0.99773], [0.25862, 0.57958, 0.99876], [0.25425, 0.5895, 0.99896], [0.24946, 0.59943, 0.99835], [0.24427, 0.60937, 0.99697], [0.23874, 0.61931, 0.99485], [0.23288, 0.62923, 0.99202], [0.22676, 0.63913, 0.98851], [0.22039, 0.64901, 0.98436], [0.21382, 0.65886, 0.97959], [0.20708, 0.66866, 0.97423], [0.20021, 0.67842, 0.96833], [0.19326, 0.68812, 0.9619], [0.18625, 0.69775, 0.95498], [0.17923, 0.70732, 0.94761], [0.17223, 0.7168, 0.93981], [0.16529, 0.7262, 0.93161], [0.15844, 0.73551, 0.92305], [0.15173, 0.74472, 0.91416], [0.14519, 0.75381, 0.90496], [0.13886, 0.76279, 0.8955], [0.13278, 0.77165, 0.8858], [0.12698, 0.78037, 0.8759], [0.12151, 0.78896, 0.86581], [0.11639, 0.7974, 0.85559], [0.11167, 0.80569, 0.84525], [0.10738, 0.81381, 0.83484], [0.10357, 0.82177, 0.82437], [0.10026, 0.82955, 0.81389], [0.0975, 0.83714, 0.80342], [0.09532, 0.84455, 0.79299], [0.09377, 0.85175, 0.78264], [0.09287, 0.85875, 0.7724], [0.09267, 0.86554, 0.7623], [0.0932, 0.87211, 0.75237], [0.09451, 0.87844, 0.74265], [0.09662, 0.88454, 0.73316], [0.09958, 0.8904, 0.72393], [0.10342, 0.896, 0.715], [0.10815, 0.90142, 0.70599], [0.11374, 0.90673, 0.69651], [0.12014, 0.91193, 0.6866], [0.12733, 0.91701, 0.67627], [0.13526, 0.92197, 0.66556], [0.14391, 0.9268, 0.65448], [0.15323, 0.93151, 0.64308], [0.16319, 0.93609, 0.63137], [0.17377, 0.94053, 0.61938], [0.18491, 0.94484, 0.60713], [0.19659, 0.94901, 0.59466], [0.20877, 0.95304, 0.58199], [0.22142, 0.95692, 0.56914], [0.23449, 0.96065, 0.55614], [0.24797, 0.96423, 0.54303], [0.2618, 0.96765, 0.52981], [0.27597, 0.97092, 0.51653], [0.29042, 0.97403, 0.50321], [0.30513, 0.97697, 0.48987], [0.32006, 0.97974, 0.47654], [0.33517, 0.98234, 0.46325], [0.35043, 0.98477, 0.45002], [0.36581, 0.98702, 0.43688], [0.38127, 0.98909, 0.42386], [0.39678, 0.99098, 0.41098], [0.41229, 0.99268, 0.39826], [0.42778, 0.99419, 0.38575], [0.44321, 0.99551, 0.37345], [0.45854, 0.99663, 0.3614], [0.47375, 0.99755, 0.34963], [0.48879, 0.99828, 0.33816], [0.50362, 0.99879, 0.32701], [0.51822, 0.9991, 0.31622], [0.53255, 0.99919, 0.30581], [0.54658, 0.99907, 0.29581], [0.56026, 0.99873, 0.28623], [0.57357, 0.99817, 0.27712], [0.58646, 0.99739, 0.26849], [0.59891, 0.99638, 0.26038], [0.61088, 0.99514, 0.2528], [0.62233, 0.99366, 0.24579], [0.63323, 0.99195, 0.23937], [0.64362, 0.98999, 0.23356], [0.65394, 0.98775, 0.22835], [0.66428, 0.98524, 0.2237], [0.67462, 0.98246, 0.2196], [0.68494, 0.97941, 0.21602], [0.69525, 0.9761, 0.21294], [0.70553, 0.97255, 0.21032], [0.71577, 0.96875, 0.20815], [0.72596, 0.9647, 0.2064], [0.7361, 0.96043, 0.20504], [0.74617, 0.95593, 0.20406], [0.75617, 0.95121, 0.20343], [0.76608, 0.94627, 0.20311], [0.77591, 0.94113, 0.2031], [0.78563, 0.93579, 0.20336], [0.79524, 0.93025, 0.20386], [0.80473, 0.92452, 0.20459], [0.8141, 0.91861, 0.20552], [0.82333, 0.91253, 0.20663], [0.83241, 0.90627, 0.20788], [0.84133, 0.89986, 0.20926], [0.8501, 0.89328, 0.21074], [0.85868, 0.88655, 0.2123], [0.86709, 0.87968, 0.21391], [0.8753, 0.87267, 0.21555], [0.88331, 0.86553, 0.21719], [0.89112, 0.85826, 0.2188], [0.8987, 0.85087, 0.22038], [0.90605, 0.84337, 0.22188], [0.91317, 0.83576, 0.22328], [0.92004, 0.82806, 0.22456], [0.92666, 0.82025, 0.2257], [0.93301, 0.81236, 0.22667], [0.93909, 0.80439, 0.22744], [0.94489, 0.79634, 0.228], [0.95039, 0.78823, 0.22831], [0.9556, 0.78005, 0.22836], [0.96049, 0.77181, 0.22811], [0.96507, 0.76352, 0.22754], [0.96931, 0.75519, 0.22663], [0.97323, 0.74682, 0.22536], [0.97679, 0.73842, 0.22369], [0.98, 0.73, 0.22161], [0.98289, 0.7214, 0.21918], [0.98549, 0.7125, 0.2165], [0.98781, 0.7033, 0.21358], [0.98986, 0.69382, 0.21043], [0.99163, 0.68408, 0.20706], [0.99314, 0.67408, 0.20348], [0.99438, 0.66386, 0.19971], [0.99535, 0.65341, 0.19577], [0.99607, 0.64277, 0.19165], [0.99654, 0.63193, 0.18738], [0.99675, 0.62093, 0.18297], [0.99672, 0.60977, 0.17842], [0.99644, 0.59846, 0.17376], [0.99593, 0.58703, 0.16899], [0.99517, 0.57549, 0.16412], [0.99419, 0.56386, 0.15918], [0.99297, 0.55214, 0.15417], [0.99153, 0.54036, 0.1491], [0.98987, 0.52854, 0.14398], [0.98799, 0.51667, 0.13883], [0.9859, 0.50479, 0.13367], [0.9836, 0.49291, 0.12849], [0.98108, 0.48104, 0.12332], [0.97837, 0.4692, 0.11817], [0.97545, 0.4574, 0.11305], [0.97234, 0.44565, 0.10797], [0.96904, 0.43399, 0.10294], [0.96555, 0.42241, 0.09798], [0.96187, 0.41093, 0.0931], [0.95801, 0.39958, 0.08831], [0.95398, 0.38836, 0.08362], [0.94977, 0.37729, 0.07905], [0.94538, 0.36638, 0.07461], [0.94084, 0.35566, 0.07031], [0.93612, 0.34513, 0.06616], [0.93125, 0.33482, 0.06218], [0.92623, 0.32473, 0.05837], [0.92105, 0.31489, 0.05475], [0.91572, 0.3053, 0.05134], [0.91024, 0.29599, 0.04814], [0.90463, 0.28696, 0.04516], [0.89888, 0.27824, 0.04243], [0.89298, 0.26981, 0.03993], [0.88691, 0.26152, 0.03753], [0.88066, 0.25334, 0.03521], [0.87422, 0.24526, 0.03297], [0.8676, 0.2373, 0.03082], [0.86079, 0.22945, 0.02875], [0.8538, 0.2217, 0.02677], [0.84662, 0.21407, 0.02487], [0.83926, 0.20654, 0.02305], [0.83172, 0.19912, 0.02131], [0.82399, 0.19182, 0.01966], [0.81608, 0.18462, 0.01809], [0.80799, 0.17753, 0.0166], [0.79971, 0.17055, 0.0152], [0.79125, 0.16368, 0.01387], [0.7826, 0.15693, 0.01264], [0.77377, 0.15028, 0.01148], [0.76476, 0.14374, 0.01041], [0.75556, 0.13731, 0.00942], [0.74617, 0.13098, 0.00851], [0.73661, 0.12477, 0.00769], [0.72686, 0.11867, 0.00695], [0.71692, 0.11268, 0.00629], [0.7068, 0.1068, 0.00571], [0.6965, 0.10102, 0.00522], [0.68602, 0.09536, 0.00481], [0.67535, 0.0898, 0.00449], [0.66449, 0.08436, 0.00424], [0.65345, 0.07902, 0.00408], [0.64223, 0.0738, 0.00401], [0.63082, 0.06868, 0.00401], [0.61923, 0.06367, 0.0041], [0.60746, 0.05878, 0.00427], [0.5955, 0.05399, 0.00453], [0.58336, 0.04931, 0.00486], [0.57103, 0.04474, 0.00529], [0.55852, 0.04028, 0.00579], [0.54583, 0.03593, 0.00638], [0.53295, 0.03169, 0.00705], [0.51989, 0.02756, 0.0078], [0.50664, 0.02354, 0.00863], [0.49321, 0.01963, 0.00955], [0.4796, 0.01583, 0.01055]] _berlin_data = [[0.62108, 0.69018, 0.99951], [0.61216, 0.68923, 0.99537], [0.6032, 0.68825, 0.99124], [0.5942, 0.68726, 0.98709], [0.58517, 0.68625, 0.98292], [0.57609, 0.68522, 0.97873], [0.56696, 0.68417, 0.97452], [0.55779, 0.6831, 0.97029], [0.54859, 0.68199, 0.96602], [0.53933, 0.68086, 0.9617], [0.53003, 0.67969, 0.95735], [0.52069, 0.67848, 0.95294], [0.51129, 0.67723, 0.94847], [0.50186, 0.67591, 0.94392], [0.49237, 0.67453, 0.9393], [0.48283, 0.67308, 0.93457], [0.47324, 0.67153, 0.92975], [0.46361, 0.6699, 0.92481], [0.45393, 0.66815, 0.91974], [0.44421, 0.66628, 0.91452], [0.43444, 0.66427, 0.90914], [0.42465, 0.66212, 0.90359], [0.41482, 0.65979, 0.89785], [0.40498, 0.65729, 0.89191], [0.39514, 0.65458, 0.88575], [0.3853, 0.65167, 0.87937], [0.37549, 0.64854, 0.87276], [0.36574, 0.64516, 0.8659], [0.35606, 0.64155, 0.8588], [0.34645, 0.63769, 0.85145], [0.33698, 0.63357, 0.84386], [0.32764, 0.62919, 0.83602], [0.31849, 0.62455, 0.82794], [0.30954, 0.61966, 0.81963], [0.30078, 0.6145, 0.81111], [0.29231, 0.60911, 0.80238], [0.2841, 0.60348, 0.79347], [0.27621, 0.59763, 0.78439], [0.26859, 0.59158, 0.77514], [0.26131, 0.58534, 0.76578], [0.25437, 0.57891, 0.7563], [0.24775, 0.57233, 0.74672], [0.24146, 0.5656, 0.73707], [0.23552, 0.55875, 0.72735], [0.22984, 0.5518, 0.7176], [0.2245, 0.54475, 0.7078], [0.21948, 0.53763, 0.698], [0.21469, 0.53043, 0.68819], [0.21017, 0.52319, 0.67838], [0.20589, 0.5159, 0.66858], [0.20177, 0.5086, 0.65879], [0.19788, 0.50126, 0.64903], [0.19417, 0.4939, 0.63929], [0.19056, 0.48654, 0.62957], [0.18711, 0.47918, 0.6199], [0.18375, 0.47183, 0.61024], [0.1805, 0.46447, 0.60062], [0.17737, 0.45712, 0.59104], [0.17426, 0.44979, 0.58148], [0.17122, 0.44247, 0.57197], [0.16824, 0.43517, 0.56249], [0.16529, 0.42788, 0.55302], [0.16244, 0.42061, 0.5436], [0.15954, 0.41337, 0.53421], [0.15674, 0.40615, 0.52486], [0.15391, 0.39893, 0.51552], [0.15112, 0.39176, 0.50623], [0.14835, 0.38459, 0.49697], [0.14564, 0.37746, 0.48775], [0.14288, 0.37034, 0.47854], [0.14014, 0.36326, 0.46939], [0.13747, 0.3562, 0.46024], [0.13478, 0.34916, 0.45115], [0.13208, 0.34215, 0.44209], [0.1294, 0.33517, 0.43304], [0.12674, 0.3282, 0.42404], [0.12409, 0.32126, 0.41507], [0.12146, 0.31435, 0.40614], [0.1189, 0.30746, 0.39723], [0.11632, 0.30061, 0.38838], [0.11373, 0.29378, 0.37955], [0.11119, 0.28698, 0.37075], [0.10861, 0.28022, 0.362], [0.10616, 0.2735, 0.35328], [0.10367, 0.26678, 0.34459], [0.10118, 0.26011, 0.33595], [0.098776, 0.25347, 0.32734], [0.096347, 0.24685, 0.31878], [0.094059, 0.24026, 0.31027], [0.091788, 0.23373, 0.30176], [0.089506, 0.22725, 0.29332], [0.087341, 0.2208, 0.28491], [0.085142, 0.21436, 0.27658], [0.083069, 0.20798, 0.26825], [0.081098, 0.20163, 0.25999], [0.07913, 0.19536, 0.25178], [0.077286, 0.18914, 0.24359], [0.075571, 0.18294, 0.2355], [0.073993, 0.17683, 0.22743], [0.07241, 0.17079, 0.21943], [0.071045, 0.1648, 0.2115], [0.069767, 0.1589, 0.20363], [0.068618, 0.15304, 0.19582], [0.06756, 0.14732, 0.18812], [0.066665, 0.14167, 0.18045], [0.065923, 0.13608, 0.17292], [0.065339, 0.1307, 0.16546], [0.064911, 0.12535, 0.15817], [0.064636, 0.12013, 0.15095], [0.064517, 0.11507, 0.14389], [0.064554, 0.11022, 0.13696], [0.064749, 0.10543, 0.13023], [0.0651, 0.10085, 0.12357], [0.065383, 0.096469, 0.11717], [0.065574, 0.092338, 0.11101], [0.065892, 0.088201, 0.10498], [0.066388, 0.084134, 0.099288], [0.067108, 0.080051, 0.093829], [0.068193, 0.076099, 0.08847], [0.06972, 0.072283, 0.083025], [0.071639, 0.068654, 0.077544], [0.073978, 0.065058, 0.07211], [0.076596, 0.061657, 0.066651], [0.079637, 0.05855, 0.061133], [0.082963, 0.055666, 0.055745], [0.086537, 0.052997, 0.050336], [0.090315, 0.050699, 0.04504], [0.09426, 0.048753, 0.039773], [0.098319, 0.047041, 0.034683], [0.10246, 0.045624, 0.030074], [0.10673, 0.044705, 0.026012], [0.11099, 0.043972, 0.022379], [0.11524, 0.043596, 0.01915], [0.11955, 0.043567, 0.016299], [0.12381, 0.043861, 0.013797], [0.1281, 0.044459, 0.011588], [0.13232, 0.045229, 0.0095315], [0.13645, 0.046164, 0.0078947], [0.14063, 0.047374, 0.006502], [0.14488, 0.048634, 0.0053266], [0.14923, 0.049836, 0.0043455], [0.15369, 0.050997, 0.0035374], [0.15831, 0.05213, 0.0028824], [0.16301, 0.053218, 0.0023628], [0.16781, 0.05424, 0.0019629], [0.17274, 0.055172, 0.001669], [0.1778, 0.056018, 0.0014692], [0.18286, 0.05682, 0.0013401], [0.18806, 0.057574, 0.0012617], [0.19323, 0.058514, 0.0012261], [0.19846, 0.05955, 0.0012271], [0.20378, 0.060501, 0.0012601], [0.20909, 0.061486, 0.0013221], [0.21447, 0.06271, 0.0014116], [0.2199, 0.063823, 0.0015287], [0.22535, 0.065027, 0.0016748], [0.23086, 0.066297, 0.0018529], [0.23642, 0.067645, 0.0020675], [0.24202, 0.069092, 0.0023247], [0.24768, 0.070458, 0.0026319], [0.25339, 0.071986, 0.0029984], [0.25918, 0.07364, 0.003435], [0.265, 0.075237, 0.0039545], [0.27093, 0.076965, 0.004571], [0.27693, 0.078822, 0.0053006], [0.28302, 0.080819, 0.0061608], [0.2892, 0.082879, 0.0071713], [0.29547, 0.085075, 0.0083494], [0.30186, 0.08746, 0.0097258], [0.30839, 0.089912, 0.011455], [0.31502, 0.09253, 0.013324], [0.32181, 0.095392, 0.015413], [0.32874, 0.098396, 0.01778], [0.3358, 0.10158, 0.020449], [0.34304, 0.10498, 0.02344], [0.35041, 0.10864, 0.026771], [0.35795, 0.11256, 0.030456], [0.36563, 0.11666, 0.034571], [0.37347, 0.12097, 0.039115], [0.38146, 0.12561, 0.043693], [0.38958, 0.13046, 0.048471], [0.39785, 0.13547, 0.053136], [0.40622, 0.1408, 0.057848], [0.41469, 0.14627, 0.062715], [0.42323, 0.15198, 0.067685], [0.43184, 0.15791, 0.073044], [0.44044, 0.16403, 0.07862], [0.44909, 0.17027, 0.084644], [0.4577, 0.17667, 0.090869], [0.46631, 0.18321, 0.097335], [0.4749, 0.18989, 0.10406], [0.48342, 0.19668, 0.11104], [0.49191, 0.20352, 0.11819], [0.50032, 0.21043, 0.1255], [0.50869, 0.21742, 0.13298], [0.51698, 0.22443, 0.14062], [0.5252, 0.23154, 0.14835], [0.53335, 0.23862, 0.15626], [0.54144, 0.24575, 0.16423], [0.54948, 0.25292, 0.17226], [0.55746, 0.26009, 0.1804], [0.56538, 0.26726, 0.18864], [0.57327, 0.27446, 0.19692], [0.58111, 0.28167, 0.20524], [0.58892, 0.28889, 0.21362], [0.59672, 0.29611, 0.22205], [0.60448, 0.30335, 0.23053], [0.61223, 0.31062, 0.23905], [0.61998, 0.31787, 0.24762], [0.62771, 0.32513, 0.25619], [0.63544, 0.33244, 0.26481], [0.64317, 0.33975, 0.27349], [0.65092, 0.34706, 0.28218], [0.65866, 0.3544, 0.29089], [0.66642, 0.36175, 0.29964], [0.67419, 0.36912, 0.30842], [0.68198, 0.37652, 0.31722], [0.68978, 0.38392, 0.32604], [0.6976, 0.39135, 0.33493], [0.70543, 0.39879, 0.3438], [0.71329, 0.40627, 0.35272], [0.72116, 0.41376, 0.36166], [0.72905, 0.42126, 0.37062], [0.73697, 0.4288, 0.37962], [0.7449, 0.43635, 0.38864], [0.75285, 0.44392, 0.39768], [0.76083, 0.45151, 0.40675], [0.76882, 0.45912, 0.41584], [0.77684, 0.46676, 0.42496], [0.78488, 0.47441, 0.43409], [0.79293, 0.48208, 0.44327], [0.80101, 0.48976, 0.45246], [0.80911, 0.49749, 0.46167], [0.81722, 0.50521, 0.47091], [0.82536, 0.51296, 0.48017], [0.83352, 0.52073, 0.48945], [0.84169, 0.52853, 0.49876], [0.84988, 0.53634, 0.5081], [0.85809, 0.54416, 0.51745], [0.86632, 0.55201, 0.52683], [0.87457, 0.55988, 0.53622], [0.88283, 0.56776, 0.54564], [0.89111, 0.57567, 0.55508], [0.89941, 0.58358, 0.56455], [0.90772, 0.59153, 0.57404], [0.91603, 0.59949, 0.58355], [0.92437, 0.60747, 0.59309], [0.93271, 0.61546, 0.60265], [0.94108, 0.62348, 0.61223], [0.94945, 0.63151, 0.62183], [0.95783, 0.63956, 0.63147], [0.96622, 0.64763, 0.64111], [0.97462, 0.65572, 0.65079], [0.98303, 0.66382, 0.66049], [0.99145, 0.67194, 0.67022], [0.99987, 0.68007, 0.67995]] _managua_data = [[1, 0.81263, 0.40424], [0.99516, 0.80455, 0.40155], [0.99024, 0.79649, 0.39888], [0.98532, 0.78848, 0.39622], [0.98041, 0.7805, 0.39356], [0.97551, 0.77257, 0.39093], [0.97062, 0.76468, 0.3883], [0.96573, 0.75684, 0.38568], [0.96087, 0.74904, 0.3831], [0.95601, 0.74129, 0.38052], [0.95116, 0.7336, 0.37795], [0.94631, 0.72595, 0.37539], [0.94149, 0.71835, 0.37286], [0.93667, 0.7108, 0.37034], [0.93186, 0.7033, 0.36784], [0.92706, 0.69585, 0.36536], [0.92228, 0.68845, 0.36289], [0.9175, 0.68109, 0.36042], [0.91273, 0.67379, 0.358], [0.90797, 0.66653, 0.35558], [0.90321, 0.65932, 0.35316], [0.89846, 0.65216, 0.35078], [0.89372, 0.64503, 0.34839], [0.88899, 0.63796, 0.34601], [0.88426, 0.63093, 0.34367], [0.87953, 0.62395, 0.34134], [0.87481, 0.617, 0.33902], [0.87009, 0.61009, 0.3367], [0.86538, 0.60323, 0.33442], [0.86067, 0.59641, 0.33213], [0.85597, 0.58963, 0.32987], [0.85125, 0.5829, 0.3276], [0.84655, 0.57621, 0.32536], [0.84185, 0.56954, 0.32315], [0.83714, 0.56294, 0.32094], [0.83243, 0.55635, 0.31874], [0.82772, 0.54983, 0.31656], [0.82301, 0.54333, 0.31438], [0.81829, 0.53688, 0.31222], [0.81357, 0.53046, 0.3101], [0.80886, 0.52408, 0.30796], [0.80413, 0.51775, 0.30587], [0.7994, 0.51145, 0.30375], [0.79466, 0.50519, 0.30167], [0.78991, 0.49898, 0.29962], [0.78516, 0.4928, 0.29757], [0.7804, 0.48668, 0.29553], [0.77564, 0.48058, 0.29351], [0.77086, 0.47454, 0.29153], [0.76608, 0.46853, 0.28954], [0.76128, 0.46255, 0.28756], [0.75647, 0.45663, 0.28561], [0.75166, 0.45075, 0.28369], [0.74682, 0.44491, 0.28178], [0.74197, 0.4391, 0.27988], [0.73711, 0.43333, 0.27801], [0.73223, 0.42762, 0.27616], [0.72732, 0.42192, 0.2743], [0.72239, 0.41628, 0.27247], [0.71746, 0.41067, 0.27069], [0.71247, 0.40508, 0.26891], [0.70747, 0.39952, 0.26712], [0.70244, 0.39401, 0.26538], [0.69737, 0.38852, 0.26367], [0.69227, 0.38306, 0.26194], [0.68712, 0.37761, 0.26025], [0.68193, 0.37219, 0.25857], [0.67671, 0.3668, 0.25692], [0.67143, 0.36142, 0.25529], [0.6661, 0.35607, 0.25367], [0.66071, 0.35073, 0.25208], [0.65528, 0.34539, 0.25049], [0.6498, 0.34009, 0.24895], [0.64425, 0.3348, 0.24742], [0.63866, 0.32953, 0.2459], [0.633, 0.32425, 0.24442], [0.62729, 0.31901, 0.24298], [0.62152, 0.3138, 0.24157], [0.6157, 0.3086, 0.24017], [0.60983, 0.30341, 0.23881], [0.60391, 0.29826, 0.23752], [0.59793, 0.29314, 0.23623], [0.59191, 0.28805, 0.235], [0.58585, 0.28302, 0.23377], [0.57974, 0.27799, 0.23263], [0.57359, 0.27302, 0.23155], [0.56741, 0.26808, 0.23047], [0.5612, 0.26321, 0.22948], [0.55496, 0.25837, 0.22857], [0.54871, 0.25361, 0.22769], [0.54243, 0.24891, 0.22689], [0.53614, 0.24424, 0.22616], [0.52984, 0.23968, 0.22548], [0.52354, 0.2352, 0.22487], [0.51724, 0.23076, 0.22436], [0.51094, 0.22643, 0.22395], [0.50467, 0.22217, 0.22363], [0.49841, 0.21802, 0.22339], [0.49217, 0.21397, 0.22325], [0.48595, 0.21, 0.22321], [0.47979, 0.20618, 0.22328], [0.47364, 0.20242, 0.22345], [0.46756, 0.1988, 0.22373], [0.46152, 0.19532, 0.22413], [0.45554, 0.19195, 0.22465], [0.44962, 0.18873, 0.22534], [0.44377, 0.18566, 0.22616], [0.43799, 0.18266, 0.22708], [0.43229, 0.17987, 0.22817], [0.42665, 0.17723, 0.22938], [0.42111, 0.17474, 0.23077], [0.41567, 0.17238, 0.23232], [0.41033, 0.17023, 0.23401], [0.40507, 0.16822, 0.2359], [0.39992, 0.1664, 0.23794], [0.39489, 0.16475, 0.24014], [0.38996, 0.16331, 0.24254], [0.38515, 0.16203, 0.24512], [0.38046, 0.16093, 0.24792], [0.37589, 0.16, 0.25087], [0.37143, 0.15932, 0.25403], [0.36711, 0.15883, 0.25738], [0.36292, 0.15853, 0.26092], [0.35885, 0.15843, 0.26466], [0.35494, 0.15853, 0.26862], [0.35114, 0.15882, 0.27276], [0.34748, 0.15931, 0.27711], [0.34394, 0.15999, 0.28164], [0.34056, 0.16094, 0.28636], [0.33731, 0.16207, 0.29131], [0.3342, 0.16338, 0.29642], [0.33121, 0.16486, 0.3017], [0.32837, 0.16658, 0.30719], [0.32565, 0.16847, 0.31284], [0.3231, 0.17056, 0.31867], [0.32066, 0.17283, 0.32465], [0.31834, 0.1753, 0.33079], [0.31616, 0.17797, 0.3371], [0.3141, 0.18074, 0.34354], [0.31216, 0.18373, 0.35011], [0.31038, 0.1869, 0.35682], [0.3087, 0.19021, 0.36363], [0.30712, 0.1937, 0.37056], [0.3057, 0.19732, 0.3776], [0.30435, 0.20106, 0.38473], [0.30314, 0.205, 0.39195], [0.30204, 0.20905, 0.39924], [0.30106, 0.21323, 0.40661], [0.30019, 0.21756, 0.41404], [0.29944, 0.22198, 0.42151], [0.29878, 0.22656, 0.42904], [0.29822, 0.23122, 0.4366], [0.29778, 0.23599, 0.44419], [0.29745, 0.24085, 0.45179], [0.29721, 0.24582, 0.45941], [0.29708, 0.2509, 0.46703], [0.29704, 0.25603, 0.47465], [0.2971, 0.26127, 0.48225], [0.29726, 0.26658, 0.48983], [0.2975, 0.27194, 0.4974], [0.29784, 0.27741, 0.50493], [0.29828, 0.28292, 0.51242], [0.29881, 0.28847, 0.51987], [0.29943, 0.29408, 0.52728], [0.30012, 0.29976, 0.53463], [0.3009, 0.30548, 0.54191], [0.30176, 0.31122, 0.54915], [0.30271, 0.317, 0.5563], [0.30373, 0.32283, 0.56339], [0.30483, 0.32866, 0.5704], [0.30601, 0.33454, 0.57733], [0.30722, 0.34042, 0.58418], [0.30853, 0.34631, 0.59095], [0.30989, 0.35224, 0.59763], [0.3113, 0.35817, 0.60423], [0.31277, 0.3641, 0.61073], [0.31431, 0.37005, 0.61715], [0.3159, 0.376, 0.62347], [0.31752, 0.38195, 0.62969], [0.3192, 0.3879, 0.63583], [0.32092, 0.39385, 0.64188], [0.32268, 0.39979, 0.64783], [0.32446, 0.40575, 0.6537], [0.3263, 0.41168, 0.65948], [0.32817, 0.41763, 0.66517], [0.33008, 0.42355, 0.67079], [0.33201, 0.4295, 0.67632], [0.33398, 0.43544, 0.68176], [0.33596, 0.44137, 0.68715], [0.33798, 0.44731, 0.69246], [0.34003, 0.45327, 0.69769], [0.3421, 0.45923, 0.70288], [0.34419, 0.4652, 0.70799], [0.34631, 0.4712, 0.71306], [0.34847, 0.4772, 0.71808], [0.35064, 0.48323, 0.72305], [0.35283, 0.48928, 0.72798], [0.35506, 0.49537, 0.73288], [0.3573, 0.50149, 0.73773], [0.35955, 0.50763, 0.74256], [0.36185, 0.51381, 0.74736], [0.36414, 0.52001, 0.75213], [0.36649, 0.52627, 0.75689], [0.36884, 0.53256, 0.76162], [0.37119, 0.53889, 0.76633], [0.37359, 0.54525, 0.77103], [0.376, 0.55166, 0.77571], [0.37842, 0.55809, 0.78037], [0.38087, 0.56458, 0.78503], [0.38333, 0.5711, 0.78966], [0.38579, 0.57766, 0.79429], [0.38828, 0.58426, 0.7989], [0.39078, 0.59088, 0.8035], [0.39329, 0.59755, 0.8081], [0.39582, 0.60426, 0.81268], [0.39835, 0.61099, 0.81725], [0.4009, 0.61774, 0.82182], [0.40344, 0.62454, 0.82637], [0.406, 0.63137, 0.83092], [0.40856, 0.63822, 0.83546], [0.41114, 0.6451, 0.83999], [0.41372, 0.65202, 0.84451], [0.41631, 0.65896, 0.84903], [0.4189, 0.66593, 0.85354], [0.42149, 0.67294, 0.85805], [0.4241, 0.67996, 0.86256], [0.42671, 0.68702, 0.86705], [0.42932, 0.69411, 0.87156], [0.43195, 0.70123, 0.87606], [0.43457, 0.70839, 0.88056], [0.4372, 0.71557, 0.88506], [0.43983, 0.72278, 0.88956], [0.44248, 0.73004, 0.89407], [0.44512, 0.73732, 0.89858], [0.44776, 0.74464, 0.9031], [0.45042, 0.752, 0.90763], [0.45308, 0.75939, 0.91216], [0.45574, 0.76682, 0.9167], [0.45841, 0.77429, 0.92124], [0.46109, 0.78181, 0.9258], [0.46377, 0.78936, 0.93036], [0.46645, 0.79694, 0.93494], [0.46914, 0.80458, 0.93952], [0.47183, 0.81224, 0.94412], [0.47453, 0.81995, 0.94872], [0.47721, 0.8277, 0.95334], [0.47992, 0.83549, 0.95796], [0.48261, 0.84331, 0.96259], [0.4853, 0.85117, 0.96722], [0.48801, 0.85906, 0.97186], [0.49071, 0.86699, 0.97651], [0.49339, 0.87495, 0.98116], [0.49607, 0.88294, 0.98581], [0.49877, 0.89096, 0.99047], [0.50144, 0.89901, 0.99512], [0.50411, 0.90708, 0.99978]] _vanimo_data = [[1, 0.80346, 0.99215], [0.99397, 0.79197, 0.98374], [0.98791, 0.78052, 0.97535], [0.98185, 0.7691, 0.96699], [0.97578, 0.75774, 0.95867], [0.96971, 0.74643, 0.95037], [0.96363, 0.73517, 0.94211], [0.95755, 0.72397, 0.93389], [0.95147, 0.71284, 0.9257], [0.94539, 0.70177, 0.91756], [0.93931, 0.69077, 0.90945], [0.93322, 0.67984, 0.90137], [0.92713, 0.66899, 0.89334], [0.92104, 0.65821, 0.88534], [0.91495, 0.64751, 0.87738], [0.90886, 0.63689, 0.86946], [0.90276, 0.62634, 0.86158], [0.89666, 0.61588, 0.85372], [0.89055, 0.60551, 0.84591], [0.88444, 0.59522, 0.83813], [0.87831, 0.58503, 0.83039], [0.87219, 0.57491, 0.82268], [0.86605, 0.5649, 0.815], [0.8599, 0.55499, 0.80736], [0.85373, 0.54517, 0.79974], [0.84756, 0.53544, 0.79216], [0.84138, 0.52583, 0.78461], [0.83517, 0.5163, 0.77709], [0.82896, 0.5069, 0.76959], [0.82272, 0.49761, 0.76212], [0.81647, 0.48841, 0.75469], [0.81018, 0.47934, 0.74728], [0.80389, 0.47038, 0.7399], [0.79757, 0.46154, 0.73255], [0.79123, 0.45283, 0.72522], [0.78487, 0.44424, 0.71792], [0.77847, 0.43578, 0.71064], [0.77206, 0.42745, 0.70339], [0.76562, 0.41925, 0.69617], [0.75914, 0.41118, 0.68897], [0.75264, 0.40327, 0.68179], [0.74612, 0.39549, 0.67465], [0.73957, 0.38783, 0.66752], [0.73297, 0.38034, 0.66041], [0.72634, 0.37297, 0.65331], [0.71967, 0.36575, 0.64623], [0.71293, 0.35864, 0.63915], [0.70615, 0.35166, 0.63206], [0.69929, 0.34481, 0.62496], [0.69236, 0.33804, 0.61782], [0.68532, 0.33137, 0.61064], [0.67817, 0.32479, 0.6034], [0.67091, 0.3183, 0.59609], [0.66351, 0.31184, 0.5887], [0.65598, 0.30549, 0.58123], [0.64828, 0.29917, 0.57366], [0.64045, 0.29289, 0.56599], [0.63245, 0.28667, 0.55822], [0.6243, 0.28051, 0.55035], [0.61598, 0.27442, 0.54237], [0.60752, 0.26838, 0.53428], [0.59889, 0.2624, 0.5261], [0.59012, 0.25648, 0.51782], [0.5812, 0.25063, 0.50944], [0.57214, 0.24483, 0.50097], [0.56294, 0.23914, 0.4924], [0.55359, 0.23348, 0.48376], [0.54413, 0.22795, 0.47505], [0.53454, 0.22245, 0.46623], [0.52483, 0.21706, 0.45736], [0.51501, 0.21174, 0.44843], [0.50508, 0.20651, 0.43942], [0.49507, 0.20131, 0.43036], [0.48495, 0.19628, 0.42125], [0.47476, 0.19128, 0.4121], [0.4645, 0.18639, 0.4029], [0.45415, 0.18157, 0.39367], [0.44376, 0.17688, 0.38441], [0.43331, 0.17225, 0.37513], [0.42282, 0.16773, 0.36585], [0.41232, 0.16332, 0.35655], [0.40178, 0.15897, 0.34726], [0.39125, 0.15471, 0.33796], [0.38071, 0.15058, 0.32869], [0.37017, 0.14651, 0.31945], [0.35969, 0.14258, 0.31025], [0.34923, 0.13872, 0.30106], [0.33883, 0.13499, 0.29196], [0.32849, 0.13133, 0.28293], [0.31824, 0.12778, 0.27396], [0.30808, 0.12431, 0.26508], [0.29805, 0.12097, 0.25631], [0.28815, 0.11778, 0.24768], [0.27841, 0.11462, 0.23916], [0.26885, 0.11169, 0.23079], [0.25946, 0.10877, 0.22259], [0.25025, 0.10605, 0.21455], [0.24131, 0.10341, 0.20673], [0.23258, 0.10086, 0.19905], [0.2241, 0.098494, 0.19163], [0.21593, 0.096182, 0.18443], [0.20799, 0.094098, 0.17748], [0.20032, 0.092102, 0.17072], [0.19299, 0.09021, 0.16425], [0.18596, 0.088461, 0.15799], [0.17918, 0.086861, 0.15197], [0.17272, 0.08531, 0.14623], [0.16658, 0.084017, 0.14075], [0.1607, 0.082745, 0.13546], [0.15515, 0.081683, 0.13049], [0.1499, 0.080653, 0.1257], [0.14493, 0.07978, 0.12112], [0.1402, 0.079037, 0.11685], [0.13578, 0.078426, 0.11282], [0.13168, 0.077944, 0.10894], [0.12782, 0.077586, 0.10529], [0.12422, 0.077332, 0.1019], [0.12091, 0.077161, 0.098724], [0.11793, 0.077088, 0.095739], [0.11512, 0.077124, 0.092921], [0.11267, 0.077278, 0.090344], [0.11042, 0.077557, 0.087858], [0.10835, 0.077968, 0.085431], [0.10665, 0.078516, 0.083233], [0.105, 0.079207, 0.081185], [0.10368, 0.080048, 0.079202], [0.10245, 0.081036, 0.077408], [0.10143, 0.082173, 0.075793], [0.1006, 0.083343, 0.074344], [0.099957, 0.084733, 0.073021], [0.099492, 0.086174, 0.071799], [0.099204, 0.087868, 0.070716], [0.099092, 0.089631, 0.069813], [0.099154, 0.091582, 0.069047], [0.099384, 0.093597, 0.068337], [0.099759, 0.095871, 0.067776], [0.10029, 0.098368, 0.067351], [0.10099, 0.101, 0.067056], [0.10185, 0.1039, 0.066891], [0.1029, 0.10702, 0.066853], [0.10407, 0.11031, 0.066942], [0.10543, 0.1138, 0.067155], [0.10701, 0.1175, 0.067485], [0.10866, 0.12142, 0.067929], [0.11059, 0.12561, 0.06849], [0.11265, 0.12998, 0.069162], [0.11483, 0.13453, 0.069842], [0.11725, 0.13923, 0.07061], [0.11985, 0.14422, 0.071528], [0.12259, 0.14937, 0.072403], [0.12558, 0.15467, 0.073463], [0.12867, 0.16015, 0.074429], [0.13196, 0.16584, 0.075451], [0.1354, 0.17169, 0.076499], [0.13898, 0.17771, 0.077615], [0.14273, 0.18382, 0.078814], [0.14658, 0.1901, 0.080098], [0.15058, 0.19654, 0.081473], [0.15468, 0.20304, 0.08282], [0.15891, 0.20968, 0.084315], [0.16324, 0.21644, 0.085726], [0.16764, 0.22326, 0.087378], [0.17214, 0.23015, 0.088955], [0.17673, 0.23717, 0.090617], [0.18139, 0.24418, 0.092314], [0.18615, 0.25132, 0.094071], [0.19092, 0.25846, 0.095839], [0.19578, 0.26567, 0.097702], [0.20067, 0.2729, 0.099539], [0.20564, 0.28016, 0.10144], [0.21062, 0.28744, 0.10342], [0.21565, 0.29475, 0.10534], [0.22072, 0.30207, 0.10737], [0.22579, 0.30942, 0.10942], [0.23087, 0.31675, 0.11146], [0.236, 0.32407, 0.11354], [0.24112, 0.3314, 0.11563], [0.24625, 0.33874, 0.11774], [0.25142, 0.34605, 0.11988], [0.25656, 0.35337, 0.12202], [0.26171, 0.36065, 0.12422], [0.26686, 0.36793, 0.12645], [0.272, 0.37519, 0.12865], [0.27717, 0.38242, 0.13092], [0.28231, 0.38964, 0.13316], [0.28741, 0.39682, 0.13541], [0.29253, 0.40398, 0.13773], [0.29763, 0.41111, 0.13998], [0.30271, 0.4182, 0.14232], [0.30778, 0.42527, 0.14466], [0.31283, 0.43231, 0.14699], [0.31787, 0.43929, 0.14937], [0.32289, 0.44625, 0.15173], [0.32787, 0.45318, 0.15414], [0.33286, 0.46006, 0.1566], [0.33781, 0.46693, 0.15904], [0.34276, 0.47374, 0.16155], [0.34769, 0.48054, 0.16407], [0.3526, 0.48733, 0.16661], [0.35753, 0.4941, 0.16923], [0.36245, 0.50086, 0.17185], [0.36738, 0.50764, 0.17458], [0.37234, 0.51443, 0.17738], [0.37735, 0.52125, 0.18022], [0.38238, 0.52812, 0.18318], [0.38746, 0.53505, 0.18626], [0.39261, 0.54204, 0.18942], [0.39783, 0.54911, 0.19272], [0.40311, 0.55624, 0.19616], [0.40846, 0.56348, 0.1997], [0.4139, 0.57078, 0.20345], [0.41942, 0.57819, 0.20734], [0.42503, 0.5857, 0.2114], [0.43071, 0.59329, 0.21565], [0.43649, 0.60098, 0.22009], [0.44237, 0.60878, 0.2247], [0.44833, 0.61667, 0.22956], [0.45439, 0.62465, 0.23468], [0.46053, 0.63274, 0.23997], [0.46679, 0.64092, 0.24553], [0.47313, 0.64921, 0.25138], [0.47959, 0.6576, 0.25745], [0.48612, 0.66608, 0.26382], [0.49277, 0.67466, 0.27047], [0.49951, 0.68335, 0.2774], [0.50636, 0.69213, 0.28464], [0.51331, 0.70101, 0.2922], [0.52035, 0.70998, 0.30008], [0.5275, 0.71905, 0.30828], [0.53474, 0.72821, 0.31682], [0.54207, 0.73747, 0.32567], [0.5495, 0.74682, 0.33491], [0.55702, 0.75625, 0.34443], [0.56461, 0.76577, 0.35434], [0.5723, 0.77537, 0.36457], [0.58006, 0.78506, 0.37515], [0.58789, 0.79482, 0.38607], [0.59581, 0.80465, 0.39734], [0.60379, 0.81455, 0.40894], [0.61182, 0.82453, 0.42086], [0.61991, 0.83457, 0.43311], [0.62805, 0.84467, 0.44566], [0.63623, 0.85482, 0.45852], [0.64445, 0.86503, 0.47168], [0.6527, 0.8753, 0.48511], [0.66099, 0.88562, 0.49882], [0.6693, 0.89599, 0.51278], [0.67763, 0.90641, 0.52699], [0.68597, 0.91687, 0.54141], [0.69432, 0.92738, 0.55605], [0.70269, 0.93794, 0.5709], [0.71107, 0.94855, 0.58593], [0.71945, 0.9592, 0.60112], [0.72782, 0.96989, 0.61646], [0.7362, 0.98063, 0.63191], [0.74458, 0.99141, 0.64748]] cmaps = {name: ListedColormap(data, name=name) for (name, data) in [('magma', _magma_data), ('inferno', _inferno_data), ('plasma', _plasma_data), ('viridis', _viridis_data), ('cividis', _cividis_data), ('twilight', _twilight_data), ('twilight_shifted', _twilight_shifted_data), ('turbo', _turbo_data), ('berlin', _berlin_data), ('managua', _managua_data), ('vanimo', _vanimo_data)]} # File: matplotlib-main/lib/matplotlib/_cm_multivar.py from .colors import LinearSegmentedColormap, MultivarColormap import matplotlib as mpl _LUTSIZE = mpl.rcParams['image.lut'] _2VarAddA0_data = [[0.0, 0.0, 0.0], [0.02, 0.026, 0.031], [0.049, 0.068, 0.085], [0.075, 0.107, 0.135], [0.097, 0.144, 0.183], [0.116, 0.178, 0.231], [0.133, 0.212, 0.279], [0.148, 0.244, 0.326], [0.161, 0.276, 0.374], [0.173, 0.308, 0.422], [0.182, 0.339, 0.471], [0.19, 0.37, 0.521], [0.197, 0.4, 0.572], [0.201, 0.431, 0.623], [0.204, 0.461, 0.675], [0.204, 0.491, 0.728], [0.202, 0.52, 0.783], [0.197, 0.549, 0.838], [0.187, 0.577, 0.895]] _2VarAddA1_data = [[0.0, 0.0, 0.0], [0.03, 0.023, 0.018], [0.079, 0.06, 0.043], [0.125, 0.093, 0.065], [0.17, 0.123, 0.083], [0.213, 0.151, 0.098], [0.255, 0.177, 0.11], [0.298, 0.202, 0.12], [0.341, 0.226, 0.128], [0.384, 0.249, 0.134], [0.427, 0.271, 0.138], [0.472, 0.292, 0.141], [0.517, 0.313, 0.142], [0.563, 0.333, 0.141], [0.61, 0.353, 0.139], [0.658, 0.372, 0.134], [0.708, 0.39, 0.127], [0.759, 0.407, 0.118], [0.813, 0.423, 0.105]] _2VarSubA0_data = [[1.0, 1.0, 1.0], [0.959, 0.973, 0.986], [0.916, 0.948, 0.974], [0.874, 0.923, 0.965], [0.832, 0.899, 0.956], [0.79, 0.875, 0.948], [0.748, 0.852, 0.94], [0.707, 0.829, 0.934], [0.665, 0.806, 0.927], [0.624, 0.784, 0.921], [0.583, 0.762, 0.916], [0.541, 0.74, 0.91], [0.5, 0.718, 0.905], [0.457, 0.697, 0.901], [0.414, 0.675, 0.896], [0.369, 0.652, 0.892], [0.32, 0.629, 0.888], [0.266, 0.604, 0.884], [0.199, 0.574, 0.881]] _2VarSubA1_data = [[1.0, 1.0, 1.0], [0.982, 0.967, 0.955], [0.966, 0.935, 0.908], [0.951, 0.902, 0.86], [0.937, 0.87, 0.813], [0.923, 0.838, 0.765], [0.91, 0.807, 0.718], [0.898, 0.776, 0.671], [0.886, 0.745, 0.624], [0.874, 0.714, 0.577], [0.862, 0.683, 0.53], [0.851, 0.653, 0.483], [0.841, 0.622, 0.435], [0.831, 0.592, 0.388], [0.822, 0.561, 0.34], [0.813, 0.53, 0.29], [0.806, 0.498, 0.239], [0.802, 0.464, 0.184], [0.801, 0.426, 0.119]] _3VarAddA0_data = [[0.0, 0.0, 0.0], [0.018, 0.023, 0.028], [0.04, 0.056, 0.071], [0.059, 0.087, 0.11], [0.074, 0.114, 0.147], [0.086, 0.139, 0.183], [0.095, 0.163, 0.219], [0.101, 0.187, 0.255], [0.105, 0.209, 0.29], [0.107, 0.23, 0.326], [0.105, 0.251, 0.362], [0.101, 0.271, 0.398], [0.091, 0.291, 0.434], [0.075, 0.309, 0.471], [0.046, 0.325, 0.507], [0.021, 0.341, 0.546], [0.021, 0.363, 0.584], [0.022, 0.385, 0.622], [0.023, 0.408, 0.661]] _3VarAddA1_data = [[0.0, 0.0, 0.0], [0.02, 0.024, 0.016], [0.047, 0.058, 0.034], [0.072, 0.088, 0.048], [0.093, 0.116, 0.059], [0.113, 0.142, 0.067], [0.131, 0.167, 0.071], [0.149, 0.19, 0.074], [0.166, 0.213, 0.074], [0.182, 0.235, 0.072], [0.198, 0.256, 0.068], [0.215, 0.276, 0.061], [0.232, 0.296, 0.051], [0.249, 0.314, 0.037], [0.27, 0.33, 0.018], [0.288, 0.347, 0.0], [0.302, 0.369, 0.0], [0.315, 0.391, 0.0], [0.328, 0.414, 0.0]] _3VarAddA2_data = [[0.0, 0.0, 0.0], [0.029, 0.02, 0.023], [0.072, 0.045, 0.055], [0.111, 0.067, 0.084], [0.148, 0.085, 0.109], [0.184, 0.101, 0.133], [0.219, 0.115, 0.155], [0.254, 0.127, 0.176], [0.289, 0.138, 0.195], [0.323, 0.147, 0.214], [0.358, 0.155, 0.232], [0.393, 0.161, 0.25], [0.429, 0.166, 0.267], [0.467, 0.169, 0.283], [0.507, 0.168, 0.298], [0.546, 0.168, 0.313], [0.58, 0.172, 0.328], [0.615, 0.175, 0.341], [0.649, 0.178, 0.355]] cmaps = {name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for (name, data) in [('2VarAddA0', _2VarAddA0_data), ('2VarAddA1', _2VarAddA1_data), ('2VarSubA0', _2VarSubA0_data), ('2VarSubA1', _2VarSubA1_data), ('3VarAddA0', _3VarAddA0_data), ('3VarAddA1', _3VarAddA1_data), ('3VarAddA2', _3VarAddA2_data)]} cmap_families = {'2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)], 'sRGB_add', name='2VarAddA'), '2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)], 'sRGB_sub', name='2VarSubA'), '3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)], 'sRGB_add', name='3VarAddA')} # File: matplotlib-main/lib/matplotlib/_color_data.py BASE_COLORS = {'b': (0, 0, 1), 'g': (0, 0.5, 0), 'r': (1, 0, 0), 'c': (0, 0.75, 0.75), 'm': (0.75, 0, 0.75), 'y': (0.75, 0.75, 0), 'k': (0, 0, 0), 'w': (1, 1, 1)} TABLEAU_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'} 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'} XKCD_COLORS = {'xkcd:' + name: value for (name, value) in XKCD_COLORS.items()} CSS4_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'} # File: matplotlib-main/lib/matplotlib/_constrained_layout.py """""" import logging import numpy as np from matplotlib import _api, artist as martist import matplotlib.transforms as mtransforms import matplotlib._layoutgrid as mlayoutgrid _log = logging.getLogger(__name__) def do_constrained_layout(fig, h_pad, w_pad, hspace=None, wspace=None, rect=(0, 0, 1, 1), compress=False): renderer = fig._get_renderer() layoutgrids = make_layoutgrids(fig, None, rect=rect) if not layoutgrids['hasgrids']: _api.warn_external('There are no gridspecs with layoutgrids. Possibly did not call parent GridSpec with the "figure" keyword') return for _ in range(2): make_layout_margins(layoutgrids, fig, renderer, h_pad=h_pad, w_pad=w_pad, hspace=hspace, wspace=wspace) make_margin_suptitles(layoutgrids, fig, renderer, h_pad=h_pad, w_pad=w_pad) match_submerged_margins(layoutgrids, fig) layoutgrids[fig].update_variables() warn_collapsed = 'constrained_layout not applied because axes sizes collapsed to zero. Try making figure larger or Axes decorations smaller.' if check_no_collapsed_axes(layoutgrids, fig): reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad, w_pad=w_pad, hspace=hspace, wspace=wspace) if compress: layoutgrids = compress_fixed_aspect(layoutgrids, fig) layoutgrids[fig].update_variables() if check_no_collapsed_axes(layoutgrids, fig): reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad, w_pad=w_pad, hspace=hspace, wspace=wspace) else: _api.warn_external(warn_collapsed) if (suptitle := fig._suptitle) is not None and suptitle.get_in_layout() and suptitle._autopos: (x, _) = suptitle.get_position() suptitle.set_position((x, layoutgrids[fig].get_inner_bbox().y1 + h_pad)) suptitle.set_verticalalignment('bottom') else: _api.warn_external(warn_collapsed) reset_margins(layoutgrids, fig) return layoutgrids def make_layoutgrids(fig, layoutgrids, rect=(0, 0, 1, 1)): if layoutgrids is None: layoutgrids = dict() layoutgrids['hasgrids'] = False if not hasattr(fig, '_parent'): layoutgrids[fig] = mlayoutgrid.LayoutGrid(parent=rect, name='figlb') else: gs = fig._subplotspec.get_gridspec() layoutgrids = make_layoutgrids_gs(layoutgrids, gs) parentlb = layoutgrids[gs] layoutgrids[fig] = mlayoutgrid.LayoutGrid(parent=parentlb, name='panellb', parent_inner=True, nrows=1, ncols=1, parent_pos=(fig._subplotspec.rowspan, fig._subplotspec.colspan)) for sfig in fig.subfigs: layoutgrids = make_layoutgrids(sfig, layoutgrids) for ax in fig._localaxes: gs = ax.get_gridspec() if gs is not None: layoutgrids = make_layoutgrids_gs(layoutgrids, gs) return layoutgrids def make_layoutgrids_gs(layoutgrids, gs): if gs in layoutgrids or gs.figure is None: return layoutgrids layoutgrids['hasgrids'] = True if not hasattr(gs, '_subplot_spec'): parent = layoutgrids[gs.figure] layoutgrids[gs] = mlayoutgrid.LayoutGrid(parent=parent, parent_inner=True, name='gridspec', ncols=gs._ncols, nrows=gs._nrows, width_ratios=gs.get_width_ratios(), height_ratios=gs.get_height_ratios()) else: subplot_spec = gs._subplot_spec parentgs = subplot_spec.get_gridspec() if parentgs not in layoutgrids: layoutgrids = make_layoutgrids_gs(layoutgrids, parentgs) subspeclb = layoutgrids[parentgs] rep = (gs, 'top') if rep not in layoutgrids: layoutgrids[rep] = mlayoutgrid.LayoutGrid(parent=subspeclb, name='top', nrows=1, ncols=1, parent_pos=(subplot_spec.rowspan, subplot_spec.colspan)) layoutgrids[gs] = mlayoutgrid.LayoutGrid(parent=layoutgrids[rep], name='gridspec', nrows=gs._nrows, ncols=gs._ncols, width_ratios=gs.get_width_ratios(), height_ratios=gs.get_height_ratios()) return layoutgrids def check_no_collapsed_axes(layoutgrids, fig): for sfig in fig.subfigs: ok = check_no_collapsed_axes(layoutgrids, sfig) if not ok: return False for ax in fig.axes: gs = ax.get_gridspec() if gs in layoutgrids: lg = layoutgrids[gs] for i in range(gs.nrows): for j in range(gs.ncols): bb = lg.get_inner_bbox(i, j) if bb.width <= 0 or bb.height <= 0: return False return True def compress_fixed_aspect(layoutgrids, fig): gs = None for ax in fig.axes: if ax.get_subplotspec() is None: continue ax.apply_aspect() sub = ax.get_subplotspec() _gs = sub.get_gridspec() if gs is None: gs = _gs extraw = np.zeros(gs.ncols) extrah = np.zeros(gs.nrows) elif _gs != gs: raise ValueError('Cannot do compressed layout if Axes are notall from the same gridspec') orig = ax.get_position(original=True) actual = ax.get_position(original=False) dw = orig.width - actual.width if dw > 0: extraw[sub.colspan] = np.maximum(extraw[sub.colspan], dw) dh = orig.height - actual.height if dh > 0: extrah[sub.rowspan] = np.maximum(extrah[sub.rowspan], dh) if gs is None: raise ValueError('Cannot do compressed layout if no Axes are part of a gridspec.') w = np.sum(extraw) / 2 layoutgrids[fig].edit_margin_min('left', w) layoutgrids[fig].edit_margin_min('right', w) h = np.sum(extrah) / 2 layoutgrids[fig].edit_margin_min('top', h) layoutgrids[fig].edit_margin_min('bottom', h) return layoutgrids def get_margin_from_padding(obj, *, w_pad=0, h_pad=0, hspace=0, wspace=0): ss = obj._subplotspec gs = ss.get_gridspec() if hasattr(gs, 'hspace'): _hspace = gs.hspace if gs.hspace is not None else hspace _wspace = gs.wspace if gs.wspace is not None else wspace else: _hspace = gs._hspace if gs._hspace is not None else hspace _wspace = gs._wspace if gs._wspace is not None else wspace _wspace = _wspace / 2 _hspace = _hspace / 2 (nrows, ncols) = gs.get_geometry() margin = {'leftcb': w_pad, 'rightcb': w_pad, 'bottomcb': h_pad, 'topcb': h_pad, 'left': 0, 'right': 0, 'top': 0, 'bottom': 0} if _wspace / ncols > w_pad: if ss.colspan.start > 0: margin['leftcb'] = _wspace / ncols if ss.colspan.stop < ncols: margin['rightcb'] = _wspace / ncols if _hspace / nrows > h_pad: if ss.rowspan.stop < nrows: margin['bottomcb'] = _hspace / nrows if ss.rowspan.start > 0: margin['topcb'] = _hspace / nrows return margin def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0, hspace=0, wspace=0): for sfig in fig.subfigs: ss = sfig._subplotspec gs = ss.get_gridspec() make_layout_margins(layoutgrids, sfig, renderer, w_pad=w_pad, h_pad=h_pad, hspace=hspace, wspace=wspace) margins = get_margin_from_padding(sfig, w_pad=0, h_pad=0, hspace=hspace, wspace=wspace) layoutgrids[gs].edit_outer_margin_mins(margins, ss) for ax in fig._localaxes: if not ax.get_subplotspec() or not ax.get_in_layout(): continue ss = ax.get_subplotspec() gs = ss.get_gridspec() if gs not in layoutgrids: return margin = get_margin_from_padding(ax, w_pad=w_pad, h_pad=h_pad, hspace=hspace, wspace=wspace) (pos, bbox) = get_pos_and_bbox(ax, renderer) margin['left'] += pos.x0 - bbox.x0 margin['right'] += bbox.x1 - pos.x1 margin['bottom'] += pos.y0 - bbox.y0 margin['top'] += bbox.y1 - pos.y1 for cbax in ax._colorbars: pad = colorbar_get_pad(layoutgrids, cbax) (cbp_rspan, cbp_cspan) = get_cb_parent_spans(cbax) loc = cbax._colorbar_info['location'] (cbpos, cbbbox) = get_pos_and_bbox(cbax, renderer) if loc == 'right': if cbp_cspan.stop == ss.colspan.stop: margin['rightcb'] += cbbbox.width + pad elif loc == 'left': if cbp_cspan.start == ss.colspan.start: margin['leftcb'] += cbbbox.width + pad elif loc == 'top': if cbp_rspan.start == ss.rowspan.start: margin['topcb'] += cbbbox.height + pad elif cbp_rspan.stop == ss.rowspan.stop: margin['bottomcb'] += cbbbox.height + pad if loc in ['top', 'bottom']: if cbp_cspan.start == ss.colspan.start and cbbbox.x0 < bbox.x0: margin['left'] += bbox.x0 - cbbbox.x0 if cbp_cspan.stop == ss.colspan.stop and cbbbox.x1 > bbox.x1: margin['right'] += cbbbox.x1 - bbox.x1 if loc in ['left', 'right']: if cbp_rspan.stop == ss.rowspan.stop and cbbbox.y0 < bbox.y0: margin['bottom'] += bbox.y0 - cbbbox.y0 if cbp_rspan.start == ss.rowspan.start and cbbbox.y1 > bbox.y1: margin['top'] += cbbbox.y1 - bbox.y1 layoutgrids[gs].edit_outer_margin_mins(margin, ss) for leg in fig.legends: inv_trans_fig = None if leg._outside_loc and leg._bbox_to_anchor is None: if inv_trans_fig is None: inv_trans_fig = fig.transFigure.inverted().transform_bbox bbox = inv_trans_fig(leg.get_tightbbox(renderer)) w = bbox.width + 2 * w_pad h = bbox.height + 2 * h_pad legendloc = leg._outside_loc if legendloc == 'lower': layoutgrids[fig].edit_margin_min('bottom', h) elif legendloc == 'upper': layoutgrids[fig].edit_margin_min('top', h) if legendloc == 'right': layoutgrids[fig].edit_margin_min('right', w) elif legendloc == 'left': layoutgrids[fig].edit_margin_min('left', w) def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0): inv_trans_fig = fig.transFigure.inverted().transform_bbox padbox = mtransforms.Bbox([[0, 0], [w_pad, h_pad]]) padbox = (fig.transFigure - fig.transSubfigure).transform_bbox(padbox) h_pad_local = padbox.height w_pad_local = padbox.width for sfig in fig.subfigs: make_margin_suptitles(layoutgrids, sfig, renderer, w_pad=w_pad, h_pad=h_pad) if fig._suptitle is not None and fig._suptitle.get_in_layout(): p = fig._suptitle.get_position() if getattr(fig._suptitle, '_autopos', False): fig._suptitle.set_position((p[0], 1 - h_pad_local)) bbox = inv_trans_fig(fig._suptitle.get_tightbbox(renderer)) layoutgrids[fig].edit_margin_min('top', bbox.height + 2 * h_pad) if fig._supxlabel is not None and fig._supxlabel.get_in_layout(): p = fig._supxlabel.get_position() if getattr(fig._supxlabel, '_autopos', False): fig._supxlabel.set_position((p[0], h_pad_local)) bbox = inv_trans_fig(fig._supxlabel.get_tightbbox(renderer)) layoutgrids[fig].edit_margin_min('bottom', bbox.height + 2 * h_pad) if fig._supylabel is not None and fig._supylabel.get_in_layout(): p = fig._supylabel.get_position() if getattr(fig._supylabel, '_autopos', False): fig._supylabel.set_position((w_pad_local, p[1])) bbox = inv_trans_fig(fig._supylabel.get_tightbbox(renderer)) layoutgrids[fig].edit_margin_min('left', bbox.width + 2 * w_pad) def match_submerged_margins(layoutgrids, fig): for sfig in fig.subfigs: match_submerged_margins(layoutgrids, sfig) axs = [a for a in fig.get_axes() if a.get_subplotspec() is not None and a.get_in_layout()] for ax1 in axs: ss1 = ax1.get_subplotspec() if ss1.get_gridspec() not in layoutgrids: axs.remove(ax1) continue lg1 = layoutgrids[ss1.get_gridspec()] if len(ss1.colspan) > 1: maxsubl = np.max(lg1.margin_vals['left'][ss1.colspan[1:]] + lg1.margin_vals['leftcb'][ss1.colspan[1:]]) maxsubr = np.max(lg1.margin_vals['right'][ss1.colspan[:-1]] + lg1.margin_vals['rightcb'][ss1.colspan[:-1]]) for ax2 in axs: ss2 = ax2.get_subplotspec() lg2 = layoutgrids[ss2.get_gridspec()] if lg2 is not None and len(ss2.colspan) > 1: maxsubl2 = np.max(lg2.margin_vals['left'][ss2.colspan[1:]] + lg2.margin_vals['leftcb'][ss2.colspan[1:]]) if maxsubl2 > maxsubl: maxsubl = maxsubl2 maxsubr2 = np.max(lg2.margin_vals['right'][ss2.colspan[:-1]] + lg2.margin_vals['rightcb'][ss2.colspan[:-1]]) if maxsubr2 > maxsubr: maxsubr = maxsubr2 for i in ss1.colspan[1:]: lg1.edit_margin_min('left', maxsubl, cell=i) for i in ss1.colspan[:-1]: lg1.edit_margin_min('right', maxsubr, cell=i) if len(ss1.rowspan) > 1: maxsubt = np.max(lg1.margin_vals['top'][ss1.rowspan[1:]] + lg1.margin_vals['topcb'][ss1.rowspan[1:]]) maxsubb = np.max(lg1.margin_vals['bottom'][ss1.rowspan[:-1]] + lg1.margin_vals['bottomcb'][ss1.rowspan[:-1]]) for ax2 in axs: ss2 = ax2.get_subplotspec() lg2 = layoutgrids[ss2.get_gridspec()] if lg2 is not None: if len(ss2.rowspan) > 1: maxsubt = np.max([np.max(lg2.margin_vals['top'][ss2.rowspan[1:]] + lg2.margin_vals['topcb'][ss2.rowspan[1:]]), maxsubt]) maxsubb = np.max([np.max(lg2.margin_vals['bottom'][ss2.rowspan[:-1]] + lg2.margin_vals['bottomcb'][ss2.rowspan[:-1]]), maxsubb]) for i in ss1.rowspan[1:]: lg1.edit_margin_min('top', maxsubt, cell=i) for i in ss1.rowspan[:-1]: lg1.edit_margin_min('bottom', maxsubb, cell=i) def get_cb_parent_spans(cbax): rowstart = np.inf rowstop = -np.inf colstart = np.inf colstop = -np.inf for parent in cbax._colorbar_info['parents']: ss = parent.get_subplotspec() rowstart = min(ss.rowspan.start, rowstart) rowstop = max(ss.rowspan.stop, rowstop) colstart = min(ss.colspan.start, colstart) colstop = max(ss.colspan.stop, colstop) rowspan = range(rowstart, rowstop) colspan = range(colstart, colstop) return (rowspan, colspan) def get_pos_and_bbox(ax, renderer): fig = ax.get_figure(root=False) pos = ax.get_position(original=True) pos = pos.transformed(fig.transSubfigure - fig.transFigure) tightbbox = martist._get_tightbbox_for_layout_only(ax, renderer) if tightbbox is None: bbox = pos else: bbox = tightbbox.transformed(fig.transFigure.inverted()) return (pos, bbox) def reposition_axes(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0, hspace=0, wspace=0): trans_fig_to_subfig = fig.transFigure - fig.transSubfigure for sfig in fig.subfigs: bbox = layoutgrids[sfig].get_outer_bbox() sfig._redo_transform_rel_fig(bbox=bbox.transformed(trans_fig_to_subfig)) reposition_axes(layoutgrids, sfig, renderer, w_pad=w_pad, h_pad=h_pad, wspace=wspace, hspace=hspace) for ax in fig._localaxes: if ax.get_subplotspec() is None or not ax.get_in_layout(): continue ss = ax.get_subplotspec() gs = ss.get_gridspec() if gs not in layoutgrids: return bbox = layoutgrids[gs].get_inner_bbox(rows=ss.rowspan, cols=ss.colspan) newbbox = trans_fig_to_subfig.transform_bbox(bbox) ax._set_position(newbbox) offset = {'left': 0, 'right': 0, 'bottom': 0, 'top': 0} for (nn, cbax) in enumerate(ax._colorbars[::-1]): if ax == cbax._colorbar_info['parents'][0]: reposition_colorbar(layoutgrids, cbax, renderer, offset=offset) def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None): parents = cbax._colorbar_info['parents'] gs = parents[0].get_gridspec() fig = cbax.get_figure(root=False) trans_fig_to_subfig = fig.transFigure - fig.transSubfigure (cb_rspans, cb_cspans) = get_cb_parent_spans(cbax) bboxparent = layoutgrids[gs].get_bbox_for_cb(rows=cb_rspans, cols=cb_cspans) pb = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans) location = cbax._colorbar_info['location'] anchor = cbax._colorbar_info['anchor'] fraction = cbax._colorbar_info['fraction'] aspect = cbax._colorbar_info['aspect'] shrink = cbax._colorbar_info['shrink'] (cbpos, cbbbox) = get_pos_and_bbox(cbax, renderer) cbpad = colorbar_get_pad(layoutgrids, cbax) if location in ('left', 'right'): pbcb = pb.shrunk(fraction, shrink).anchored(anchor, pb) if location == 'right': lmargin = cbpos.x0 - cbbbox.x0 dx = bboxparent.x1 - pbcb.x0 + offset['right'] dx += cbpad + lmargin offset['right'] += cbbbox.width + cbpad pbcb = pbcb.translated(dx, 0) else: lmargin = cbpos.x0 - cbbbox.x0 dx = bboxparent.x0 - pbcb.x0 dx += -cbbbox.width - cbpad + lmargin - offset['left'] offset['left'] += cbbbox.width + cbpad pbcb = pbcb.translated(dx, 0) else: pbcb = pb.shrunk(shrink, fraction).anchored(anchor, pb) if location == 'top': bmargin = cbpos.y0 - cbbbox.y0 dy = bboxparent.y1 - pbcb.y0 + offset['top'] dy += cbpad + bmargin offset['top'] += cbbbox.height + cbpad pbcb = pbcb.translated(0, dy) else: bmargin = cbpos.y0 - cbbbox.y0 dy = bboxparent.y0 - pbcb.y0 dy += -cbbbox.height - cbpad + bmargin - offset['bottom'] offset['bottom'] += cbbbox.height + cbpad pbcb = pbcb.translated(0, dy) pbcb = trans_fig_to_subfig.transform_bbox(pbcb) cbax.set_transform(fig.transSubfigure) cbax._set_position(pbcb) cbax.set_anchor(anchor) if location in ['bottom', 'top']: aspect = 1 / aspect cbax.set_box_aspect(aspect) cbax.set_aspect('auto') return offset def reset_margins(layoutgrids, fig): for sfig in fig.subfigs: reset_margins(layoutgrids, sfig) for ax in fig.axes: if ax.get_in_layout(): gs = ax.get_gridspec() if gs in layoutgrids: layoutgrids[gs].reset_margins() layoutgrids[fig].reset_margins() def colorbar_get_pad(layoutgrids, cax): parents = cax._colorbar_info['parents'] gs = parents[0].get_gridspec() (cb_rspans, cb_cspans) = get_cb_parent_spans(cax) bboxouter = layoutgrids[gs].get_inner_bbox(rows=cb_rspans, cols=cb_cspans) if cax._colorbar_info['location'] in ['right', 'left']: size = bboxouter.width else: size = bboxouter.height return cax._colorbar_info['pad'] * size # File: matplotlib-main/lib/matplotlib/_docstring.py import inspect from . import _api def kwarg_doc(text): def decorator(func): func._kwarg_doc = text return func return decorator class Substitution: 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 def update(self, *args, **kwargs): self.params.update(*args, **kwargs) 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(Substitution): def __init__(self): self.params = _ArtistKwdocLoader() def __call__(self, obj): super().__call__(obj) if isinstance(obj, type) and obj.__init__ != object.__init__: self(obj.__init__) return obj def copy(source): def do_copy(target): if source.__doc__: target.__doc__ = source.__doc__ return target return do_copy dedent_interpd = interpd = _ArtistPropertiesSubstitution() # File: matplotlib-main/lib/matplotlib/_enums.py """""" from enum import Enum, auto from matplotlib import _docstring class _AutoStringNameEnum(Enum): def _generate_next_value_(name, start, count, last_values): return name def __hash__(self): return str(self).__hash__() class JoinStyle(str, _AutoStringNameEnum): miter = auto() round = auto() bevel = auto() @staticmethod def demo(): import numpy as np import matplotlib.pyplot as plt def plot_angle(ax, x, y, angle, style): phi = np.radians(angle) xx = [x + 0.5, x, x + 0.5 * np.cos(phi)] yy = [y, y, y + 0.5 * np.sin(phi)] ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style) ax.plot(xx, yy, lw=1, color='black') ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3) (fig, ax) = plt.subplots(figsize=(5, 4), constrained_layout=True) ax.set_title('Join style') for (x, style) in enumerate(['miter', 'round', 'bevel']): ax.text(x, 5, style) for (y, angle) in enumerate([20, 45, 60, 90, 120]): plot_angle(ax, x, y, angle, style) if x == 0: ax.text(-1.3, y, f'{angle} degrees') ax.set_xlim(-1.5, 2.75) ax.set_ylim(-0.5, 5.5) ax.set_axis_off() fig.show() JoinStyle.input_description = '{' + ', '.join([f"'{js.name}'" for js in JoinStyle]) + '}' class CapStyle(str, _AutoStringNameEnum): butt = auto() projecting = auto() round = auto() @staticmethod def demo(): import matplotlib.pyplot as plt fig = plt.figure(figsize=(4, 1.2)) ax = fig.add_axes([0, 0, 1, 0.8]) ax.set_title('Cap style') for (x, style) in enumerate(['butt', 'round', 'projecting']): ax.text(x + 0.25, 0.85, style, ha='center') xx = [x, x + 0.5] yy = [0, 0] ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style) ax.plot(xx, yy, lw=1, color='black') ax.plot(xx, yy, 'o', color='tab:red', markersize=3) ax.set_ylim(-0.5, 1.5) ax.set_axis_off() fig.show() CapStyle.input_description = '{' + ', '.join([f"'{cs.name}'" for cs in CapStyle]) + '}' _docstring.interpd.update({'JoinStyle': JoinStyle.input_description, 'CapStyle': CapStyle.input_description}) # File: matplotlib-main/lib/matplotlib/_fontconfig_pattern.py """""" from functools import lru_cache, partial import re from pyparsing import Group, Optional, ParseException, Regex, StringEnd, Suppress, ZeroOrMore, oneOf _family_punc = '\\\\\\-:,' _family_unescape = partial(re.compile('\\\\(?=[%s])' % _family_punc).sub, '') _family_escape = partial(re.compile('(?=[%s])' % _family_punc).sub, '\\\\') _value_punc = '\\\\=_:,' _value_unescape = partial(re.compile('\\\\(?=[%s])' % _value_punc).sub, '') _value_escape = partial(re.compile('(?=[%s])' % _value_punc).sub, '\\\\') _CONSTANTS = {'thin': ('weight', 'light'), 'extralight': ('weight', 'light'), 'ultralight': ('weight', 'light'), 'light': ('weight', 'light'), 'book': ('weight', 'book'), 'regular': ('weight', 'regular'), 'normal': ('weight', 'normal'), 'medium': ('weight', 'medium'), 'demibold': ('weight', 'demibold'), 'semibold': ('weight', 'semibold'), 'bold': ('weight', 'bold'), 'extrabold': ('weight', 'extra bold'), 'black': ('weight', 'black'), 'heavy': ('weight', 'heavy'), 'roman': ('slant', 'normal'), 'italic': ('slant', 'italic'), 'oblique': ('slant', 'oblique'), 'ultracondensed': ('width', 'ultra-condensed'), 'extracondensed': ('width', 'extra-condensed'), 'condensed': ('width', 'condensed'), 'semicondensed': ('width', 'semi-condensed'), 'expanded': ('width', 'expanded'), 'extraexpanded': ('width', 'extra-expanded'), 'ultraexpanded': ('width', 'ultra-expanded')} @lru_cache def _make_fontconfig_parser(): def comma_separated(elem): return elem + ZeroOrMore(Suppress(',') + elem) family = Regex(f'([^{_family_punc}]|(\\\\[{_family_punc}]))*') size = Regex('([0-9]+\\.?[0-9]*|\\.[0-9]+)') name = Regex('[a-z]+') value = Regex(f'([^{_value_punc}]|(\\\\[{_value_punc}]))*') prop = Group(name + Suppress('=') + comma_separated(value) | oneOf(_CONSTANTS)) return Optional(comma_separated(family)('families')) + Optional('-' + comma_separated(size)('sizes')) + ZeroOrMore(':' + prop('properties*')) + StringEnd() @lru_cache def parse_fontconfig_pattern(pattern): parser = _make_fontconfig_parser() try: parse = parser.parseString(pattern) except ParseException as err: raise ValueError('\n' + ParseException.explain(err, 0)) from None parser.resetCache() props = {} if 'families' in parse: props['family'] = [*map(_family_unescape, parse['families'])] if 'sizes' in parse: props['size'] = [*parse['sizes']] for prop in parse.get('properties', []): if len(prop) == 1: prop = _CONSTANTS[prop[0]] (k, *v) = prop props.setdefault(k, []).extend(map(_value_unescape, v)) return props def generate_fontconfig_pattern(d): kvs = [(k, getattr(d, f'get_{k}')()) for k in ['style', 'variant', 'weight', 'stretch', 'file', 'size']] return ','.join((_family_escape(f) for f in d.get_family())) + ''.join((f':{k}={_value_escape(str(v))}' for (k, v) in kvs if v is not None)) # File: matplotlib-main/lib/matplotlib/_internal_utils.py """""" from io import StringIO from pathlib import Path import subprocess from matplotlib.transforms import TransformNode def graphviz_dump_transform(transform, dest, *, highlight=None): if highlight is None: highlight = [transform] seen = set() def recurse(root, buf): if id(root) in seen: return seen.add(id(root)) props = {} label = type(root).__name__ if root._invalid: label = f'[{label}]' if root in highlight: props['style'] = 'bold' props['shape'] = 'box' props['label'] = '"%s"' % label props = ' '.join(map('{0[0]}={0[1]}'.format, props.items())) buf.write(f'{id(root)} [{props}];\n') for (key, val) in vars(root).items(): if isinstance(val, TransformNode) and id(root) in val._parents: buf.write(f'"{id(root)}" -> "{id(val)}" [label="{key}", fontsize=10];\n') recurse(val, buf) buf = StringIO() buf.write('digraph G {\n') recurse(transform, buf) buf.write('}\n') subprocess.run(['dot', '-T', Path(dest).suffix[1:], '-o', dest], input=buf.getvalue().encode('utf-8'), check=True) # File: matplotlib-main/lib/matplotlib/_layoutgrid.py """""" import itertools import kiwisolver as kiwi import logging import numpy as np import matplotlib as mpl import matplotlib.patches as mpatches from matplotlib.transforms import Bbox _log = logging.getLogger(__name__) class 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): self.solver = kiwi.Solver() else: parent.add_child(self, *parent_pos) self.solver = parent.solver self.artists = np.empty((nrows, ncols), dtype=object) self.children = np.empty((nrows, ncols), dtype=object) self.margins = {} self.margin_vals = {} for todo in ['left', 'right', 'leftcb', 'rightcb']: 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') 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}: L{self.lefts[j].value():1.3f}, B{self.bottoms[i].value():1.3f}, R{self.rights[j].value():1.3f}, T{self.tops[i].value():1.3f}, ML{self.margins['left'][j].value():1.3f}, MR{self.margins['right'][j].value():1.3f}, MB{self.margins['bottom'][i].value():1.3f}, MT{self.margins['top'][i].value():1.3f}, \n" return str def reset_margins(self): for todo in ['left', 'right', 'bottom', 'top', 'leftcb', 'rightcb', 'bottomcb', 'topcb']: self.edit_margins(todo, 0.0) def add_constraints(self, parent): self.hard_constraints() self.parent_constraints(parent) self.grid_constraints() def hard_constraints(self): 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): self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child def parent_constraints(self, parent): if not isinstance(parent, LayoutGrid): hc = [self.lefts[0] == parent[0], self.rights[-1] == parent[0] + parent[2], 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: 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, self.tops[0] == top, self.bottoms[-1] == bottom] for c in hc: self.solver.addConstraint(c | 'required') def grid_constraints(self): 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] 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') c = self.rights[i - 1] == self.lefts[i] self.solver.addConstraint(c | 'strong') 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] 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') c = self.bottoms[i - 1] == self.tops[i] self.solver.addConstraint(c | 'strong') def edit_margin(self, todo, size, cell): self.solver.suggestValue(self.margins[todo][cell], size) self.margin_vals[todo][cell] = size def edit_margin_min(self, todo, size, cell=0): if size > self.margin_vals[todo][cell]: self.edit_margin(todo, size, cell) def edit_margins(self, todo, size): for i in range(len(self.margin_vals[todo])): self.edit_margin(todo, size, i) def edit_all_margins_min(self, todo, 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): 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) 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 self.margin_vals[todo][col] def get_outer_bbox(self, rows=0, cols=0): 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): 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): 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): 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): 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): 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): 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): self.solver.updateVariables() _layoutboxobjnum = itertools.count() def seq_id(): return '%06d' % next(_layoutboxobjnum) def plot_children(fig, lg=None, level=0): 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) # File: matplotlib-main/lib/matplotlib/_mathtext.py """""" from __future__ import annotations import abc import copy import enum import functools import logging import os import re import types import unicodedata import string import typing as T from typing import NamedTuple import numpy as np from pyparsing import Empty, Forward, Literal, NotAny, oneOf, OneOrMore, Optional, ParseBaseException, ParseException, ParseExpression, ParseFatalException, ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore, pyparsing_common, Group import matplotlib as mpl from . import cbook from ._mathtext_data import latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni from .font_manager import FontProperties, findfont, get_font from .ft2font import FT2Font, FT2Image, KERNING_DEFAULT from packaging.version import parse as parse_version from pyparsing import __version__ as pyparsing_version if parse_version(pyparsing_version).major < 3: from pyparsing import nestedExpr as nested_expr else: from pyparsing import nested_expr if T.TYPE_CHECKING: from collections.abc import Iterable from .ft2font import Glyph ParserElement.enablePackrat() _log = logging.getLogger('matplotlib.mathtext') def get_unicode_index(symbol: str) -> int: try: return ord(symbol) except TypeError: pass try: return tex2uni[symbol.strip('\\')] except KeyError as err: raise ValueError(f'{symbol!r} is not a valid Unicode character or TeX/Type1 symbol') from err class VectorParse(NamedTuple): width: float height: float depth: float glyphs: list[tuple[FT2Font, float, int, float, float]] rects: list[tuple[float, float, float, float]] VectorParse.__module__ = 'matplotlib.mathtext' class RasterParse(NamedTuple): ox: float oy: float width: float height: float depth: float image: FT2Image RasterParse.__module__ = 'matplotlib.mathtext' class Output: def __init__(self, box: Box): self.box = box self.glyphs: list[tuple[float, float, FontInfo]] = [] self.rects: list[tuple[float, float, float, float]] = [] def to_vector(self) -> VectorParse: (w, h, d) = map(np.ceil, [self.box.width, self.box.height, self.box.depth]) gs = [(info.font, info.fontsize, info.num, ox, h - oy + info.offset) for (ox, oy, info) in self.glyphs] rs = [(x1, h - y2, x2 - x1, y2 - y1) for (x1, y1, x2, y2) in self.rects] return VectorParse(w, h + d, d, gs, rs) def to_raster(self, *, antialiased: bool) -> RasterParse: xmin = min([*[ox + info.metrics.xmin for (ox, oy, info) in self.glyphs], *[x1 for (x1, y1, x2, y2) in self.rects], 0]) - 1 ymin = min([*[oy - info.metrics.ymax for (ox, oy, info) in self.glyphs], *[y1 for (x1, y1, x2, y2) in self.rects], 0]) - 1 xmax = max([*[ox + info.metrics.xmax for (ox, oy, info) in self.glyphs], *[x2 for (x1, y1, x2, y2) in self.rects], 0]) + 1 ymax = max([*[oy - info.metrics.ymin for (ox, oy, info) in self.glyphs], *[y2 for (x1, y1, x2, y2) in self.rects], 0]) + 1 w = xmax - xmin h = ymax - ymin - self.box.depth d = ymax - ymin - self.box.height image = FT2Image(np.ceil(w), np.ceil(h + max(d, 0))) shifted = ship(self.box, (-xmin, -ymin)) for (ox, oy, info) in shifted.glyphs: info.font.draw_glyph_to_bitmap(image, ox, oy - info.metrics.iceberg, info.glyph, antialiased=antialiased) for (x1, y1, x2, y2) in shifted.rects: height = max(int(y2 - y1) - 1, 0) if height == 0: center = (y2 + y1) / 2 y = int(center - (height + 1) / 2) else: y = int(y1) image.draw_rect_filled(int(x1), y, np.ceil(x2), y + height) return RasterParse(0, 0, w, h + d, d, image) class FontMetrics(NamedTuple): advance: float height: float width: float xmin: float xmax: float ymin: float ymax: float iceberg: float slanted: bool class FontInfo(NamedTuple): font: FT2Font fontsize: float postscript_name: str metrics: FontMetrics num: int glyph: Glyph offset: float class Fonts(abc.ABC): def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): self.default_font_prop = default_font_prop self.load_glyph_flags = load_glyph_flags def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, font2: str, fontclass2: str, sym2: str, fontsize2: float, dpi: float) -> float: return 0.0 def _get_font(self, font: str) -> FT2Font: raise NotImplementedError def _get_info(self, font: str, font_class: str, sym: str, fontsize: float, dpi: float) -> FontInfo: raise NotImplementedError def get_metrics(self, font: str, font_class: str, sym: str, fontsize: float, dpi: float) -> FontMetrics: info = self._get_info(font, font_class, sym, fontsize, dpi) return info.metrics def render_glyph(self, output: Output, ox: float, oy: float, font: str, font_class: str, sym: str, fontsize: float, dpi: float) -> None: info = self._get_info(font, font_class, sym, fontsize, dpi) output.glyphs.append((ox, oy, info)) def render_rect_filled(self, output: Output, x1: float, y1: float, x2: float, y2: float) -> None: output.rects.append((x1, y1, x2, y2)) def get_xheight(self, font: str, fontsize: float, dpi: float) -> float: raise NotImplementedError() def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: raise NotImplementedError() def get_sized_alternatives_for_symbol(self, fontname: str, sym: str) -> list[tuple[str, str]]: return [(fontname, sym)] class TruetypeFonts(Fonts, metaclass=abc.ABCMeta): def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): super().__init__(default_font_prop, load_glyph_flags) self._get_info = functools.cache(self._get_info) self._fonts = {} self.fontmap: dict[str | int, str] = {} filename = findfont(self.default_font_prop) default_font = get_font(filename) self._fonts['default'] = default_font self._fonts['regular'] = default_font def _get_font(self, font: str | int) -> FT2Font: if font in self.fontmap: basename = self.fontmap[font] else: basename = T.cast(str, font) cached_font = self._fonts.get(basename) if cached_font is None and os.path.exists(basename): cached_font = get_font(basename) self._fonts[basename] = cached_font self._fonts[cached_font.postscript_name] = cached_font self._fonts[cached_font.postscript_name.lower()] = cached_font return T.cast(FT2Font, cached_font) def _get_offset(self, font: FT2Font, glyph: Glyph, fontsize: float, dpi: float) -> float: if font.postscript_name == 'Cmex10': return glyph.height / 64 / 2 + fontsize / 3 * dpi / 72 return 0.0 def _get_glyph(self, fontname: str, font_class: str, sym: str) -> tuple[FT2Font, int, bool]: raise NotImplementedError def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float, dpi: float) -> FontInfo: (font, num, slanted) = self._get_glyph(fontname, font_class, sym) font.set_size(fontsize, dpi) glyph = font.load_char(num, flags=self.load_glyph_flags) (xmin, ymin, xmax, ymax) = (val / 64 for val in glyph.bbox) offset = self._get_offset(font, glyph, fontsize, dpi) metrics = FontMetrics(advance=glyph.linearHoriAdvance / 65536, height=glyph.height / 64, width=glyph.width / 64, xmin=xmin, xmax=xmax, ymin=ymin + offset, ymax=ymax + offset, iceberg=glyph.horiBearingY / 64 + offset, slanted=slanted) return FontInfo(font=font, fontsize=fontsize, postscript_name=font.postscript_name, metrics=metrics, num=num, glyph=glyph, offset=offset) def get_xheight(self, fontname: str, fontsize: float, dpi: float) -> float: font = self._get_font(fontname) font.set_size(fontsize, dpi) pclt = font.get_sfnt_table('pclt') if pclt is None: metrics = self.get_metrics(fontname, mpl.rcParams['mathtext.default'], 'x', fontsize, dpi) return metrics.iceberg xHeight = pclt['xHeight'] / 64.0 * (fontsize / 12.0) * (dpi / 100.0) return xHeight def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float: return 0.75 / 12.0 * fontsize * dpi / 72.0 def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float, font2: str, fontclass2: str, sym2: str, fontsize2: float, dpi: float) -> float: if font1 == font2 and fontsize1 == fontsize2: info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi) info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi) font = info1.font return font.get_kerning(info1.num, info2.num, KERNING_DEFAULT) / 64 return super().get_kern(font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi) class BakomaFonts(TruetypeFonts): _fontmap = {'cal': 'cmsy10', 'rm': 'cmr10', 'tt': 'cmtt10', 'it': 'cmmi10', 'bf': 'cmb10', 'sf': 'cmss10', 'ex': 'cmex10'} def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): self._stix_fallback = StixFonts(default_font_prop, load_glyph_flags) super().__init__(default_font_prop, load_glyph_flags) for (key, val) in self._fontmap.items(): fullpath = findfont(val) self.fontmap[key] = fullpath self.fontmap[val] = fullpath _slanted_symbols = set('\\int \\oint'.split()) def _get_glyph(self, fontname: str, font_class: str, sym: str) -> tuple[FT2Font, int, bool]: font = None if fontname in self.fontmap and sym in latex_to_bakoma: (basename, num) = latex_to_bakoma[sym] slanted = basename == 'cmmi10' or sym in self._slanted_symbols font = self._get_font(basename) elif len(sym) == 1: slanted = fontname == 'it' font = self._get_font(fontname) if font is not None: num = ord(sym) if font is not None and font.get_char_index(num) != 0: return (font, num, slanted) else: return self._stix_fallback._get_glyph(fontname, font_class, sym) _size_alternatives = {'(': [('rm', '('), ('ex', '¡'), ('ex', '³'), ('ex', 'µ'), ('ex', 'Ã')], ')': [('rm', ')'), ('ex', '¢'), ('ex', '´'), ('ex', '¶'), ('ex', '!')], '{': [('cal', '{'), ('ex', '©'), ('ex', 'n'), ('ex', '½'), ('ex', '(')], '}': [('cal', '}'), ('ex', 'ª'), ('ex', 'o'), ('ex', '¾'), ('ex', ')')], '[': [('rm', '['), ('ex', '£'), ('ex', 'h'), ('ex', '"')], ']': [('rm', ']'), ('ex', '¤'), ('ex', 'i'), ('ex', '#')], '\\lfloor': [('ex', '¥'), ('ex', 'j'), ('ex', '¹'), ('ex', '$')], '\\rfloor': [('ex', '¦'), ('ex', 'k'), ('ex', 'º'), ('ex', '%')], '\\lceil': [('ex', '§'), ('ex', 'l'), ('ex', '»'), ('ex', '&')], '\\rceil': [('ex', '¨'), ('ex', 'm'), ('ex', '¼'), ('ex', "'")], '\\langle': [('ex', '\xad'), ('ex', 'D'), ('ex', '¿'), ('ex', '*')], '\\rangle': [('ex', '®'), ('ex', 'E'), ('ex', 'À'), ('ex', '+')], '\\__sqrt__': [('ex', 'p'), ('ex', 'q'), ('ex', 'r'), ('ex', 's')], '\\backslash': [('ex', '²'), ('ex', '/'), ('ex', 'Â'), ('ex', '-')], '/': [('rm', '/'), ('ex', '±'), ('ex', '.'), ('ex', 'Ë'), ('ex', ',')], '\\widehat': [('rm', '^'), ('ex', 'b'), ('ex', 'c'), ('ex', 'd')], '\\widetilde': [('rm', '~'), ('ex', 'e'), ('ex', 'f'), ('ex', 'g')], '<': [('cal', 'h'), ('ex', 'D')], '>': [('cal', 'i'), ('ex', 'E')]} for (alias, target) in [('\\leftparen', '('), ('\\rightparent', ')'), ('\\leftbrace', '{'), ('\\rightbrace', '}'), ('\\leftbracket', '['), ('\\rightbracket', ']'), ('\\{', '{'), ('\\}', '}'), ('\\[', '['), ('\\]', ']')]: _size_alternatives[alias] = _size_alternatives[target] def get_sized_alternatives_for_symbol(self, fontname: str, sym: str) -> list[tuple[str, str]]: return self._size_alternatives.get(sym, [(fontname, sym)]) class UnicodeFonts(TruetypeFonts): _cmr10_substitutions = {215: 163, 8722: 161} def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): fallback_rc = mpl.rcParams['mathtext.fallback'] font_cls: type[TruetypeFonts] | None = {'stix': StixFonts, 'stixsans': StixSansFonts, 'cm': BakomaFonts}.get(fallback_rc) self._fallback_font = font_cls(default_font_prop, load_glyph_flags) if font_cls else None super().__init__(default_font_prop, load_glyph_flags) for texfont in 'cal rm tt it bf sf bfit'.split(): prop = mpl.rcParams['mathtext.' + texfont] font = findfont(prop) self.fontmap[texfont] = font prop = FontProperties('cmex10') font = findfont(prop) self.fontmap['ex'] = font if isinstance(self._fallback_font, StixFonts): stixsizedaltfonts = {0: 'STIXGeneral', 1: 'STIXSizeOneSym', 2: 'STIXSizeTwoSym', 3: 'STIXSizeThreeSym', 4: 'STIXSizeFourSym', 5: 'STIXSizeFiveSym'} for (size, name) in stixsizedaltfonts.items(): fullpath = findfont(name) self.fontmap[size] = fullpath self.fontmap[name] = fullpath _slanted_symbols = set('\\int \\oint'.split()) def _map_virtual_font(self, fontname: str, font_class: str, uniindex: int) -> tuple[str, int]: return (fontname, uniindex) def _get_glyph(self, fontname: str, font_class: str, sym: str) -> tuple[FT2Font, int, bool]: try: uniindex = get_unicode_index(sym) found_symbol = True except ValueError: uniindex = ord('?') found_symbol = False _log.warning('No TeX to Unicode mapping for %a.', sym) (fontname, uniindex) = self._map_virtual_font(fontname, font_class, uniindex) new_fontname = fontname if found_symbol: if fontname == 'it' and uniindex < 65536: char = chr(uniindex) if unicodedata.category(char)[0] != 'L' or unicodedata.name(char).startswith('GREEK CAPITAL'): new_fontname = 'rm' slanted = new_fontname == 'it' or sym in self._slanted_symbols found_symbol = False font = self._get_font(new_fontname) if font is not None: if uniindex in self._cmr10_substitutions and font.family_name == 'cmr10': font = get_font(cbook._get_data_path('fonts/ttf/cmsy10.ttf')) uniindex = self._cmr10_substitutions[uniindex] glyphindex = font.get_char_index(uniindex) if glyphindex != 0: found_symbol = True if not found_symbol: if self._fallback_font: if fontname in ('it', 'regular') and isinstance(self._fallback_font, StixFonts): fontname = 'rm' g = self._fallback_font._get_glyph(fontname, font_class, sym) family = g[0].family_name if family in list(BakomaFonts._fontmap.values()): family = 'Computer Modern' _log.info('Substituting symbol %s from %s', sym, family) return g else: if fontname in ('it', 'regular') and isinstance(self, StixFonts): return self._get_glyph('rm', font_class, sym) _log.warning('Font %r does not have a glyph for %a [U+%x], substituting with a dummy symbol.', new_fontname, sym, uniindex) font = self._get_font('rm') uniindex = 164 slanted = False return (font, uniindex, slanted) def get_sized_alternatives_for_symbol(self, fontname: str, sym: str) -> list[tuple[str, str]]: if self._fallback_font: return self._fallback_font.get_sized_alternatives_for_symbol(fontname, sym) return [(fontname, sym)] class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta): _fontmap: dict[str | int, str] = {} def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): if isinstance(self, DejaVuSerifFonts): self._fallback_font = StixFonts(default_font_prop, load_glyph_flags) else: self._fallback_font = StixSansFonts(default_font_prop, load_glyph_flags) self.bakoma = BakomaFonts(default_font_prop, load_glyph_flags) TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) self._fontmap.update({1: 'STIXSizeOneSym', 2: 'STIXSizeTwoSym', 3: 'STIXSizeThreeSym', 4: 'STIXSizeFourSym', 5: 'STIXSizeFiveSym'}) for (key, name) in self._fontmap.items(): fullpath = findfont(name) self.fontmap[key] = fullpath self.fontmap[name] = fullpath def _get_glyph(self, fontname: str, font_class: str, sym: str) -> tuple[FT2Font, int, bool]: if sym == '\\prime': return self.bakoma._get_glyph(fontname, font_class, sym) else: uniindex = get_unicode_index(sym) font = self._get_font('ex') if font is not None: glyphindex = font.get_char_index(uniindex) if glyphindex != 0: return super()._get_glyph('ex', font_class, sym) return super()._get_glyph(fontname, font_class, sym) class DejaVuSerifFonts(DejaVuFonts): _fontmap = {'rm': 'DejaVu Serif', 'it': 'DejaVu Serif:italic', 'bf': 'DejaVu Serif:weight=bold', 'bfit': 'DejaVu Serif:italic:bold', 'sf': 'DejaVu Sans', 'tt': 'DejaVu Sans Mono', 'ex': 'DejaVu Serif Display', 0: 'DejaVu Serif'} class DejaVuSansFonts(DejaVuFonts): _fontmap = {'rm': 'DejaVu Sans', 'it': 'DejaVu Sans:italic', 'bf': 'DejaVu Sans:weight=bold', 'bfit': 'DejaVu Sans:italic:bold', 'sf': 'DejaVu Sans', 'tt': 'DejaVu Sans Mono', 'ex': 'DejaVu Sans Display', 0: 'DejaVu Sans'} class StixFonts(UnicodeFonts): _fontmap: dict[str | int, str] = {'rm': 'STIXGeneral', 'it': 'STIXGeneral:italic', 'bf': 'STIXGeneral:weight=bold', 'bfit': 'STIXGeneral:italic:bold', 'nonunirm': 'STIXNonUnicode', 'nonuniit': 'STIXNonUnicode:italic', 'nonunibf': 'STIXNonUnicode:weight=bold', 0: 'STIXGeneral', 1: 'STIXSizeOneSym', 2: 'STIXSizeTwoSym', 3: 'STIXSizeThreeSym', 4: 'STIXSizeFourSym', 5: 'STIXSizeFiveSym'} _fallback_font = None _sans = False def __init__(self, default_font_prop: FontProperties, load_glyph_flags: int): TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags) for (key, name) in self._fontmap.items(): fullpath = findfont(name) self.fontmap[key] = fullpath self.fontmap[name] = fullpath def _map_virtual_font(self, fontname: str, font_class: str, uniindex: int) -> tuple[str, int]: font_mapping = stix_virtual_fonts.get(fontname) if self._sans and font_mapping is None and (fontname not in ('regular', 'default')): font_mapping = stix_virtual_fonts['sf'] doing_sans_conversion = True else: doing_sans_conversion = False if isinstance(font_mapping, dict): try: mapping = font_mapping[font_class] except KeyError: mapping = font_mapping['rm'] elif isinstance(font_mapping, list): mapping = font_mapping else: mapping = None if mapping is not None: lo = 0 hi = len(mapping) while lo < hi: mid = (lo + hi) // 2 range = mapping[mid] if uniindex < range[0]: hi = mid elif uniindex <= range[1]: break else: lo = mid + 1 if range[0] <= uniindex <= range[1]: uniindex = uniindex - range[0] + range[3] fontname = range[2] elif not doing_sans_conversion: uniindex = 1 fontname = mpl.rcParams['mathtext.default'] if fontname in ('rm', 'it'): uniindex = stix_glyph_fixes.get(uniindex, uniindex) if fontname in ('it', 'rm', 'bf', 'bfit') and 57344 <= uniindex <= 63743: fontname = 'nonuni' + fontname return (fontname, uniindex) @functools.cache def get_sized_alternatives_for_symbol(self, fontname: str, sym: str) -> list[tuple[str, str]] | list[tuple[int, str]]: fixes = {'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']', '<': '⟨', '>': '⟩'} sym = fixes.get(sym, sym) try: uniindex = get_unicode_index(sym) except ValueError: return [(fontname, sym)] alternatives = [(i, chr(uniindex)) for i in range(6) if self._get_font(i).get_char_index(uniindex) != 0] if sym == '\\__sqrt__': alternatives = alternatives[:-1] return alternatives class StixSansFonts(StixFonts): _sans = True SHRINK_FACTOR = 0.7 NUM_SIZE_LEVELS = 6 class FontConstantsBase: script_space: T.ClassVar[float] = 0.05 subdrop: T.ClassVar[float] = 0.4 sup1: T.ClassVar[float] = 0.7 sub1: T.ClassVar[float] = 0.3 sub2: T.ClassVar[float] = 0.5 delta: T.ClassVar[float] = 0.025 delta_slanted: T.ClassVar[float] = 0.2 delta_integral: T.ClassVar[float] = 0.1 class ComputerModernFontConstants(FontConstantsBase): script_space = 0.075 subdrop = 0.2 sup1 = 0.45 sub1 = 0.2 sub2 = 0.3 delta = 0.075 delta_slanted = 0.3 delta_integral = 0.3 class STIXFontConstants(FontConstantsBase): script_space = 0.1 sup1 = 0.8 sub2 = 0.6 delta = 0.05 delta_slanted = 0.3 delta_integral = 0.3 class STIXSansFontConstants(FontConstantsBase): script_space = 0.05 sup1 = 0.8 delta_slanted = 0.6 delta_integral = 0.3 class DejaVuSerifFontConstants(FontConstantsBase): pass class DejaVuSansFontConstants(FontConstantsBase): pass _font_constant_mapping = {'DejaVu Sans': DejaVuSansFontConstants, 'DejaVu Sans Mono': DejaVuSansFontConstants, 'DejaVu Serif': DejaVuSerifFontConstants, 'cmb10': ComputerModernFontConstants, 'cmex10': ComputerModernFontConstants, 'cmmi10': ComputerModernFontConstants, 'cmr10': ComputerModernFontConstants, 'cmss10': ComputerModernFontConstants, 'cmsy10': ComputerModernFontConstants, 'cmtt10': ComputerModernFontConstants, 'STIXGeneral': STIXFontConstants, 'STIXNonUnicode': STIXFontConstants, 'STIXSizeFiveSym': STIXFontConstants, 'STIXSizeFourSym': STIXFontConstants, 'STIXSizeThreeSym': STIXFontConstants, 'STIXSizeTwoSym': STIXFontConstants, 'STIXSizeOneSym': STIXFontConstants, 'Bitstream Vera Sans': DejaVuSansFontConstants, 'Bitstream Vera': DejaVuSansFontConstants} def _get_font_constant_set(state: ParserState) -> type[FontConstantsBase]: constants = _font_constant_mapping.get(state.fontset._get_font(state.font).family_name, FontConstantsBase) if constants is STIXFontConstants and isinstance(state.fontset, StixSansFonts): return STIXSansFontConstants return constants class Node: def __init__(self) -> None: self.size = 0 def __repr__(self) -> str: return type(self).__name__ def get_kerning(self, next: Node | None) -> float: return 0.0 def shrink(self) -> None: self.size += 1 def render(self, output: Output, x: float, y: float) -> None: class Box(Node): def __init__(self, width: float, height: float, depth: float) -> None: super().__init__() self.width = width self.height = height self.depth = depth def shrink(self) -> None: super().shrink() if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR def render(self, output: Output, x1: float, y1: float, x2: float, y2: float) -> None: pass class Vbox(Box): def __init__(self, height: float, depth: float): super().__init__(0.0, height, depth) class Hbox(Box): def __init__(self, width: float): super().__init__(width, 0.0, 0.0) class Char(Node): def __init__(self, c: str, state: ParserState): super().__init__() self.c = c self.fontset = state.fontset self.font = state.font self.font_class = state.font_class self.fontsize = state.fontsize self.dpi = state.dpi self._update_metrics() def __repr__(self) -> str: return '`%s`' % self.c def _update_metrics(self) -> None: metrics = self._metrics = self.fontset.get_metrics(self.font, self.font_class, self.c, self.fontsize, self.dpi) if self.c == ' ': self.width = metrics.advance else: self.width = metrics.width self.height = metrics.iceberg self.depth = -(metrics.iceberg - metrics.height) def is_slanted(self) -> bool: return self._metrics.slanted def get_kerning(self, next: Node | None) -> float: advance = self._metrics.advance - self.width kern = 0.0 if isinstance(next, Char): kern = self.fontset.get_kern(self.font, self.font_class, self.c, self.fontsize, next.font, next.font_class, next.c, next.fontsize, self.dpi) return advance + kern def render(self, output: Output, x: float, y: float) -> None: self.fontset.render_glyph(output, x, y, self.font, self.font_class, self.c, self.fontsize, self.dpi) def shrink(self) -> None: super().shrink() if self.size < NUM_SIZE_LEVELS: self.fontsize *= SHRINK_FACTOR self.width *= SHRINK_FACTOR self.height *= SHRINK_FACTOR self.depth *= SHRINK_FACTOR class Accent(Char): def _update_metrics(self) -> None: metrics = self._metrics = self.fontset.get_metrics(self.font, self.font_class, self.c, self.fontsize, self.dpi) self.width = metrics.xmax - metrics.xmin self.height = metrics.ymax - metrics.ymin self.depth = 0 def shrink(self) -> None: super().shrink() self._update_metrics() def render(self, output: Output, x: float, y: float) -> None: self.fontset.render_glyph(output, x - self._metrics.xmin, y + self._metrics.ymin, self.font, self.font_class, self.c, self.fontsize, self.dpi) class List(Box): def __init__(self, elements: T.Sequence[Node]): super().__init__(0.0, 0.0, 0.0) self.shift_amount = 0.0 self.children = [*elements] self.glue_set = 0.0 self.glue_sign = 0 self.glue_order = 0 def __repr__(self) -> str: return '{}[{}]'.format(super().__repr__(), self.width, self.height, self.depth, self.shift_amount, ', '.join([repr(x) for x in self.children])) def _set_glue(self, x: float, sign: int, totals: list[float], error_type: str) -> None: self.glue_order = o = next((i for i in range(len(totals))[::-1] if totals[i] != 0), 0) self.glue_sign = sign if totals[o] != 0.0: self.glue_set = x / totals[o] else: self.glue_sign = 0 self.glue_ratio = 0.0 if o == 0: if len(self.children): _log.warning('%s %s: %r', error_type, type(self).__name__, self) def shrink(self) -> None: for child in self.children: child.shrink() super().shrink() if self.size < NUM_SIZE_LEVELS: self.shift_amount *= SHRINK_FACTOR self.glue_set *= SHRINK_FACTOR class Hlist(List): def __init__(self, elements: T.Sequence[Node], w: float=0.0, m: T.Literal['additional', 'exactly']='additional', do_kern: bool=True): super().__init__(elements) if do_kern: self.kern() self.hpack(w=w, m=m) def kern(self) -> None: new_children = [] num_children = len(self.children) if num_children: for i in range(num_children): elem = self.children[i] if i < num_children - 1: next = self.children[i + 1] else: next = None new_children.append(elem) kerning_distance = elem.get_kerning(next) if kerning_distance != 0.0: kern = Kern(kerning_distance) new_children.append(kern) self.children = new_children def hpack(self, w: float=0.0, m: T.Literal['additional', 'exactly']='additional') -> None: h = 0.0 d = 0.0 x = 0.0 total_stretch = [0.0] * 4 total_shrink = [0.0] * 4 for p in self.children: if isinstance(p, Char): x += p.width h = max(h, p.height) d = max(d, p.depth) elif isinstance(p, Box): x += p.width if not np.isinf(p.height) and (not np.isinf(p.depth)): s = getattr(p, 'shift_amount', 0.0) h = max(h, p.height - s) d = max(d, p.depth + s) elif isinstance(p, Glue): glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += p.width self.height = h self.depth = d if m == 'additional': w += x self.width = w x = w - x if x == 0.0: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0.0 return if x > 0.0: self._set_glue(x, 1, total_stretch, 'Overful') else: self._set_glue(x, -1, total_shrink, 'Underful') class Vlist(List): def __init__(self, elements: T.Sequence[Node], h: float=0.0, m: T.Literal['additional', 'exactly']='additional'): super().__init__(elements) self.vpack(h=h, m=m) def vpack(self, h: float=0.0, m: T.Literal['additional', 'exactly']='additional', l: float=np.inf) -> None: w = 0.0 d = 0.0 x = 0.0 total_stretch = [0.0] * 4 total_shrink = [0.0] * 4 for p in self.children: if isinstance(p, Box): x += d + p.height d = p.depth if not np.isinf(p.width): s = getattr(p, 'shift_amount', 0.0) w = max(w, p.width + s) elif isinstance(p, Glue): x += d d = 0.0 glue_spec = p.glue_spec x += glue_spec.width total_stretch[glue_spec.stretch_order] += glue_spec.stretch total_shrink[glue_spec.shrink_order] += glue_spec.shrink elif isinstance(p, Kern): x += d + p.width d = 0.0 elif isinstance(p, Char): raise RuntimeError('Internal mathtext error: Char node found in Vlist') self.width = w if d > l: x += d - l self.depth = l else: self.depth = d if m == 'additional': h += x self.height = h x = h - x if x == 0: self.glue_sign = 0 self.glue_order = 0 self.glue_ratio = 0.0 return if x > 0.0: self._set_glue(x, 1, total_stretch, 'Overful') else: self._set_glue(x, -1, total_shrink, 'Underful') class Rule(Box): def __init__(self, width: float, height: float, depth: float, state: ParserState): super().__init__(width, height, depth) self.fontset = state.fontset def render(self, output: Output, x: float, y: float, w: float, h: float) -> None: self.fontset.render_rect_filled(output, x, y, x + w, y + h) class Hrule(Rule): def __init__(self, state: ParserState, thickness: float | None=None): if thickness is None: thickness = state.get_current_underline_thickness() height = depth = thickness * 0.5 super().__init__(np.inf, height, depth, state) class Vrule(Rule): def __init__(self, state: ParserState): thickness = state.get_current_underline_thickness() super().__init__(thickness, np.inf, np.inf, state) class _GlueSpec(NamedTuple): width: float stretch: float stretch_order: int shrink: float shrink_order: int _GlueSpec._named = {'fil': _GlueSpec(0.0, 1.0, 1, 0.0, 0), 'fill': _GlueSpec(0.0, 1.0, 2, 0.0, 0), 'filll': _GlueSpec(0.0, 1.0, 3, 0.0, 0), 'neg_fil': _GlueSpec(0.0, 0.0, 0, 1.0, 1), 'neg_fill': _GlueSpec(0.0, 0.0, 0, 1.0, 2), 'neg_filll': _GlueSpec(0.0, 0.0, 0, 1.0, 3), 'empty': _GlueSpec(0.0, 0.0, 0, 0.0, 0), 'ss': _GlueSpec(0.0, 1.0, 1, -1.0, 1)} class Glue(Node): def __init__(self, glue_type: _GlueSpec | T.Literal['fil', 'fill', 'filll', 'neg_fil', 'neg_fill', 'neg_filll', 'empty', 'ss']): super().__init__() if isinstance(glue_type, str): glue_spec = _GlueSpec._named[glue_type] elif isinstance(glue_type, _GlueSpec): glue_spec = glue_type else: raise ValueError('glue_type must be a glue spec name or instance') self.glue_spec = glue_spec def shrink(self) -> None: super().shrink() if self.size < NUM_SIZE_LEVELS: g = self.glue_spec self.glue_spec = g._replace(width=g.width * SHRINK_FACTOR) class HCentered(Hlist): def __init__(self, elements: list[Node]): super().__init__([Glue('ss'), *elements, Glue('ss')], do_kern=False) class VCentered(Vlist): def __init__(self, elements: list[Node]): super().__init__([Glue('ss'), *elements, Glue('ss')]) class Kern(Node): height = 0 depth = 0 def __init__(self, width: float): super().__init__() self.width = width def __repr__(self) -> str: return 'k%.02f' % self.width def shrink(self) -> None: super().shrink() if self.size < NUM_SIZE_LEVELS: self.width *= SHRINK_FACTOR class AutoHeightChar(Hlist): def __init__(self, c: str, height: float, depth: float, state: ParserState, always: bool=False, factor: float | None=None): alternatives = state.fontset.get_sized_alternatives_for_symbol(state.font, c) xHeight = state.fontset.get_xheight(state.font, state.fontsize, state.dpi) state = state.copy() target_total = height + depth for (fontname, sym) in alternatives: state.font = fontname char = Char(sym, state) if char.height + char.depth >= target_total - 0.2 * xHeight: break shift = 0.0 if state.font != 0 or len(alternatives) == 1: if factor is None: factor = target_total / (char.height + char.depth) state.fontsize *= factor char = Char(sym, state) shift = depth - char.depth super().__init__([char]) self.shift_amount = shift class AutoWidthChar(Hlist): def __init__(self, c: str, width: float, state: ParserState, always: bool=False, char_class: type[Char]=Char): alternatives = state.fontset.get_sized_alternatives_for_symbol(state.font, c) state = state.copy() for (fontname, sym) in alternatives: state.font = fontname char = char_class(sym, state) if char.width >= width: break factor = width / char.width state.fontsize *= factor char = char_class(sym, state) super().__init__([char]) self.width = char.width def ship(box: Box, xy: tuple[float, float]=(0, 0)) -> Output: (ox, oy) = xy cur_v = 0.0 cur_h = 0.0 off_h = ox off_v = oy + box.height output = Output(box) def clamp(value: float) -> float: return -1000000000.0 if value < -1000000000.0 else +1000000000.0 if value > +1000000000.0 else value def hlist_out(box: Hlist) -> None: nonlocal cur_v, cur_h, off_h, off_v cur_g = 0 cur_glue = 0.0 glue_order = box.glue_order glue_sign = box.glue_sign base_line = cur_v left_edge = cur_h for p in box.children: if isinstance(p, Char): p.render(output, cur_h + off_h, cur_v + off_v) cur_h += p.width elif isinstance(p, Kern): cur_h += p.width elif isinstance(p, List): if len(p.children) == 0: cur_h += p.width else: edge = cur_h cur_v = base_line + p.shift_amount if isinstance(p, Hlist): hlist_out(p) elif isinstance(p, Vlist): vlist_out(p) else: assert False, 'unreachable code' cur_h = edge + p.width cur_v = base_line elif isinstance(p, Box): rule_height = p.height rule_depth = p.depth rule_width = p.width if np.isinf(rule_height): rule_height = box.height if np.isinf(rule_depth): rule_depth = box.depth if rule_height > 0 and rule_width > 0: cur_v = base_line + rule_depth p.render(output, cur_h + off_h, cur_v + off_v, rule_width, rule_height) cur_v = base_line cur_h += rule_width elif isinstance(p, Glue): glue_spec = p.glue_spec rule_width = glue_spec.width - cur_g if glue_sign != 0: if glue_sign == 1: if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = round(clamp(box.glue_set * cur_glue)) elif glue_spec.shrink_order == glue_order: cur_glue += glue_spec.shrink cur_g = round(clamp(box.glue_set * cur_glue)) rule_width += cur_g cur_h += rule_width def vlist_out(box: Vlist) -> None: nonlocal cur_v, cur_h, off_h, off_v cur_g = 0 cur_glue = 0.0 glue_order = box.glue_order glue_sign = box.glue_sign left_edge = cur_h cur_v -= box.height top_edge = cur_v for p in box.children: if isinstance(p, Kern): cur_v += p.width elif isinstance(p, List): if len(p.children) == 0: cur_v += p.height + p.depth else: cur_v += p.height cur_h = left_edge + p.shift_amount save_v = cur_v p.width = box.width if isinstance(p, Hlist): hlist_out(p) elif isinstance(p, Vlist): vlist_out(p) else: assert False, 'unreachable code' cur_v = save_v + p.depth cur_h = left_edge elif isinstance(p, Box): rule_height = p.height rule_depth = p.depth rule_width = p.width if np.isinf(rule_width): rule_width = box.width rule_height += rule_depth if rule_height > 0 and rule_depth > 0: cur_v += rule_height p.render(output, cur_h + off_h, cur_v + off_v, rule_width, rule_height) elif isinstance(p, Glue): glue_spec = p.glue_spec rule_height = glue_spec.width - cur_g if glue_sign != 0: if glue_sign == 1: if glue_spec.stretch_order == glue_order: cur_glue += glue_spec.stretch cur_g = round(clamp(box.glue_set * cur_glue)) elif glue_spec.shrink_order == glue_order: cur_glue += glue_spec.shrink cur_g = round(clamp(box.glue_set * cur_glue)) rule_height += cur_g cur_v += rule_height elif isinstance(p, Char): raise RuntimeError('Internal mathtext error: Char node found in vlist') assert isinstance(box, Hlist) hlist_out(box) return output def Error(msg: str) -> ParserElement: def raise_error(s: str, loc: int, toks: ParseResults) -> T.Any: raise ParseFatalException(s, loc, msg) return Empty().setParseAction(raise_error) class ParserState: def __init__(self, fontset: Fonts, font: str, font_class: str, fontsize: float, dpi: float): self.fontset = fontset self._font = font self.font_class = font_class self.fontsize = fontsize self.dpi = dpi def copy(self) -> ParserState: return copy.copy(self) @property def font(self) -> str: return self._font @font.setter def font(self, name: str) -> None: if name in ('rm', 'it', 'bf', 'bfit'): self.font_class = name self._font = name def get_current_underline_thickness(self) -> float: return self.fontset.get_underline_thickness(self.font, self.fontsize, self.dpi) def cmd(expr: str, args: ParserElement) -> ParserElement: def names(elt: ParserElement) -> T.Generator[str, None, None]: if isinstance(elt, ParseExpression): for expr in elt.exprs: yield from names(expr) elif elt.resultsName: yield elt.resultsName csname = expr.split('{', 1)[0] err = csname + ''.join(('{%s}' % name for name in names(args))) if expr == csname else expr return csname - (args | Error(f'Expected {err}')) class Parser: class _MathStyle(enum.Enum): DISPLAYSTYLE = 0 TEXTSTYLE = 1 SCRIPTSTYLE = 2 SCRIPTSCRIPTSTYLE = 3 _binary_operators = set('+ * - −\n \\pm \\sqcap \\rhd\n \\mp \\sqcup \\unlhd\n \\times \\vee \\unrhd\n \\div \\wedge \\oplus\n \\ast \\setminus \\ominus\n \\star \\wr \\otimes\n \\circ \\diamond \\oslash\n \\bullet \\bigtriangleup \\odot\n \\cdot \\bigtriangledown \\bigcirc\n \\cap \\triangleleft \\dagger\n \\cup \\triangleright \\ddagger\n \\uplus \\lhd \\amalg\n \\dotplus \\dotminus \\Cap\n \\Cup \\barwedge \\boxdot\n \\boxminus \\boxplus \\boxtimes\n \\curlyvee \\curlywedge \\divideontimes\n \\doublebarwedge \\leftthreetimes \\rightthreetimes\n \\slash \\veebar \\barvee\n \\cupdot \\intercal \\amalg\n \\circledcirc \\circleddash \\circledast\n \\boxbar \\obar \\merge\n \\minuscolon \\dotsminusdots\n '.split()) _relation_symbols = set('\n = < > :\n \\leq \\geq \\equiv \\models\n \\prec \\succ \\sim \\perp\n \\preceq \\succeq \\simeq \\mid\n \\ll \\gg \\asymp \\parallel\n \\subset \\supset \\approx \\bowtie\n \\subseteq \\supseteq \\cong \\Join\n \\sqsubset \\sqsupset \\neq \\smile\n \\sqsubseteq \\sqsupseteq \\doteq \\frown\n \\in \\ni \\propto \\vdash\n \\dashv \\dots \\doteqdot \\leqq\n \\geqq \\lneqq \\gneqq \\lessgtr\n \\leqslant \\geqslant \\eqgtr \\eqless\n \\eqslantless \\eqslantgtr \\lesseqgtr \\backsim\n \\backsimeq \\lesssim \\gtrsim \\precsim\n \\precnsim \\gnsim \\lnsim \\succsim\n \\succnsim \\nsim \\lesseqqgtr \\gtreqqless\n \\gtreqless \\subseteqq \\supseteqq \\subsetneqq\n \\supsetneqq \\lessapprox \\approxeq \\gtrapprox\n \\precapprox \\succapprox \\precnapprox \\succnapprox\n \\npreccurlyeq \\nsucccurlyeq \\nsqsubseteq \\nsqsupseteq\n \\sqsubsetneq \\sqsupsetneq \\nlesssim \\ngtrsim\n \\nlessgtr \\ngtrless \\lnapprox \\gnapprox\n \\napprox \\approxeq \\approxident \\lll\n \\ggg \\nparallel \\Vdash \\Vvdash\n \\nVdash \\nvdash \\vDash \\nvDash\n \\nVDash \\oequal \\simneqq \\triangle\n \\triangleq \\triangleeq \\triangleleft\n \\triangleright \\ntriangleleft \\ntriangleright\n \\trianglelefteq \\ntrianglelefteq \\trianglerighteq\n \\ntrianglerighteq \\blacktriangleleft \\blacktriangleright\n \\equalparallel \\measuredrightangle \\varlrtriangle\n \\Doteq \\Bumpeq \\Subset \\Supset\n \\backepsilon \\because \\therefore \\bot\n \\top \\bumpeq \\circeq \\coloneq\n \\curlyeqprec \\curlyeqsucc \\eqcirc \\eqcolon\n \\eqsim \\fallingdotseq \\gtrdot \\gtrless\n \\ltimes \\rtimes \\lessdot \\ne\n \\ncong \\nequiv \\ngeq \\ngtr\n \\nleq \\nless \\nmid \\notin\n \\nprec \\nsubset \\nsubseteq \\nsucc\n \\nsupset \\nsupseteq \\pitchfork \\preccurlyeq\n \\risingdotseq \\subsetneq \\succcurlyeq \\supsetneq\n \\varpropto \\vartriangleleft \\scurel\n \\vartriangleright \\rightangle \\equal \\backcong\n \\eqdef \\wedgeq \\questeq \\between\n \\veeeq \\disin \\varisins \\isins\n \\isindot \\varisinobar \\isinobar \\isinvb\n \\isinE \\nisd \\varnis \\nis\n \\varniobar \\niobar \\bagmember \\ratio\n \\Equiv \\stareq \\measeq \\arceq\n \\rightassert \\rightModels \\smallin \\smallowns\n \\notsmallowns \\nsimeq'.split()) _arrow_symbols = set('\n \\leftarrow \\longleftarrow \\uparrow \\Leftarrow \\Longleftarrow\n \\Uparrow \\rightarrow \\longrightarrow \\downarrow \\Rightarrow\n \\Longrightarrow \\Downarrow \\leftrightarrow \\updownarrow\n \\longleftrightarrow \\updownarrow \\Leftrightarrow\n \\Longleftrightarrow \\Updownarrow \\mapsto \\longmapsto \\nearrow\n \\hookleftarrow \\hookrightarrow \\searrow \\leftharpoonup\n \\rightharpoonup \\swarrow \\leftharpoondown \\rightharpoondown\n \\nwarrow \\rightleftharpoons \\leadsto \\dashrightarrow\n \\dashleftarrow \\leftleftarrows \\leftrightarrows \\Lleftarrow\n \\Rrightarrow \\twoheadleftarrow \\leftarrowtail \\looparrowleft\n \\leftrightharpoons \\curvearrowleft \\circlearrowleft \\Lsh\n \\upuparrows \\upharpoonleft \\downharpoonleft \\multimap\n \\leftrightsquigarrow \\rightrightarrows \\rightleftarrows\n \\rightrightarrows \\rightleftarrows \\twoheadrightarrow\n \\rightarrowtail \\looparrowright \\rightleftharpoons\n \\curvearrowright \\circlearrowright \\Rsh \\downdownarrows\n \\upharpoonright \\downharpoonright \\rightsquigarrow \\nleftarrow\n \\nrightarrow \\nLeftarrow \\nRightarrow \\nleftrightarrow\n \\nLeftrightarrow \\to \\Swarrow \\Searrow \\Nwarrow \\Nearrow\n \\leftsquigarrow \\overleftarrow \\overleftrightarrow \\cwopencirclearrow\n \\downzigzagarrow \\cupleftarrow \\rightzigzagarrow \\twoheaddownarrow\n \\updownarrowbar \\twoheaduparrow \\rightarrowbar \\updownarrows\n \\barleftarrow \\mapsfrom \\mapsdown \\mapsup \\Ldsh \\Rdsh\n '.split()) _spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols _punctuation_symbols = set(', ; . ! \\ldotp \\cdotp'.split()) _overunder_symbols = set('\n \\sum \\prod \\coprod \\bigcap \\bigcup \\bigsqcup \\bigvee\n \\bigwedge \\bigodot \\bigotimes \\bigoplus \\biguplus\n '.split()) _overunder_functions = set('lim liminf limsup sup max min'.split()) _dropsub_symbols = set('\\int \\oint \\iint \\oiint \\iiint \\oiiint \\iiiint'.split()) _fontnames = set('rm cal it tt sf bf bfit default bb frak scr regular'.split()) _function_names = set('\n arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim\n liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan\n coth inf max tanh'.split()) _ambi_delims = set('\n | \\| / \\backslash \\uparrow \\downarrow \\updownarrow \\Uparrow\n \\Downarrow \\Updownarrow . \\vert \\Vert'.split()) _left_delims = set('\n ( [ \\{ < \\lfloor \\langle \\lceil \\lbrace \\leftbrace \\lbrack \\leftparen \\lgroup\n '.split()) _right_delims = set('\n ) ] \\} > \\rfloor \\rangle \\rceil \\rbrace \\rightbrace \\rbrack \\rightparen \\rgroup\n '.split()) _delims = _left_delims | _right_delims | _ambi_delims _small_greek = set([unicodedata.name(chr(i)).split()[-1].lower() for i in range(ord('α'), ord('ω') + 1)]) _latin_alphabets = set(string.ascii_letters) def __init__(self) -> None: p = types.SimpleNamespace() def set_names_and_parse_actions() -> None: for (key, val) in vars(p).items(): if not key.startswith('_'): if key not in ('token', 'placeable', 'auto_delim'): val.setName(key) if hasattr(self, key): val.setParseAction(getattr(self, key)) def csnames(group: str, names: Iterable[str]) -> Regex: ends_with_alpha = [] ends_with_nonalpha = [] for name in names: if name[-1].isalpha(): ends_with_alpha.append(name) else: ends_with_nonalpha.append(name) return Regex('\\\\(?P<{group}>(?:{alpha})(?![A-Za-z]){additional}{nonalpha})'.format(group=group, alpha='|'.join(map(re.escape, ends_with_alpha)), additional='|' if ends_with_nonalpha else '', nonalpha='|'.join(map(re.escape, ends_with_nonalpha)))) p.float_literal = Regex('[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)') p.space = oneOf(self._space_widths)('space') p.style_literal = oneOf([str(e.value) for e in self._MathStyle])('style_literal') p.symbol = Regex("[a-zA-Z0-9 +\\-*/<>=:,.;!\\?&'@()\\[\\]|\\U00000080-\\U0001ffff]|\\\\[%${}\\[\\]_|]" + '|\\\\(?:{})(?![A-Za-z])'.format('|'.join(map(re.escape, tex2uni))))('sym').leaveWhitespace() p.unknown_symbol = Regex('\\\\[A-Za-z]+')('name') p.font = csnames('font', self._fontnames) p.start_group = Optional('\\math' + oneOf(self._fontnames)('font')) + '{' p.end_group = Literal('}') p.delim = oneOf(self._delims) p.auto_delim = Forward() p.placeable = Forward() p.named_placeable = Forward() p.required_group = Forward() p.optional_group = Forward() p.token = Forward() p.named_placeable <<= p.placeable set_names_and_parse_actions() p.optional_group <<= '{' + ZeroOrMore(p.token)('group') + '}' p.required_group <<= '{' + OneOrMore(p.token)('group') + '}' p.customspace = cmd('\\hspace', '{' + p.float_literal('space') + '}') p.accent = csnames('accent', [*self._accent_map, *self._wide_accents]) - p.named_placeable('sym') p.function = csnames('name', self._function_names) p.group = p.start_group + ZeroOrMore(p.token)('group') + p.end_group p.unclosed_group = p.start_group + ZeroOrMore(p.token)('group') + StringEnd() p.frac = cmd('\\frac', p.required_group('num') + p.required_group('den')) p.dfrac = cmd('\\dfrac', p.required_group('num') + p.required_group('den')) p.binom = cmd('\\binom', p.required_group('num') + p.required_group('den')) p.genfrac = cmd('\\genfrac', '{' + Optional(p.delim)('ldelim') + '}' + '{' + Optional(p.delim)('rdelim') + '}' + '{' + p.float_literal('rulesize') + '}' + '{' + Optional(p.style_literal)('style') + '}' + p.required_group('num') + p.required_group('den')) p.sqrt = cmd('\\sqrt{value}', Optional('[' + OneOrMore(NotAny(']') + p.token)('root') + ']') + p.required_group('value')) p.overline = cmd('\\overline', p.required_group('body')) p.overset = cmd('\\overset', p.optional_group('annotation') + p.optional_group('body')) p.underset = cmd('\\underset', p.optional_group('annotation') + p.optional_group('body')) p.text = cmd('\\text', QuotedString('{', '\\', endQuoteChar='}')) p.substack = cmd('\\substack', nested_expr(opener='{', closer='}', content=Group(OneOrMore(p.token)) + ZeroOrMore(Literal('\\\\').suppress()))('parts')) p.subsuper = Optional(p.placeable)('nucleus') + OneOrMore(oneOf(['_', '^']) - p.placeable)('subsuper') + Regex("'*")('apostrophes') | Regex("'+")('apostrophes') | p.named_placeable('nucleus') + Regex("'*")('apostrophes') p.simple = p.space | p.customspace | p.font | p.subsuper p.token <<= p.simple | p.auto_delim | p.unclosed_group | p.unknown_symbol p.operatorname = cmd('\\operatorname', '{' + ZeroOrMore(p.simple)('name') + '}') p.boldsymbol = cmd('\\boldsymbol', '{' + ZeroOrMore(p.simple)('value') + '}') p.placeable <<= p.accent | p.symbol | p.function | p.operatorname | p.group | p.frac | p.dfrac | p.binom | p.genfrac | p.overset | p.underset | p.sqrt | p.overline | p.text | p.boldsymbol | p.substack mdelim = '\\middle' - (p.delim('mdelim') | Error('Expected a delimiter')) p.auto_delim <<= '\\left' - (p.delim('left') | Error('Expected a delimiter')) + ZeroOrMore(p.simple | p.auto_delim | mdelim)('mid') + '\\right' - (p.delim('right') | Error('Expected a delimiter')) p.math = OneOrMore(p.token) p.math_string = QuotedString('$', '\\', unquoteResults=False) p.non_math = Regex('(?:(?:\\\\[$])|[^$])*').leaveWhitespace() p.main = p.non_math + ZeroOrMore(p.math_string + p.non_math) + StringEnd() set_names_and_parse_actions() self._expression = p.main self._math_expression = p.math self._in_subscript_or_superscript = False def parse(self, s: str, fonts_object: Fonts, fontsize: float, dpi: float) -> Hlist: self._state_stack = [ParserState(fonts_object, 'default', 'rm', fontsize, dpi)] self._em_width_cache: dict[tuple[str, float, float], float] = {} try: result = self._expression.parseString(s) except ParseBaseException as err: raise ValueError('\n' + ParseException.explain(err, 0)) from None self._state_stack = [] self._in_subscript_or_superscript = False self._em_width_cache = {} ParserElement.resetCache() return T.cast(Hlist, result[0]) def get_state(self) -> ParserState: return self._state_stack[-1] def pop_state(self) -> None: self._state_stack.pop() def push_state(self) -> None: self._state_stack.append(self.get_state().copy()) def main(self, toks: ParseResults) -> list[Hlist]: return [Hlist(toks.asList())] def math_string(self, toks: ParseResults) -> ParseResults: return self._math_expression.parseString(toks[0][1:-1], parseAll=True) def math(self, toks: ParseResults) -> T.Any: hlist = Hlist(toks.asList()) self.pop_state() return [hlist] def non_math(self, toks: ParseResults) -> T.Any: s = toks[0].replace('\\$', '$') symbols = [Char(c, self.get_state()) for c in s] hlist = Hlist(symbols) self.push_state() self.get_state().font = mpl.rcParams['mathtext.default'] return [hlist] float_literal = staticmethod(pyparsing_common.convertToFloat) def text(self, toks: ParseResults) -> T.Any: self.push_state() state = self.get_state() state.font = 'rm' hlist = Hlist([Char(c, state) for c in toks[1]]) self.pop_state() return [hlist] def _make_space(self, percentage: float) -> Kern: state = self.get_state() key = (state.font, state.fontsize, state.dpi) width = self._em_width_cache.get(key) if width is None: metrics = state.fontset.get_metrics('it', mpl.rcParams['mathtext.default'], 'm', state.fontsize, state.dpi) width = metrics.advance self._em_width_cache[key] = width return Kern(width * percentage) _space_widths = {'\\,': 0.16667, '\\thinspace': 0.16667, '\\/': 0.16667, '\\>': 0.22222, '\\:': 0.22222, '\\;': 0.27778, '\\ ': 0.33333, '~': 0.33333, '\\enspace': 0.5, '\\quad': 1, '\\qquad': 2, '\\!': -0.16667} def space(self, toks: ParseResults) -> T.Any: num = self._space_widths[toks['space']] box = self._make_space(num) return [box] def customspace(self, toks: ParseResults) -> T.Any: return [self._make_space(toks['space'])] def symbol(self, s: str, loc: int, toks: ParseResults | dict[str, str]) -> T.Any: c = toks['sym'] if c == '-': c = '−' try: char = Char(c, self.get_state()) except ValueError as err: raise ParseFatalException(s, loc, 'Unknown symbol: %s' % c) from err if c in self._spaced_symbols: prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') if self._in_subscript_or_superscript or (c in self._binary_operators and (len(s[:loc].split()) == 0 or prev_char in {'{', *self._left_delims, *self._relation_symbols})): return [char] else: return [Hlist([self._make_space(0.2), char, self._make_space(0.2)], do_kern=True)] elif c in self._punctuation_symbols: prev_char = next((c for c in s[:loc][::-1] if c != ' '), '') next_char = next((c for c in s[loc + 1:] if c != ' '), '') if c == ',': if prev_char == '{' and next_char == '}': return [char] if c == '.' and prev_char.isdigit() and next_char.isdigit(): return [char] else: return [Hlist([char, self._make_space(0.2)], do_kern=True)] return [char] def unknown_symbol(self, s: str, loc: int, toks: ParseResults) -> T.Any: raise ParseFatalException(s, loc, f"Unknown symbol: {toks['name']}") _accent_map = {'hat': '\\circumflexaccent', 'breve': '\\combiningbreve', 'bar': '\\combiningoverline', 'grave': '\\combininggraveaccent', 'acute': '\\combiningacuteaccent', 'tilde': '\\combiningtilde', 'dot': '\\combiningdotabove', 'ddot': '\\combiningdiaeresis', 'dddot': '\\combiningthreedotsabove', 'ddddot': '\\combiningfourdotsabove', 'vec': '\\combiningrightarrowabove', '"': '\\combiningdiaeresis', '`': '\\combininggraveaccent', "'": '\\combiningacuteaccent', '~': '\\combiningtilde', '.': '\\combiningdotabove', '^': '\\circumflexaccent', 'overrightarrow': '\\rightarrow', 'overleftarrow': '\\leftarrow', 'mathring': '\\circ'} _wide_accents = set('widehat widetilde widebar'.split()) def accent(self, toks: ParseResults) -> T.Any: state = self.get_state() thickness = state.get_current_underline_thickness() accent = toks['accent'] sym = toks['sym'] accent_box: Node if accent in self._wide_accents: accent_box = AutoWidthChar('\\' + accent, sym.width, state, char_class=Accent) else: accent_box = Accent(self._accent_map[accent], state) if accent == 'mathring': accent_box.shrink() accent_box.shrink() centered = HCentered([Hbox(sym.width / 4.0), accent_box]) centered.hpack(sym.width, 'exactly') return Vlist([centered, Vbox(0.0, thickness * 2.0), Hlist([sym])]) def function(self, s: str, loc: int, toks: ParseResults) -> T.Any: hlist = self.operatorname(s, loc, toks) hlist.function_name = toks['name'] return hlist def operatorname(self, s: str, loc: int, toks: ParseResults) -> T.Any: self.push_state() state = self.get_state() state.font = 'rm' hlist_list: list[Node] = [] name = toks['name'] for c in name: if isinstance(c, Char): c.font = 'rm' c._update_metrics() hlist_list.append(c) elif isinstance(c, str): hlist_list.append(Char(c, state)) else: hlist_list.append(c) next_char_loc = loc + len(name) + 1 if isinstance(name, ParseResults): next_char_loc += len('operatorname{}') next_char = next((c for c in s[next_char_loc:] if c != ' '), '') delimiters = self._delims | {'^', '_'} if next_char not in delimiters and name not in self._overunder_functions: hlist_list += [self._make_space(self._space_widths['\\,'])] self.pop_state() if next_char in {'^', '_'}: self._in_subscript_or_superscript = True else: self._in_subscript_or_superscript = False return Hlist(hlist_list) def start_group(self, toks: ParseResults) -> T.Any: self.push_state() if toks.get('font'): self.get_state().font = toks.get('font') return [] def group(self, toks: ParseResults) -> T.Any: grp = Hlist(toks.get('group', [])) return [grp] def required_group(self, toks: ParseResults) -> T.Any: return Hlist(toks.get('group', [])) optional_group = required_group def end_group(self) -> T.Any: self.pop_state() return [] def unclosed_group(self, s: str, loc: int, toks: ParseResults) -> T.Any: raise ParseFatalException(s, len(s), "Expected '}'") def font(self, toks: ParseResults) -> T.Any: self.get_state().font = toks['font'] return [] def is_overunder(self, nucleus: Node) -> bool: if isinstance(nucleus, Char): return nucleus.c in self._overunder_symbols elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'): return nucleus.function_name in self._overunder_functions return False def is_dropsub(self, nucleus: Node) -> bool: if isinstance(nucleus, Char): return nucleus.c in self._dropsub_symbols return False def is_slanted(self, nucleus: Node) -> bool: if isinstance(nucleus, Char): return nucleus.is_slanted() return False def subsuper(self, s: str, loc: int, toks: ParseResults) -> T.Any: nucleus = toks.get('nucleus', Hbox(0)) subsuper = toks.get('subsuper', []) napostrophes = len(toks.get('apostrophes', [])) if not subsuper and (not napostrophes): return nucleus sub = super = None while subsuper: (op, arg, *subsuper) = subsuper if op == '_': if sub is not None: raise ParseFatalException('Double subscript') sub = arg else: if super is not None: raise ParseFatalException('Double superscript') super = arg state = self.get_state() rule_thickness = state.fontset.get_underline_thickness(state.font, state.fontsize, state.dpi) xHeight = state.fontset.get_xheight(state.font, state.fontsize, state.dpi) if napostrophes: if super is None: super = Hlist([]) for i in range(napostrophes): super.children.extend(self.symbol(s, loc, {'sym': '\\prime'})) super.kern() super.hpack() if self.is_overunder(nucleus): vlist = [] shift = 0.0 width = nucleus.width if super is not None: super.shrink() width = max(width, super.width) if sub is not None: sub.shrink() width = max(width, sub.width) vgap = rule_thickness * 3.0 if super is not None: hlist = HCentered([super]) hlist.hpack(width, 'exactly') vlist.extend([hlist, Vbox(0, vgap)]) hlist = HCentered([nucleus]) hlist.hpack(width, 'exactly') vlist.append(hlist) if sub is not None: hlist = HCentered([sub]) hlist.hpack(width, 'exactly') vlist.extend([Vbox(0, vgap), hlist]) shift = hlist.height + vgap + nucleus.depth vlt = Vlist(vlist) vlt.shift_amount = shift result = Hlist([vlt]) return [result] last_char = nucleus if isinstance(nucleus, Hlist): new_children = nucleus.children if len(new_children): if isinstance(new_children[-1], Kern) and hasattr(new_children[-2], '_metrics'): new_children = new_children[:-1] last_char = new_children[-1] if hasattr(last_char, '_metrics'): last_char.width = last_char._metrics.advance nucleus = Hlist(new_children, do_kern=False) else: if isinstance(nucleus, Char): last_char.width = last_char._metrics.advance nucleus = Hlist([nucleus]) constants = _get_font_constant_set(state) lc_height = last_char.height lc_baseline = 0 if self.is_dropsub(last_char): lc_baseline = last_char.depth superkern = constants.delta * xHeight subkern = constants.delta * xHeight if self.is_slanted(last_char): superkern += constants.delta * xHeight superkern += constants.delta_slanted * (lc_height - xHeight * 2.0 / 3.0) if self.is_dropsub(last_char): subkern = (3 * constants.delta - constants.delta_integral) * lc_height superkern = (3 * constants.delta + constants.delta_integral) * lc_height else: subkern = 0 x: List if super is None: x = Hlist([Kern(subkern), T.cast(Node, sub)]) x.shrink() if self.is_dropsub(last_char): shift_down = lc_baseline + constants.subdrop * xHeight else: shift_down = constants.sub1 * xHeight x.shift_amount = shift_down else: x = Hlist([Kern(superkern), super]) x.shrink() if self.is_dropsub(last_char): shift_up = lc_height - constants.subdrop * xHeight else: shift_up = constants.sup1 * xHeight if sub is None: x.shift_amount = -shift_up else: y = Hlist([Kern(subkern), sub]) y.shrink() if self.is_dropsub(last_char): shift_down = lc_baseline + constants.subdrop * xHeight else: shift_down = constants.sub2 * xHeight clr = 2.0 * rule_thickness - (shift_up - x.depth - (y.height - shift_down)) if clr > 0.0: shift_up += clr x = Vlist([x, Kern(shift_up - x.depth - (y.height - shift_down)), y]) x.shift_amount = shift_down if not self.is_dropsub(last_char): x.width += constants.script_space * xHeight spaced_nucleus = [nucleus, x] if self._in_subscript_or_superscript: spaced_nucleus += [self._make_space(self._space_widths['\\,'])] self._in_subscript_or_superscript = False result = Hlist(spaced_nucleus) return [result] def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathStyle, num: Hlist, den: Hlist) -> T.Any: state = self.get_state() thickness = state.get_current_underline_thickness() for _ in range(style.value): num.shrink() den.shrink() cnum = HCentered([num]) cden = HCentered([den]) width = max(num.width, den.width) cnum.hpack(width, 'exactly') cden.hpack(width, 'exactly') vlist = Vlist([cnum, Vbox(0, thickness * 2.0), Hrule(state, rule), Vbox(0, thickness * 2.0), cden]) metrics = state.fontset.get_metrics(state.font, mpl.rcParams['mathtext.default'], '=', state.fontsize, state.dpi) shift = cden.height - ((metrics.ymax + metrics.ymin) / 2 - thickness * 3.0) vlist.shift_amount = shift result = [Hlist([vlist, Hbox(thickness * 2.0)])] if ldelim or rdelim: if ldelim == '': ldelim = '.' if rdelim == '': rdelim = '.' return self._auto_sized_delimiter(ldelim, T.cast(list[Box | Char | str], result), rdelim) return result def style_literal(self, toks: ParseResults) -> T.Any: return self._MathStyle(int(toks['style_literal'])) def genfrac(self, toks: ParseResults) -> T.Any: return self._genfrac(toks.get('ldelim', ''), toks.get('rdelim', ''), toks['rulesize'], toks.get('style', self._MathStyle.TEXTSTYLE), toks['num'], toks['den']) def frac(self, toks: ParseResults) -> T.Any: return self._genfrac('', '', self.get_state().get_current_underline_thickness(), self._MathStyle.TEXTSTYLE, toks['num'], toks['den']) def dfrac(self, toks: ParseResults) -> T.Any: return self._genfrac('', '', self.get_state().get_current_underline_thickness(), self._MathStyle.DISPLAYSTYLE, toks['num'], toks['den']) def binom(self, toks: ParseResults) -> T.Any: return self._genfrac('(', ')', 0, self._MathStyle.TEXTSTYLE, toks['num'], toks['den']) def _genset(self, s: str, loc: int, toks: ParseResults) -> T.Any: annotation = toks['annotation'] body = toks['body'] thickness = self.get_state().get_current_underline_thickness() annotation.shrink() centered_annotation = HCentered([annotation]) centered_body = HCentered([body]) width = max(centered_annotation.width, centered_body.width) centered_annotation.hpack(width, 'exactly') centered_body.hpack(width, 'exactly') vgap = thickness * 3 if s[loc + 1] == 'u': vlist = Vlist([centered_body, Vbox(0, vgap), centered_annotation]) vlist.shift_amount = centered_body.depth + centered_annotation.height + vgap else: vlist = Vlist([centered_annotation, Vbox(0, vgap), centered_body]) return vlist overset = underset = _genset def sqrt(self, toks: ParseResults) -> T.Any: root = toks.get('root') body = toks['value'] state = self.get_state() thickness = state.get_current_underline_thickness() height = body.height - body.shift_amount + thickness * 5.0 depth = body.depth + body.shift_amount check = AutoHeightChar('\\__sqrt__', height, depth, state, always=True) height = check.height - check.shift_amount depth = check.depth + check.shift_amount padded_body = Hlist([Hbox(2 * thickness), body, Hbox(2 * thickness)]) rightside = Vlist([Hrule(state), Glue('fill'), padded_body]) rightside.vpack(height + state.fontsize * state.dpi / (100.0 * 12.0), 'exactly', depth) if not root: root = Box(check.width * 0.5, 0.0, 0.0) else: root = Hlist(root) root.shrink() root.shrink() root_vlist = Vlist([Hlist([root])]) root_vlist.shift_amount = -height * 0.6 hlist = Hlist([root_vlist, Kern(-check.width * 0.5), check, rightside]) return [hlist] def overline(self, toks: ParseResults) -> T.Any: body = toks['body'] state = self.get_state() thickness = state.get_current_underline_thickness() height = body.height - body.shift_amount + thickness * 3.0 depth = body.depth + body.shift_amount rightside = Vlist([Hrule(state), Glue('fill'), Hlist([body])]) rightside.vpack(height + state.fontsize * state.dpi / (100.0 * 12.0), 'exactly', depth) hlist = Hlist([rightside]) return [hlist] def _auto_sized_delimiter(self, front: str, middle: list[Box | Char | str], back: str) -> T.Any: state = self.get_state() if len(middle): height = max([x.height for x in middle if not isinstance(x, str)]) depth = max([x.depth for x in middle if not isinstance(x, str)]) factor = None for (idx, el) in enumerate(middle): if el == '\\middle': c = T.cast(str, middle[idx + 1]) if c != '.': middle[idx + 1] = AutoHeightChar(c, height, depth, state, factor=factor) else: middle.remove(c) del middle[idx] middle_part = T.cast(list[Box | Char], middle) else: height = 0 depth = 0 factor = 1.0 middle_part = [] parts: list[Node] = [] if front != '.': parts.append(AutoHeightChar(front, height, depth, state, factor=factor)) parts.extend(middle_part) if back != '.': parts.append(AutoHeightChar(back, height, depth, state, factor=factor)) hlist = Hlist(parts) return hlist def auto_delim(self, toks: ParseResults) -> T.Any: return self._auto_sized_delimiter(toks['left'], toks['mid'].asList() if 'mid' in toks else [], toks['right']) def boldsymbol(self, toks: ParseResults) -> T.Any: self.push_state() state = self.get_state() hlist: list[Node] = [] name = toks['value'] for c in name: if isinstance(c, Hlist): k = c.children[1] if isinstance(k, Char): k.font = 'bf' k._update_metrics() hlist.append(c) elif isinstance(c, Char): c.font = 'bf' if c.c in self._latin_alphabets or c.c[1:] in self._small_greek: c.font = 'bfit' c._update_metrics() c._update_metrics() hlist.append(c) else: hlist.append(c) self.pop_state() return Hlist(hlist) def substack(self, toks: ParseResults) -> T.Any: parts = toks['parts'] state = self.get_state() thickness = state.get_current_underline_thickness() hlist = [Hlist(k) for k in parts[0]] max_width = max(map(lambda c: c.width, hlist)) vlist = [] for sub in hlist: cp = HCentered([sub]) cp.hpack(max_width, 'exactly') vlist.append(cp) stack = [val for pair in zip(vlist, [Vbox(0, thickness * 2)] * len(vlist)) for val in pair] del stack[-1] vlt = Vlist(stack) result = [Hlist([vlt])] return result # File: matplotlib-main/lib/matplotlib/_mathtext_data.py """""" from __future__ import annotations from typing import overload latex_to_bakoma = {'\\__sqrt__': ('cmex10', 112), '\\bigcap': ('cmex10', 92), '\\bigcup': ('cmex10', 91), '\\bigodot': ('cmex10', 75), '\\bigoplus': ('cmex10', 77), '\\bigotimes': ('cmex10', 79), '\\biguplus': ('cmex10', 93), '\\bigvee': ('cmex10', 95), '\\bigwedge': ('cmex10', 94), '\\coprod': ('cmex10', 97), '\\int': ('cmex10', 90), '\\langle': ('cmex10', 173), '\\leftangle': ('cmex10', 173), '\\leftbrace': ('cmex10', 169), '\\oint': ('cmex10', 73), '\\prod': ('cmex10', 89), '\\rangle': ('cmex10', 174), '\\rightangle': ('cmex10', 174), '\\rightbrace': ('cmex10', 170), '\\sum': ('cmex10', 88), '\\widehat': ('cmex10', 98), '\\widetilde': ('cmex10', 101), '\\{': ('cmex10', 169), '\\}': ('cmex10', 170), '{': ('cmex10', 169), '}': ('cmex10', 170), ',': ('cmmi10', 59), '.': ('cmmi10', 58), '/': ('cmmi10', 61), '<': ('cmmi10', 60), '>': ('cmmi10', 62), '\\alpha': ('cmmi10', 174), '\\beta': ('cmmi10', 175), '\\chi': ('cmmi10', 194), '\\combiningrightarrowabove': ('cmmi10', 126), '\\delta': ('cmmi10', 177), '\\ell': ('cmmi10', 96), '\\epsilon': ('cmmi10', 178), '\\eta': ('cmmi10', 180), '\\flat': ('cmmi10', 91), '\\frown': ('cmmi10', 95), '\\gamma': ('cmmi10', 176), '\\imath': ('cmmi10', 123), '\\iota': ('cmmi10', 182), '\\jmath': ('cmmi10', 124), '\\kappa': ('cmmi10', 8729), '\\lambda': ('cmmi10', 184), '\\leftharpoondown': ('cmmi10', 41), '\\leftharpoonup': ('cmmi10', 40), '\\mu': ('cmmi10', 185), '\\natural': ('cmmi10', 92), '\\nu': ('cmmi10', 186), '\\omega': ('cmmi10', 33), '\\phi': ('cmmi10', 193), '\\pi': ('cmmi10', 188), '\\psi': ('cmmi10', 195), '\\rho': ('cmmi10', 189), '\\rightharpoondown': ('cmmi10', 43), '\\rightharpoonup': ('cmmi10', 42), '\\sharp': ('cmmi10', 93), '\\sigma': ('cmmi10', 190), '\\smile': ('cmmi10', 94), '\\tau': ('cmmi10', 191), '\\theta': ('cmmi10', 181), '\\triangleleft': ('cmmi10', 47), '\\triangleright': ('cmmi10', 46), '\\upsilon': ('cmmi10', 192), '\\varepsilon': ('cmmi10', 34), '\\varphi': ('cmmi10', 39), '\\varrho': ('cmmi10', 37), '\\varsigma': ('cmmi10', 38), '\\vartheta': ('cmmi10', 35), '\\wp': ('cmmi10', 125), '\\xi': ('cmmi10', 187), '\\zeta': ('cmmi10', 179), '!': ('cmr10', 33), '%': ('cmr10', 37), '&': ('cmr10', 38), '(': ('cmr10', 40), ')': ('cmr10', 41), '+': ('cmr10', 43), '0': ('cmr10', 48), '1': ('cmr10', 49), '2': ('cmr10', 50), '3': ('cmr10', 51), '4': ('cmr10', 52), '5': ('cmr10', 53), '6': ('cmr10', 54), '7': ('cmr10', 55), '8': ('cmr10', 56), '9': ('cmr10', 57), ':': ('cmr10', 58), ';': ('cmr10', 59), '=': ('cmr10', 61), '?': ('cmr10', 63), '@': ('cmr10', 64), '[': ('cmr10', 91), '\\#': ('cmr10', 35), '\\$': ('cmr10', 36), '\\%': ('cmr10', 37), '\\Delta': ('cmr10', 162), '\\Gamma': ('cmr10', 161), '\\Lambda': ('cmr10', 164), '\\Omega': ('cmr10', 173), '\\Phi': ('cmr10', 169), '\\Pi': ('cmr10', 166), '\\Psi': ('cmr10', 170), '\\Sigma': ('cmr10', 167), '\\Theta': ('cmr10', 163), '\\Upsilon': ('cmr10', 168), '\\Xi': ('cmr10', 165), '\\circumflexaccent': ('cmr10', 94), '\\combiningacuteaccent': ('cmr10', 182), '\\combiningbreve': ('cmr10', 184), '\\combiningdiaeresis': ('cmr10', 196), '\\combiningdotabove': ('cmr10', 95), '\\combininggraveaccent': ('cmr10', 181), '\\combiningoverline': ('cmr10', 185), '\\combiningtilde': ('cmr10', 126), '\\leftbracket': ('cmr10', 91), '\\leftparen': ('cmr10', 40), '\\rightbracket': ('cmr10', 93), '\\rightparen': ('cmr10', 41), '\\widebar': ('cmr10', 185), ']': ('cmr10', 93), '*': ('cmsy10', 164), '−': ('cmsy10', 161), '\\Downarrow': ('cmsy10', 43), '\\Im': ('cmsy10', 61), '\\Leftarrow': ('cmsy10', 40), '\\Leftrightarrow': ('cmsy10', 44), '\\P': ('cmsy10', 123), '\\Re': ('cmsy10', 60), '\\Rightarrow': ('cmsy10', 41), '\\S': ('cmsy10', 120), '\\Uparrow': ('cmsy10', 42), '\\Updownarrow': ('cmsy10', 109), '\\Vert': ('cmsy10', 107), '\\aleph': ('cmsy10', 64), '\\approx': ('cmsy10', 188), '\\ast': ('cmsy10', 164), '\\asymp': ('cmsy10', 179), '\\backslash': ('cmsy10', 110), '\\bigcirc': ('cmsy10', 176), '\\bigtriangledown': ('cmsy10', 53), '\\bigtriangleup': ('cmsy10', 52), '\\bot': ('cmsy10', 63), '\\bullet': ('cmsy10', 178), '\\cap': ('cmsy10', 92), '\\cdot': ('cmsy10', 162), '\\circ': ('cmsy10', 177), '\\clubsuit': ('cmsy10', 124), '\\cup': ('cmsy10', 91), '\\dag': ('cmsy10', 121), '\\dashv': ('cmsy10', 97), '\\ddag': ('cmsy10', 122), '\\diamond': ('cmsy10', 166), '\\diamondsuit': ('cmsy10', 125), '\\div': ('cmsy10', 165), '\\downarrow': ('cmsy10', 35), '\\emptyset': ('cmsy10', 59), '\\equiv': ('cmsy10', 180), '\\exists': ('cmsy10', 57), '\\forall': ('cmsy10', 56), '\\geq': ('cmsy10', 184), '\\gg': ('cmsy10', 192), '\\heartsuit': ('cmsy10', 126), '\\in': ('cmsy10', 50), '\\infty': ('cmsy10', 49), '\\lbrace': ('cmsy10', 102), '\\lceil': ('cmsy10', 100), '\\leftarrow': ('cmsy10', 195), '\\leftrightarrow': ('cmsy10', 36), '\\leq': ('cmsy10', 8729), '\\lfloor': ('cmsy10', 98), '\\ll': ('cmsy10', 191), '\\mid': ('cmsy10', 106), '\\mp': ('cmsy10', 168), '\\nabla': ('cmsy10', 114), '\\nearrow': ('cmsy10', 37), '\\neg': ('cmsy10', 58), '\\ni': ('cmsy10', 51), '\\nwarrow': ('cmsy10', 45), '\\odot': ('cmsy10', 175), '\\ominus': ('cmsy10', 170), '\\oplus': ('cmsy10', 169), '\\oslash': ('cmsy10', 174), '\\otimes': ('cmsy10', 173), '\\pm': ('cmsy10', 167), '\\prec': ('cmsy10', 193), '\\preceq': ('cmsy10', 185), '\\prime': ('cmsy10', 48), '\\propto': ('cmsy10', 47), '\\rbrace': ('cmsy10', 103), '\\rceil': ('cmsy10', 101), '\\rfloor': ('cmsy10', 99), '\\rightarrow': ('cmsy10', 33), '\\searrow': ('cmsy10', 38), '\\sim': ('cmsy10', 187), '\\simeq': ('cmsy10', 39), '\\slash': ('cmsy10', 54), '\\spadesuit': ('cmsy10', 196), '\\sqcap': ('cmsy10', 117), '\\sqcup': ('cmsy10', 116), '\\sqsubseteq': ('cmsy10', 118), '\\sqsupseteq': ('cmsy10', 119), '\\subset': ('cmsy10', 189), '\\subseteq': ('cmsy10', 181), '\\succ': ('cmsy10', 194), '\\succeq': ('cmsy10', 186), '\\supset': ('cmsy10', 190), '\\supseteq': ('cmsy10', 182), '\\swarrow': ('cmsy10', 46), '\\times': ('cmsy10', 163), '\\to': ('cmsy10', 33), '\\top': ('cmsy10', 62), '\\uparrow': ('cmsy10', 34), '\\updownarrow': ('cmsy10', 108), '\\uplus': ('cmsy10', 93), '\\vdash': ('cmsy10', 96), '\\vee': ('cmsy10', 95), '\\vert': ('cmsy10', 106), '\\wedge': ('cmsy10', 94), '\\wr': ('cmsy10', 111), '\\|': ('cmsy10', 107), '|': ('cmsy10', 106), '\\_': ('cmtt10', 95)} type12uni = {'aring': 229, 'quotedblright': 8221, 'V': 86, 'dollar': 36, 'four': 52, 'Yacute': 221, 'P': 80, 'underscore': 95, 'p': 112, 'Otilde': 213, 'perthousand': 8240, 'zero': 48, 'dotlessi': 305, 'Scaron': 352, 'zcaron': 382, 'egrave': 232, 'section': 167, 'Icircumflex': 206, 'ntilde': 241, 'ampersand': 38, 'dotaccent': 729, 'degree': 176, 'K': 75, 'acircumflex': 226, 'Aring': 197, 'k': 107, 'smalltilde': 732, 'Agrave': 192, 'divide': 247, 'ocircumflex': 244, 'asciitilde': 126, 'two': 50, 'E': 69, 'scaron': 353, 'F': 70, 'bracketleft': 91, 'asciicircum': 94, 'f': 102, 'ordmasculine': 186, 'mu': 181, 'paragraph': 182, 'nine': 57, 'v': 118, 'guilsinglleft': 8249, 'backslash': 92, 'six': 54, 'A': 65, 'icircumflex': 238, 'a': 97, 'ogonek': 731, 'q': 113, 'oacute': 243, 'ograve': 242, 'edieresis': 235, 'comma': 44, 'otilde': 245, 'guillemotright': 187, 'ecircumflex': 234, 'greater': 62, 'uacute': 250, 'L': 76, 'bullet': 8226, 'cedilla': 184, 'ydieresis': 255, 'l': 108, 'logicalnot': 172, 'exclamdown': 161, 'endash': 8211, 'agrave': 224, 'Adieresis': 196, 'germandbls': 223, 'Odieresis': 214, 'space': 32, 'quoteright': 8217, 'ucircumflex': 251, 'G': 71, 'quoteleft': 8216, 'W': 87, 'Q': 81, 'g': 103, 'w': 119, 'question': 63, 'one': 49, 'ring': 730, 'figuredash': 8210, 'B': 66, 'iacute': 237, 'Ydieresis': 376, 'R': 82, 'b': 98, 'r': 114, 'Ccedilla': 199, 'minus': 8722, 'Lslash': 321, 'Uacute': 218, 'yacute': 253, 'Ucircumflex': 219, 'quotedbl': 34, 'onehalf': 189, 'Thorn': 222, 'M': 77, 'eight': 56, 'multiply': 215, 'grave': 96, 'Ocircumflex': 212, 'm': 109, 'Ugrave': 217, 'guilsinglright': 8250, 'Ntilde': 209, 'questiondown': 191, 'Atilde': 195, 'ccedilla': 231, 'Z': 90, 'copyright': 169, 'yen': 165, 'Eacute': 201, 'H': 72, 'X': 88, 'Idieresis': 207, 'bar': 124, 'h': 104, 'x': 120, 'udieresis': 252, 'ordfeminine': 170, 'braceleft': 123, 'macron': 175, 'atilde': 227, 'Acircumflex': 194, 'Oslash': 216, 'C': 67, 'quotedblleft': 8220, 'S': 83, 'exclam': 33, 'Zcaron': 381, 'equal': 61, 's': 115, 'eth': 240, 'Egrave': 200, 'hyphen': 45, 'period': 46, 'igrave': 236, 'colon': 58, 'Ecircumflex': 202, 'trademark': 8482, 'Aacute': 193, 'cent': 162, 'lslash': 322, 'c': 99, 'N': 78, 'breve': 728, 'Oacute': 211, 'guillemotleft': 171, 'n': 110, 'idieresis': 239, 'braceright': 125, 'seven': 55, 'brokenbar': 166, 'ugrave': 249, 'periodcentered': 183, 'sterling': 163, 'I': 73, 'Y': 89, 'Eth': 208, 'emdash': 8212, 'i': 105, 'daggerdbl': 8225, 'y': 121, 'plusminus': 177, 'less': 60, 'Udieresis': 220, 'D': 68, 'five': 53, 'T': 84, 'oslash': 248, 'acute': 180, 'd': 100, 'OE': 338, 'Igrave': 204, 't': 116, 'parenright': 41, 'adieresis': 228, 'quotesingle': 39, 'twodotenleader': 8229, 'slash': 47, 'ellipsis': 8230, 'numbersign': 35, 'odieresis': 246, 'O': 79, 'oe': 339, 'o': 111, 'Edieresis': 203, 'plus': 43, 'dagger': 8224, 'three': 51, 'hungarumlaut': 733, 'parenleft': 40, 'fraction': 8260, 'registered': 174, 'J': 74, 'dieresis': 168, 'Ograve': 210, 'j': 106, 'z': 122, 'ae': 230, 'semicolon': 59, 'at': 64, 'Iacute': 205, 'percent': 37, 'bracketright': 93, 'AE': 198, 'asterisk': 42, 'aacute': 225, 'U': 85, 'eacute': 233, 'e': 101, 'thorn': 254, 'u': 117} uni2type1 = {v: k for (k, v) in type12uni.items()} tex2uni = {'#': 35, '$': 36, '%': 37, 'AA': 197, 'AE': 198, 'BbbC': 8450, 'BbbN': 8469, 'BbbP': 8473, 'BbbQ': 8474, 'BbbR': 8477, 'BbbZ': 8484, 'Bumpeq': 8782, 'Cap': 8914, 'Colon': 8759, 'Cup': 8915, 'DH': 208, 'Delta': 916, 'Doteq': 8785, 'Downarrow': 8659, 'Equiv': 8803, 'Finv': 8498, 'Game': 8513, 'Gamma': 915, 'H': 779, 'Im': 8465, 'Join': 10781, 'L': 321, 'Lambda': 923, 'Ldsh': 8626, 'Leftarrow': 8656, 'Leftrightarrow': 8660, 'Lleftarrow': 8666, 'Longleftarrow': 10232, 'Longleftrightarrow': 10234, 'Longrightarrow': 10233, 'Lsh': 8624, 'Nearrow': 8663, 'Nwarrow': 8662, 'O': 216, 'OE': 338, 'Omega': 937, 'P': 182, 'Phi': 934, 'Pi': 928, 'Psi': 936, 'QED': 8718, 'Rdsh': 8627, 'Re': 8476, 'Rightarrow': 8658, 'Rrightarrow': 8667, 'Rsh': 8625, 'S': 167, 'Searrow': 8664, 'Sigma': 931, 'Subset': 8912, 'Supset': 8913, 'Swarrow': 8665, 'Theta': 920, 'Thorn': 222, 'Uparrow': 8657, 'Updownarrow': 8661, 'Upsilon': 933, 'Vdash': 8873, 'Vert': 8214, 'Vvdash': 8874, 'Xi': 926, '_': 95, '__sqrt__': 8730, 'aa': 229, 'ac': 8766, 'acute': 769, 'acwopencirclearrow': 8634, 'adots': 8944, 'ae': 230, 'aleph': 8501, 'alpha': 945, 'amalg': 10815, 'angle': 8736, 'approx': 8776, 'approxeq': 8778, 'approxident': 8779, 'arceq': 8792, 'ast': 8727, 'asterisk': 42, 'asymp': 8781, 'backcong': 8780, 'backepsilon': 1014, 'backprime': 8245, 'backsim': 8765, 'backsimeq': 8909, 'backslash': 92, 'bagmember': 8959, 'bar': 772, 'barleftarrow': 8676, 'barvee': 8893, 'barwedge': 8892, 'because': 8757, 'beta': 946, 'beth': 8502, 'between': 8812, 'bigcap': 8898, 'bigcirc': 9675, 'bigcup': 8899, 'bigodot': 10752, 'bigoplus': 10753, 'bigotimes': 10754, 'bigsqcup': 10758, 'bigstar': 9733, 'bigtriangledown': 9661, 'bigtriangleup': 9651, 'biguplus': 10756, 'bigvee': 8897, 'bigwedge': 8896, 'blacksquare': 9632, 'blacktriangle': 9652, 'blacktriangledown': 9662, 'blacktriangleleft': 9664, 'blacktriangleright': 9654, 'bot': 8869, 'bowtie': 8904, 'boxbar': 9707, 'boxdot': 8865, 'boxminus': 8863, 'boxplus': 8862, 'boxtimes': 8864, 'breve': 774, 'bullet': 8729, 'bumpeq': 8783, 'c': 807, 'candra': 784, 'cap': 8745, 'carriagereturn': 8629, 'cdot': 8901, 'cdotp': 183, 'cdots': 8943, 'cent': 162, 'check': 780, 'checkmark': 10003, 'chi': 967, 'circ': 8728, 'circeq': 8791, 'circlearrowleft': 8634, 'circlearrowright': 8635, 'circledR': 174, 'circledS': 9416, 'circledast': 8859, 'circledcirc': 8858, 'circleddash': 8861, 'circumflexaccent': 770, 'clubsuit': 9827, 'clubsuitopen': 9831, 'colon': 58, 'coloneq': 8788, 'combiningacuteaccent': 769, 'combiningbreve': 774, 'combiningdiaeresis': 776, 'combiningdotabove': 775, 'combiningfourdotsabove': 8412, 'combininggraveaccent': 768, 'combiningoverline': 772, 'combiningrightarrowabove': 8407, 'combiningthreedotsabove': 8411, 'combiningtilde': 771, 'complement': 8705, 'cong': 8773, 'coprod': 8720, 'copyright': 169, 'cup': 8746, 'cupdot': 8845, 'cupleftarrow': 8844, 'curlyeqprec': 8926, 'curlyeqsucc': 8927, 'curlyvee': 8910, 'curlywedge': 8911, 'curvearrowleft': 8630, 'curvearrowright': 8631, 'cwopencirclearrow': 8635, 'd': 803, 'dag': 8224, 'dagger': 8224, 'daleth': 8504, 'danger': 9761, 'dashleftarrow': 10510, 'dashrightarrow': 10511, 'dashv': 8867, 'ddag': 8225, 'ddagger': 8225, 'ddddot': 8412, 'dddot': 8411, 'ddot': 776, 'ddots': 8945, 'degree': 176, 'delta': 948, 'dh': 240, 'diamond': 8900, 'diamondsuit': 9826, 'digamma': 989, 'disin': 8946, 'div': 247, 'divideontimes': 8903, 'dot': 775, 'doteq': 8784, 'doteqdot': 8785, 'dotminus': 8760, 'dotplus': 8724, 'dots': 8230, 'dotsminusdots': 8762, 'doublebarwedge': 8966, 'downarrow': 8595, 'downdownarrows': 8650, 'downharpoonleft': 8643, 'downharpoonright': 8642, 'downzigzagarrow': 8623, 'ell': 8467, 'emdash': 8212, 'emptyset': 8709, 'endash': 8211, 'epsilon': 949, 'eqcirc': 8790, 'eqcolon': 8789, 'eqdef': 8797, 'eqgtr': 8925, 'eqless': 8924, 'eqsim': 8770, 'eqslantgtr': 10902, 'eqslantless': 10901, 'equal': 61, 'equalparallel': 8917, 'equiv': 8801, 'eta': 951, 'eth': 240, 'exists': 8707, 'fallingdotseq': 8786, 'flat': 9837, 'forall': 8704, 'frakC': 8493, 'frakZ': 8488, 'frown': 8994, 'gamma': 947, 'geq': 8805, 'geqq': 8807, 'geqslant': 10878, 'gg': 8811, 'ggg': 8921, 'gimel': 8503, 'gnapprox': 10890, 'gneqq': 8809, 'gnsim': 8935, 'grave': 768, 'greater': 62, 'gtrapprox': 10886, 'gtrdot': 8919, 'gtreqless': 8923, 'gtreqqless': 10892, 'gtrless': 8823, 'gtrsim': 8819, 'guillemotleft': 171, 'guillemotright': 187, 'guilsinglleft': 8249, 'guilsinglright': 8250, 'hat': 770, 'hbar': 295, 'heartsuit': 9825, 'hermitmatrix': 8889, 'hookleftarrow': 8617, 'hookrightarrow': 8618, 'hslash': 8463, 'i': 305, 'iiiint': 10764, 'iiint': 8749, 'iint': 8748, 'imageof': 8887, 'imath': 305, 'in': 8712, 'increment': 8710, 'infty': 8734, 'int': 8747, 'intercal': 8890, 'invnot': 8976, 'iota': 953, 'isinE': 8953, 'isindot': 8949, 'isinobar': 8951, 'isins': 8948, 'isinvb': 8952, 'jmath': 567, 'k': 808, 'kappa': 954, 'kernelcontraction': 8763, 'l': 322, 'lambda': 955, 'lambdabar': 411, 'langle': 10216, 'lasp': 701, 'lbrace': 123, 'lbrack': 91, 'lceil': 8968, 'ldots': 8230, 'leadsto': 8669, 'leftarrow': 8592, 'leftarrowtail': 8610, 'leftbrace': 123, 'leftharpoonaccent': 8400, 'leftharpoondown': 8637, 'leftharpoonup': 8636, 'leftleftarrows': 8647, 'leftparen': 40, 'leftrightarrow': 8596, 'leftrightarrows': 8646, 'leftrightharpoons': 8651, 'leftrightsquigarrow': 8621, 'leftsquigarrow': 8604, 'leftthreetimes': 8907, 'leq': 8804, 'leqq': 8806, 'leqslant': 10877, 'less': 60, 'lessapprox': 10885, 'lessdot': 8918, 'lesseqgtr': 8922, 'lesseqqgtr': 10891, 'lessgtr': 8822, 'lesssim': 8818, 'lfloor': 8970, 'lgroup': 10222, 'lhd': 9665, 'll': 8810, 'llcorner': 8990, 'lll': 8920, 'lnapprox': 10889, 'lneqq': 8808, 'lnsim': 8934, 'longleftarrow': 10229, 'longleftrightarrow': 10231, 'longmapsto': 10236, 'longrightarrow': 10230, 'looparrowleft': 8619, 'looparrowright': 8620, 'lq': 8216, 'lrcorner': 8991, 'ltimes': 8905, 'macron': 175, 'maltese': 10016, 'mapsdown': 8615, 'mapsfrom': 8612, 'mapsto': 8614, 'mapsup': 8613, 'measeq': 8798, 'measuredangle': 8737, 'measuredrightangle': 8894, 'merge': 10837, 'mho': 8487, 'mid': 8739, 'minus': 8722, 'minuscolon': 8761, 'models': 8871, 'mp': 8723, 'mu': 956, 'multimap': 8888, 'nLeftarrow': 8653, 'nLeftrightarrow': 8654, 'nRightarrow': 8655, 'nVDash': 8879, 'nVdash': 8878, 'nabla': 8711, 'napprox': 8777, 'natural': 9838, 'ncong': 8775, 'ne': 8800, 'nearrow': 8599, 'neg': 172, 'neq': 8800, 'nequiv': 8802, 'nexists': 8708, 'ngeq': 8817, 'ngtr': 8815, 'ngtrless': 8825, 'ngtrsim': 8821, 'ni': 8715, 'niobar': 8958, 'nis': 8956, 'nisd': 8954, 'nleftarrow': 8602, 'nleftrightarrow': 8622, 'nleq': 8816, 'nless': 8814, 'nlessgtr': 8824, 'nlesssim': 8820, 'nmid': 8740, 'not': 824, 'notin': 8713, 'notsmallowns': 8716, 'nparallel': 8742, 'nprec': 8832, 'npreccurlyeq': 8928, 'nrightarrow': 8603, 'nsim': 8769, 'nsimeq': 8772, 'nsqsubseteq': 8930, 'nsqsupseteq': 8931, 'nsubset': 8836, 'nsubseteq': 8840, 'nsucc': 8833, 'nsucccurlyeq': 8929, 'nsupset': 8837, 'nsupseteq': 8841, 'ntriangleleft': 8938, 'ntrianglelefteq': 8940, 'ntriangleright': 8939, 'ntrianglerighteq': 8941, 'nu': 957, 'nvDash': 8877, 'nvdash': 8876, 'nwarrow': 8598, 'o': 248, 'obar': 9021, 'ocirc': 778, 'odot': 8857, 'oe': 339, 'oequal': 8860, 'oiiint': 8752, 'oiint': 8751, 'oint': 8750, 'omega': 969, 'ominus': 8854, 'oplus': 8853, 'origof': 8886, 'oslash': 8856, 'otimes': 8855, 'overarc': 785, 'overleftarrow': 8406, 'overleftrightarrow': 8417, 'parallel': 8741, 'partial': 8706, 'perp': 10178, 'perthousand': 8240, 'phi': 981, 'pi': 960, 'pitchfork': 8916, 'plus': 43, 'pm': 177, 'prec': 8826, 'precapprox': 10935, 'preccurlyeq': 8828, 'preceq': 8828, 'precnapprox': 10937, 'precnsim': 8936, 'precsim': 8830, 'prime': 8242, 'prod': 8719, 'propto': 8733, 'prurel': 8880, 'psi': 968, 'quad': 8195, 'questeq': 8799, 'rangle': 10217, 'rasp': 700, 'ratio': 8758, 'rbrace': 125, 'rbrack': 93, 'rceil': 8969, 'rfloor': 8971, 'rgroup': 10223, 'rhd': 9655, 'rho': 961, 'rightModels': 8875, 'rightangle': 8735, 'rightarrow': 8594, 'rightarrowbar': 8677, 'rightarrowtail': 8611, 'rightassert': 8870, 'rightbrace': 125, 'rightharpoonaccent': 8401, 'rightharpoondown': 8641, 'rightharpoonup': 8640, 'rightleftarrows': 8644, 'rightleftharpoons': 8652, 'rightparen': 41, 'rightrightarrows': 8649, 'rightsquigarrow': 8605, 'rightthreetimes': 8908, 'rightzigzagarrow': 8669, 'ring': 730, 'risingdotseq': 8787, 'rq': 8217, 'rtimes': 8906, 'scrB': 8492, 'scrE': 8496, 'scrF': 8497, 'scrH': 8459, 'scrI': 8464, 'scrL': 8466, 'scrM': 8499, 'scrR': 8475, 'scre': 8495, 'scrg': 8458, 'scro': 8500, 'scurel': 8881, 'searrow': 8600, 'setminus': 8726, 'sharp': 9839, 'sigma': 963, 'sim': 8764, 'simeq': 8771, 'simneqq': 8774, 'sinewave': 8767, 'slash': 8725, 'smallin': 8714, 'smallintclockwise': 8753, 'smallointctrcclockwise': 8755, 'smallowns': 8717, 'smallsetminus': 8726, 'smallvarointclockwise': 8754, 'smile': 8995, 'solbar': 9023, 'spadesuit': 9824, 'spadesuitopen': 9828, 'sphericalangle': 8738, 'sqcap': 8851, 'sqcup': 8852, 'sqsubset': 8847, 'sqsubseteq': 8849, 'sqsubsetneq': 8932, 'sqsupset': 8848, 'sqsupseteq': 8850, 'sqsupsetneq': 8933, 'ss': 223, 'star': 8902, 'stareq': 8795, 'sterling': 163, 'subset': 8834, 'subseteq': 8838, 'subseteqq': 10949, 'subsetneq': 8842, 'subsetneqq': 10955, 'succ': 8827, 'succapprox': 10936, 'succcurlyeq': 8829, 'succeq': 8829, 'succnapprox': 10938, 'succnsim': 8937, 'succsim': 8831, 'sum': 8721, 'supset': 8835, 'supseteq': 8839, 'supseteqq': 10950, 'supsetneq': 8843, 'supsetneqq': 10956, 'swarrow': 8601, 't': 865, 'tau': 964, 'textasciiacute': 180, 'textasciicircum': 94, 'textasciigrave': 96, 'textasciitilde': 126, 'textexclamdown': 161, 'textquestiondown': 191, 'textquotedblleft': 8220, 'textquotedblright': 8221, 'therefore': 8756, 'theta': 952, 'thickspace': 8197, 'thorn': 254, 'tilde': 771, 'times': 215, 'to': 8594, 'top': 8868, 'triangle': 9651, 'triangledown': 9663, 'triangleeq': 8796, 'triangleleft': 9665, 'trianglelefteq': 8884, 'triangleq': 8796, 'triangleright': 9655, 'trianglerighteq': 8885, 'turnednot': 8985, 'twoheaddownarrow': 8609, 'twoheadleftarrow': 8606, 'twoheadrightarrow': 8608, 'twoheaduparrow': 8607, 'ulcorner': 8988, 'underbar': 817, 'unlhd': 8884, 'unrhd': 8885, 'uparrow': 8593, 'updownarrow': 8597, 'updownarrowbar': 8616, 'updownarrows': 8645, 'upharpoonleft': 8639, 'upharpoonright': 8638, 'uplus': 8846, 'upsilon': 965, 'upuparrows': 8648, 'urcorner': 8989, 'vDash': 8872, 'varepsilon': 949, 'varisinobar': 8950, 'varisins': 8947, 'varkappa': 1008, 'varlrtriangle': 8895, 'varniobar': 8957, 'varnis': 8955, 'varnothing': 8709, 'varphi': 966, 'varpi': 982, 'varpropto': 8733, 'varrho': 1009, 'varsigma': 962, 'vartheta': 977, 'vartriangle': 9653, 'vartriangleleft': 8882, 'vartriangleright': 8883, 'vdash': 8866, 'vdots': 8942, 'vec': 8407, 'vee': 8744, 'veebar': 8891, 'veeeq': 8794, 'vert': 124, 'wedge': 8743, 'wedgeq': 8793, 'widebar': 773, 'widehat': 770, 'widetilde': 771, 'wp': 8472, 'wr': 8768, 'xi': 958, 'yen': 165, 'zeta': 950, '{': 123, '|': 8214, '}': 125} _EntryTypeIn = tuple[str, str, str, str | int] _EntryTypeOut = tuple[int, int, str, int] _stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeIn]] | list[_EntryTypeIn]] = {'bb': {'rm': [('0', '9', 'rm', '𝟘'), ('A', 'B', 'rm', '𝔸'), ('C', 'C', 'rm', 'ℂ'), ('D', 'G', 'rm', '𝔻'), ('H', 'H', 'rm', 'ℍ'), ('I', 'M', 'rm', '𝕀'), ('N', 'N', 'rm', 'ℕ'), ('O', 'O', 'rm', '𝕆'), ('P', 'Q', 'rm', 'ℙ'), ('R', 'R', 'rm', 'ℝ'), ('S', 'Y', 'rm', '𝕊'), ('Z', 'Z', 'rm', 'ℤ'), ('a', 'z', 'rm', '𝕒'), ('Γ', 'Γ', 'rm', 'ℾ'), ('Π', 'Π', 'rm', 'ℿ'), ('Σ', 'Σ', 'rm', '⅀'), ('γ', 'γ', 'rm', 'ℽ'), ('π', 'π', 'rm', 'ℼ')], 'it': [('0', '9', 'rm', '𝟘'), ('A', 'B', 'it', 57684), ('C', 'C', 'it', 'ℂ'), ('D', 'D', 'it', 'ⅅ'), ('E', 'G', 'it', 57686), ('H', 'H', 'it', 'ℍ'), ('I', 'M', 'it', 57689), ('N', 'N', 'it', 'ℕ'), ('O', 'O', 'it', 57694), ('P', 'Q', 'it', 'ℙ'), ('R', 'R', 'it', 'ℝ'), ('S', 'Y', 'it', 57695), ('Z', 'Z', 'it', 'ℤ'), ('a', 'c', 'it', 57702), ('d', 'e', 'it', 'ⅆ'), ('f', 'h', 'it', 57705), ('i', 'j', 'it', 'ⅈ'), ('k', 'z', 'it', 57708), ('Γ', 'Γ', 'it', 'ℾ'), ('Π', 'Π', 'it', 'ℿ'), ('Σ', 'Σ', 'it', '⅀'), ('γ', 'γ', 'it', 'ℽ'), ('π', 'π', 'it', 'ℼ')], 'bf': [('0', '9', 'rm', '𝟘'), ('A', 'B', 'bf', 58250), ('C', 'C', 'bf', 'ℂ'), ('D', 'D', 'bf', 'ⅅ'), ('E', 'G', 'bf', 58253), ('H', 'H', 'bf', 'ℍ'), ('I', 'M', 'bf', 58256), ('N', 'N', 'bf', 'ℕ'), ('O', 'O', 'bf', 58261), ('P', 'Q', 'bf', 'ℙ'), ('R', 'R', 'bf', 'ℝ'), ('S', 'Y', 'bf', 58262), ('Z', 'Z', 'bf', 'ℤ'), ('a', 'c', 'bf', 58269), ('d', 'e', 'bf', 'ⅆ'), ('f', 'h', 'bf', 58274), ('i', 'j', 'bf', 'ⅈ'), ('k', 'z', 'bf', 58279), ('Γ', 'Γ', 'bf', 'ℾ'), ('Π', 'Π', 'bf', 'ℿ'), ('Σ', 'Σ', 'bf', '⅀'), ('γ', 'γ', 'bf', 'ℽ'), ('π', 'π', 'bf', 'ℼ')]}, 'cal': [('A', 'Z', 'it', 57901)], 'frak': {'rm': [('A', 'B', 'rm', '𝔄'), ('C', 'C', 'rm', 'ℭ'), ('D', 'G', 'rm', '𝔇'), ('H', 'H', 'rm', 'ℌ'), ('I', 'I', 'rm', 'ℑ'), ('J', 'Q', 'rm', '𝔍'), ('R', 'R', 'rm', 'ℜ'), ('S', 'Y', 'rm', '𝔖'), ('Z', 'Z', 'rm', 'ℨ'), ('a', 'z', 'rm', '𝔞')], 'bf': [('A', 'Z', 'bf', '𝕬'), ('a', 'z', 'bf', '𝖆')]}, 'scr': [('A', 'A', 'it', '𝒜'), ('B', 'B', 'it', 'ℬ'), ('C', 'D', 'it', '𝒞'), ('E', 'F', 'it', 'ℰ'), ('G', 'G', 'it', '𝒢'), ('H', 'H', 'it', 'ℋ'), ('I', 'I', 'it', 'ℐ'), ('J', 'K', 'it', '𝒥'), ('L', 'L', 'it', 'ℒ'), ('M', 'M', 'it', 'ℳ'), ('N', 'Q', 'it', '𝒩'), ('R', 'R', 'it', 'ℛ'), ('S', 'Z', 'it', '𝒮'), ('a', 'd', 'it', '𝒶'), ('e', 'e', 'it', 'ℯ'), ('f', 'f', 'it', '𝒻'), ('g', 'g', 'it', 'ℊ'), ('h', 'n', 'it', '𝒽'), ('o', 'o', 'it', 'ℴ'), ('p', 'z', 'it', '𝓅')], 'sf': {'rm': [('0', '9', 'rm', '𝟢'), ('A', 'Z', 'rm', '𝖠'), ('a', 'z', 'rm', '𝖺'), ('Α', 'Ω', 'rm', 57725), ('α', 'ω', 'rm', 57750), ('ϑ', 'ϑ', 'rm', 57776), ('ϕ', 'ϕ', 'rm', 57777), ('ϖ', 'ϖ', 'rm', 57779), ('ϱ', 'ϱ', 'rm', 57778), ('ϵ', 'ϵ', 'rm', 57775), ('∂', '∂', 'rm', 57724)], 'it': [('0', '9', 'rm', '𝟢'), ('A', 'Z', 'it', '𝘈'), ('a', 'z', 'it', '𝘢'), ('Α', 'Ω', 'rm', 57725), ('α', 'ω', 'it', 57816), ('ϑ', 'ϑ', 'it', 57842), ('ϕ', 'ϕ', 'it', 57843), ('ϖ', 'ϖ', 'it', 57845), ('ϱ', 'ϱ', 'it', 57844), ('ϵ', 'ϵ', 'it', 57841)], 'bf': [('0', '9', 'bf', '𝟬'), ('A', 'Z', 'bf', '𝗔'), ('a', 'z', 'bf', '𝗮'), ('Α', 'Ω', 'bf', '𝝖'), ('α', 'ω', 'bf', '𝝰'), ('ϑ', 'ϑ', 'bf', '𝞋'), ('ϕ', 'ϕ', 'bf', '𝞍'), ('ϖ', 'ϖ', 'bf', '𝞏'), ('ϰ', 'ϰ', 'bf', '𝞌'), ('ϱ', 'ϱ', 'bf', '𝞎'), ('ϵ', 'ϵ', 'bf', '𝞊'), ('∂', '∂', 'bf', '𝞉'), ('∇', '∇', 'bf', '𝝯')], 'bfit': [('A', 'Z', 'bfit', '𝑨'), ('a', 'z', 'bfit', '𝒂'), ('Γ', 'Ω', 'bfit', '𝜞'), ('α', 'ω', 'bfit', '𝜶')]}, 'tt': [('0', '9', 'rm', '𝟶'), ('A', 'Z', 'rm', '𝙰'), ('a', 'z', 'rm', '𝚊')]} @overload def _normalize_stix_fontcodes(d: _EntryTypeIn) -> _EntryTypeOut: ... @overload def _normalize_stix_fontcodes(d: list[_EntryTypeIn]) -> list[_EntryTypeOut]: ... @overload def _normalize_stix_fontcodes(d: dict[str, list[_EntryTypeIn] | dict[str, list[_EntryTypeIn]]]) -> dict[str, list[_EntryTypeOut] | dict[str, list[_EntryTypeOut]]]: ... def _normalize_stix_fontcodes(d): if isinstance(d, tuple): return tuple((ord(x) if isinstance(x, str) and len(x) == 1 else x for x in d)) elif isinstance(d, list): return [_normalize_stix_fontcodes(x) for x in d] elif isinstance(d, dict): return {k: _normalize_stix_fontcodes(v) for (k, v) in d.items()} stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]] stix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts) del _stix_virtual_fonts stix_glyph_fixes = {8914: 8915, 8915: 8914} # File: matplotlib-main/lib/matplotlib/_pylab_helpers.py """""" import atexit from collections import OrderedDict class Gcf: figs = OrderedDict() @classmethod def get_fig_manager(cls, num): manager = cls.figs.get(num, None) if manager is not None: cls.set_active(manager) return manager @classmethod def destroy(cls, num): if all((hasattr(num, attr) for attr in ['num', 'destroy'])): manager = num if cls.figs.get(manager.num) is manager: cls.figs.pop(manager.num) else: try: manager = cls.figs.pop(num) except KeyError: return if hasattr(manager, '_cidgcf'): manager.canvas.mpl_disconnect(manager._cidgcf) manager.destroy() @classmethod def destroy_fig(cls, fig): num = next((manager.num for manager in cls.figs.values() if manager.canvas.figure == fig), None) if num is not None: cls.destroy(num) @classmethod def destroy_all(cls): for manager in list(cls.figs.values()): manager.canvas.mpl_disconnect(manager._cidgcf) manager.destroy() cls.figs.clear() @classmethod def has_fignum(cls, num): return num in cls.figs @classmethod def get_all_fig_managers(cls): return list(cls.figs.values()) @classmethod def get_num_fig_managers(cls): return len(cls.figs) @classmethod def get_active(cls): return next(reversed(cls.figs.values())) if cls.figs else None @classmethod def _set_new_active_manager(cls, manager): if not hasattr(manager, '_cidgcf'): manager._cidgcf = manager.canvas.mpl_connect('button_press_event', lambda event: cls.set_active(manager)) fig = manager.canvas.figure fig.number = manager.num label = fig.get_label() if label: manager.set_window_title(label) cls.set_active(manager) @classmethod def set_active(cls, manager): cls.figs[manager.num] = manager cls.figs.move_to_end(manager.num) @classmethod def draw_all(cls, force=False): for manager in cls.get_all_fig_managers(): if force or manager.canvas.figure.stale: manager.canvas.draw_idle() atexit.register(Gcf.destroy_all) # File: matplotlib-main/lib/matplotlib/_text_helpers.py """""" from __future__ import annotations import dataclasses from . import _api from .ft2font import KERNING_DEFAULT, LOAD_NO_HINTING, FT2Font @dataclasses.dataclass(frozen=True) class LayoutItem: ft_object: FT2Font char: str glyph_idx: int x: float prev_kern: float def warn_on_missing_glyph(codepoint, fontnames): _api.warn_external(f"Glyph {codepoint} ({chr(codepoint).encode('ascii', 'namereplace').decode('ascii')}) missing from font(s) {fontnames}.") block = 'Hebrew' if 1424 <= codepoint <= 1535 else 'Arabic' if 1536 <= codepoint <= 1791 else 'Devanagari' if 2304 <= codepoint <= 2431 else 'Bengali' if 2432 <= codepoint <= 2559 else 'Gurmukhi' if 2560 <= codepoint <= 2687 else 'Gujarati' if 2688 <= codepoint <= 2815 else 'Oriya' if 2816 <= codepoint <= 2943 else 'Tamil' if 2944 <= codepoint <= 3071 else 'Telugu' if 3072 <= codepoint <= 3199 else 'Kannada' if 3200 <= codepoint <= 3327 else 'Malayalam' if 3328 <= codepoint <= 3455 else 'Sinhala' if 3456 <= codepoint <= 3583 else None if block: _api.warn_external(f'Matplotlib currently does not support {block} natively.') def layout(string, font, *, kern_mode=KERNING_DEFAULT): x = 0 prev_glyph_idx = None char_to_font = font._get_fontmap(string) base_font = font for char in string: font = char_to_font.get(char, base_font) glyph_idx = font.get_char_index(ord(char)) kern = base_font.get_kerning(prev_glyph_idx, glyph_idx, kern_mode) / 64 if prev_glyph_idx is not None else 0.0 x += kern glyph = font.load_glyph(glyph_idx, flags=LOAD_NO_HINTING) yield LayoutItem(font, char, glyph_idx, x, kern) x += glyph.linearHoriAdvance / 65536 prev_glyph_idx = glyph_idx # File: matplotlib-main/lib/matplotlib/_tight_bbox.py """""" from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout old_aspect = [] locator_list = [] sentinel = object() for ax in fig.axes: locator = ax.get_axes_locator() if locator is not None: ax.apply_aspect(locator(ax, None)) locator_list.append(locator) current_pos = ax.get_position(original=False).frozen() ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos) if 'apply_aspect' in ax.__dict__: old_aspect.append(ax.apply_aspect) else: old_aspect.append(sentinel) ax.apply_aspect = lambda pos=None: None def restore_bbox(): for (ax, loc, aspect) in zip(fig.axes, locator_list, old_aspect): ax.set_axes_locator(loc) if aspect is sentinel: del ax.apply_aspect else: ax.apply_aspect = aspect fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is None: fixed_dpi = fig.dpi tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size) (x0, y0) = tr.transform(bbox_inches.p0) (w1, h1) = fig.bbox.size * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): (bbox_inches, restore_bbox) = bbox_inches_restore restore_bbox() r = adjust_bbox(fig, bbox_inches, fixed_dpi) return (bbox_inches, r) # File: matplotlib-main/lib/matplotlib/_tight_layout.py """""" import numpy as np import matplotlib as mpl from matplotlib import _api, artist as martist from matplotlib.font_manager import FontProperties from 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): (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 hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin (fig_width_inch, fig_height_inch) = fig.get_size_inches() 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 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): 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): 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: (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) if rect is not None and kwargs is not None: (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 kwargs # File: matplotlib-main/lib/matplotlib/_type1font.py """""" from __future__ import annotations import binascii import functools import logging import re import string import struct import typing as T import numpy as np from matplotlib.cbook import _format_approx from . import _api _log = logging.getLogger(__name__) class _Token: __slots__ = ('pos', 'raw') kind = '?' def __init__(self, pos, raw): _log.debug('type1font._Token %s at %d: %r', self.kind, pos, raw) self.pos = pos self.raw = raw def __str__(self): return f'<{self.kind} {self.raw} @{self.pos}>' def endpos(self): return self.pos + len(self.raw) def is_keyword(self, *names): return False def is_slash_name(self): return False def is_delim(self): return False def is_number(self): return False def value(self): return self.raw class _NameToken(_Token): kind = 'name' def is_slash_name(self): return self.raw.startswith('/') def value(self): return self.raw[1:] class _BooleanToken(_Token): kind = 'boolean' def value(self): return self.raw == 'true' class _KeywordToken(_Token): kind = 'keyword' def is_keyword(self, *names): return self.raw in names class _DelimiterToken(_Token): kind = 'delimiter' def is_delim(self): return True def opposite(self): return {'[': ']', ']': '[', '{': '}', '}': '{', '<<': '>>', '>>': '<<'}[self.raw] class _WhitespaceToken(_Token): kind = 'whitespace' class _StringToken(_Token): kind = 'string' _escapes_re = re.compile('\\\\([\\\\()nrtbf]|[0-7]{1,3})') _replacements = {'\\': '\\', '(': '(', ')': ')', 'n': '\n', 'r': '\r', 't': '\t', 'b': '\x08', 'f': '\x0c'} _ws_re = re.compile('[\x00\t\r\x0c\n ]') @classmethod def _escape(cls, match): group = match.group(1) try: return cls._replacements[group] except KeyError: return chr(int(group, 8)) @functools.lru_cache def value(self): if self.raw[0] == '(': return self._escapes_re.sub(self._escape, self.raw[1:-1]) else: data = self._ws_re.sub('', self.raw[1:-1]) if len(data) % 2 == 1: data += '0' return binascii.unhexlify(data) class _BinaryToken(_Token): kind = 'binary' def value(self): return self.raw[1:] class _NumberToken(_Token): kind = 'number' def is_number(self): return True def value(self): if '.' not in self.raw: return int(self.raw) else: return float(self.raw) def _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]: text = data.decode('ascii', 'replace') whitespace_or_comment_re = re.compile('[\\0\\t\\r\\f\\n ]+|%[^\\r\\n]*') token_re = re.compile('/{0,2}[^]\\0\\t\\r\\f\\n ()<>{}/%[]+') instring_re = re.compile('[()\\\\]') hex_re = re.compile('^<[0-9a-fA-F\\0\\t\\r\\f\\n ]*>$') oct_re = re.compile('[0-7]{1,3}') pos = 0 next_binary: int | None = None while pos < len(text): if next_binary is not None: n = next_binary next_binary = (yield _BinaryToken(pos, data[pos:pos + n])) pos += n continue match = whitespace_or_comment_re.match(text, pos) if match: if not skip_ws: next_binary = (yield _WhitespaceToken(pos, match.group())) pos = match.end() elif text[pos] == '(': start = pos pos += 1 depth = 1 while depth: match = instring_re.search(text, pos) if match is None: raise ValueError(f'Unterminated string starting at {start}') pos = match.end() if match.group() == '(': depth += 1 elif match.group() == ')': depth -= 1 else: char = text[pos] if char in '\\()nrtbf': pos += 1 else: octal = oct_re.match(text, pos) if octal: pos = octal.end() else: pass next_binary = (yield _StringToken(start, text[start:pos])) elif text[pos:pos + 2] in ('<<', '>>'): next_binary = (yield _DelimiterToken(pos, text[pos:pos + 2])) pos += 2 elif text[pos] == '<': start = pos try: pos = text.index('>', pos) + 1 except ValueError as e: raise ValueError(f'Unterminated hex string starting at {start}') from e if not hex_re.match(text[start:pos]): raise ValueError(f'Malformed hex string starting at {start}') next_binary = (yield _StringToken(pos, text[start:pos])) else: match = token_re.match(text, pos) if match: raw = match.group() if raw.startswith('/'): next_binary = (yield _NameToken(pos, raw)) elif match.group() in ('true', 'false'): next_binary = (yield _BooleanToken(pos, raw)) else: try: float(raw) next_binary = (yield _NumberToken(pos, raw)) except ValueError: next_binary = (yield _KeywordToken(pos, raw)) pos = match.end() else: next_binary = (yield _DelimiterToken(pos, text[pos])) pos += 1 class _BalancedExpression(_Token): pass def _expression(initial, tokens, data): delim_stack = [] token = initial while True: if token.is_delim(): if token.raw in ('[', '{'): delim_stack.append(token) elif token.raw in (']', '}'): if not delim_stack: raise RuntimeError(f'unmatched closing token {token}') match = delim_stack.pop() if match.raw != token.opposite(): raise RuntimeError(f'opening token {match} closed by {token}') if not delim_stack: break else: raise RuntimeError(f'unknown delimiter {token}') elif not delim_stack: break token = next(tokens) return _BalancedExpression(initial.pos, data[initial.pos:token.endpos()].decode('ascii', 'replace')) class Type1Font: __slots__ = ('parts', 'decrypted', 'prop', '_pos', '_abbr') def __init__(self, input): if isinstance(input, tuple) and len(input) == 3: self.parts = input else: with open(input, 'rb') as file: data = self._read(file) self.parts = self._split(data) self.decrypted = self._decrypt(self.parts[1], 'eexec') self._abbr = {'RD': 'RD', 'ND': 'ND', 'NP': 'NP'} self._parse() def _read(self, file): rawdata = file.read() if not rawdata.startswith(b'\x80'): return rawdata data = b'' while rawdata: if not rawdata.startswith(b'\x80'): raise RuntimeError('Broken pfb file (expected byte 128, got %d)' % rawdata[0]) type = rawdata[1] if type in (1, 2): (length,) = struct.unpack('> 8) key = (key + byte) * 52845 + 22719 & 65535 return bytes(plaintext[ndiscard:]) @staticmethod def _encrypt(plaintext, key, ndiscard=4): key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key) ciphertext = [] for byte in b'\x00' * ndiscard + plaintext: c = byte ^ key >> 8 ciphertext.append(c) key = (key + c) * 52845 + 22719 & 65535 return bytes(ciphertext) def _parse(self): prop = {'Weight': 'Regular', 'ItalicAngle': 0.0, 'isFixedPitch': False, 'UnderlinePosition': -100, 'UnderlineThickness': 50} pos = {} data = self.parts[0] + self.decrypted source = _tokenize(data, True) while True: try: token = next(source) except StopIteration: break if token.is_delim(): _expression(token, source, data) if token.is_slash_name(): key = token.value() keypos = token.pos else: continue if key in ('Subrs', 'CharStrings', 'Encoding', 'OtherSubrs'): (prop[key], endpos) = {'Subrs': self._parse_subrs, 'CharStrings': self._parse_charstrings, 'Encoding': self._parse_encoding, 'OtherSubrs': self._parse_othersubrs}[key](source, data) pos.setdefault(key, []).append((keypos, endpos)) continue try: token = next(source) except StopIteration: break if isinstance(token, _KeywordToken): continue if token.is_delim(): value = _expression(token, source, data).raw else: value = token.value() try: kw = next((kw for kw in source if not kw.is_keyword('readonly', 'noaccess', 'executeonly'))) except StopIteration: break if kw.is_keyword('def', self._abbr['ND'], self._abbr['NP']): prop[key] = value pos.setdefault(key, []).append((keypos, kw.endpos())) if value == '{noaccess def}': self._abbr['ND'] = key elif value == '{noaccess put}': self._abbr['NP'] = key elif value == '{string currentfile exch readstring pop}': self._abbr['RD'] = key if 'FontName' not in prop: prop['FontName'] = prop.get('FullName') or prop.get('FamilyName') or 'Unknown' if 'FullName' not in prop: prop['FullName'] = prop['FontName'] if 'FamilyName' not in prop: extras = '(?i)([ -](regular|plain|italic|oblique|(semi)?bold|(ultra)?light|extra|condensed))+$' prop['FamilyName'] = re.sub(extras, '', prop['FullName']) ndiscard = prop.get('lenIV', 4) cs = prop['CharStrings'] for (key, value) in cs.items(): cs[key] = self._decrypt(value, 'charstring', ndiscard) if 'Subrs' in prop: prop['Subrs'] = [self._decrypt(value, 'charstring', ndiscard) for value in prop['Subrs']] self.prop = prop self._pos = pos def _parse_subrs(self, tokens, _data): count_token = next(tokens) if not count_token.is_number(): raise RuntimeError(f'Token following /Subrs must be a number, was {count_token}') count = count_token.value() array = [None] * count next((t for t in tokens if t.is_keyword('array'))) for _ in range(count): next((t for t in tokens if t.is_keyword('dup'))) index_token = next(tokens) if not index_token.is_number(): raise RuntimeError(f'Token following dup in Subrs definition must be a number, was {index_token}') nbytes_token = next(tokens) if not nbytes_token.is_number(): raise RuntimeError(f'Second token following dup in Subrs definition must be a number, was {nbytes_token}') token = next(tokens) if not token.is_keyword(self._abbr['RD']): raise RuntimeError(f"Token preceding subr must be {self._abbr['RD']}, was {token}") binary_token = tokens.send(1 + nbytes_token.value()) array[index_token.value()] = binary_token.value() return (array, next(tokens).endpos()) @staticmethod def _parse_charstrings(tokens, _data): count_token = next(tokens) if not count_token.is_number(): raise RuntimeError(f'Token following /CharStrings must be a number, was {count_token}') count = count_token.value() charstrings = {} next((t for t in tokens if t.is_keyword('begin'))) while True: token = next((t for t in tokens if t.is_keyword('end') or t.is_slash_name())) if token.raw == 'end': return (charstrings, token.endpos()) glyphname = token.value() nbytes_token = next(tokens) if not nbytes_token.is_number(): raise RuntimeError(f'Token following /{glyphname} in CharStrings definition must be a number, was {nbytes_token}') next(tokens) binary_token = tokens.send(1 + nbytes_token.value()) charstrings[glyphname] = binary_token.value() @staticmethod def _parse_encoding(tokens, _data): encoding = {} while True: token = next((t for t in tokens if t.is_keyword('StandardEncoding', 'dup', 'def'))) if token.is_keyword('StandardEncoding'): return (_StandardEncoding, token.endpos()) if token.is_keyword('def'): return (encoding, token.endpos()) index_token = next(tokens) if not index_token.is_number(): _log.warning(f'Parsing encoding: expected number, got {index_token}') continue name_token = next(tokens) if not name_token.is_slash_name(): _log.warning(f'Parsing encoding: expected slash-name, got {name_token}') continue encoding[index_token.value()] = name_token.value() @staticmethod def _parse_othersubrs(tokens, data): init_pos = None while True: token = next(tokens) if init_pos is None: init_pos = token.pos if token.is_delim(): _expression(token, tokens, data) elif token.is_keyword('def', 'ND', '|-'): return (data[init_pos:token.endpos()], token.endpos()) def transform(self, effects): fontname = self.prop['FontName'] italicangle = self.prop['ItalicAngle'] array = [float(x) for x in self.prop['FontMatrix'].lstrip('[').rstrip(']').split()] oldmatrix = np.eye(3, 3) oldmatrix[0:3, 0] = array[::2] oldmatrix[0:3, 1] = array[1::2] modifier = np.eye(3, 3) if 'slant' in effects: slant = effects['slant'] fontname += f'_Slant_{int(1000 * slant)}' italicangle = round(float(italicangle) - np.arctan(slant) / np.pi * 180, 5) modifier[1, 0] = slant if 'extend' in effects: extend = effects['extend'] fontname += f'_Extend_{int(1000 * extend)}' modifier[0, 0] = extend newmatrix = np.dot(modifier, oldmatrix) array[::2] = newmatrix[0:3, 0] array[1::2] = newmatrix[0:3, 1] fontmatrix = f"[{' '.join((_format_approx(x, 6) for x in array))}]" replacements = [(x, f'/FontName/{fontname} def') for x in self._pos['FontName']] + [(x, f'/ItalicAngle {italicangle} def') for x in self._pos['ItalicAngle']] + [(x, f'/FontMatrix {fontmatrix} readonly def') for x in self._pos['FontMatrix']] + [(x, '') for x in self._pos.get('UniqueID', [])] data = bytearray(self.parts[0]) data.extend(self.decrypted) len0 = len(self.parts[0]) for ((pos0, pos1), value) in sorted(replacements, reverse=True): data[pos0:pos1] = value.encode('ascii', 'replace') if pos0 < len(self.parts[0]): if pos1 >= len(self.parts[0]): raise RuntimeError(f'text to be replaced with {value} spans the eexec boundary') len0 += len(value) - pos1 + pos0 data = bytes(data) return Type1Font((data[:len0], self._encrypt(data[len0:], 'eexec'), self.parts[2])) _StandardEncoding = {**{ord(letter): letter for letter in string.ascii_letters}, 0: '.notdef', 32: 'space', 33: 'exclam', 34: 'quotedbl', 35: 'numbersign', 36: 'dollar', 37: 'percent', 38: 'ampersand', 39: 'quoteright', 40: 'parenleft', 41: 'parenright', 42: 'asterisk', 43: 'plus', 44: 'comma', 45: 'hyphen', 46: 'period', 47: 'slash', 48: 'zero', 49: 'one', 50: 'two', 51: 'three', 52: 'four', 53: 'five', 54: 'six', 55: 'seven', 56: 'eight', 57: 'nine', 58: 'colon', 59: 'semicolon', 60: 'less', 61: 'equal', 62: 'greater', 63: 'question', 64: 'at', 91: 'bracketleft', 92: 'backslash', 93: 'bracketright', 94: 'asciicircum', 95: 'underscore', 96: 'quoteleft', 123: 'braceleft', 124: 'bar', 125: 'braceright', 126: 'asciitilde', 161: 'exclamdown', 162: 'cent', 163: 'sterling', 164: 'fraction', 165: 'yen', 166: 'florin', 167: 'section', 168: 'currency', 169: 'quotesingle', 170: 'quotedblleft', 171: 'guillemotleft', 172: 'guilsinglleft', 173: 'guilsinglright', 174: 'fi', 175: 'fl', 177: 'endash', 178: 'dagger', 179: 'daggerdbl', 180: 'periodcentered', 182: 'paragraph', 183: 'bullet', 184: 'quotesinglbase', 185: 'quotedblbase', 186: 'quotedblright', 187: 'guillemotright', 188: 'ellipsis', 189: 'perthousand', 191: 'questiondown', 193: 'grave', 194: 'acute', 195: 'circumflex', 196: 'tilde', 197: 'macron', 198: 'breve', 199: 'dotaccent', 200: 'dieresis', 202: 'ring', 203: 'cedilla', 205: 'hungarumlaut', 206: 'ogonek', 207: 'caron', 208: 'emdash', 225: 'AE', 227: 'ordfeminine', 232: 'Lslash', 233: 'Oslash', 234: 'OE', 235: 'ordmasculine', 241: 'ae', 245: 'dotlessi', 248: 'lslash', 249: 'oslash', 250: 'oe', 251: 'germandbls'} # File: matplotlib-main/lib/matplotlib/animation.py import abc import base64 import contextlib from io import BytesIO, TextIOWrapper import itertools import logging from pathlib import Path import shutil import subprocess import sys from tempfile import TemporaryDirectory import uuid import warnings import numpy as np from PIL import Image import matplotlib as mpl from matplotlib._animation_data import DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE from matplotlib import _api, cbook import matplotlib.colors as mcolors _log = logging.getLogger(__name__) subprocess_creation_flags = subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0 def adjusted_figsize(w, h, dpi, n): def correct_roundoff(x, dpi, n): if int(x * dpi) % n != 0: if int(np.nextafter(x, np.inf) * dpi) % n == 0: x = np.nextafter(x, np.inf) elif int(np.nextafter(x, -np.inf) * dpi) % n == 0: x = np.nextafter(x, -np.inf) return x wnew = int(w * dpi / n) * n / dpi hnew = int(h * dpi / n) * n / dpi return (correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)) class MovieWriterRegistry: def __init__(self): self._registered = dict() def register(self, name): def wrapper(writer_cls): self._registered[name] = writer_cls return writer_cls return wrapper def is_available(self, name): try: cls = self._registered[name] except KeyError: return False return cls.isAvailable() def __iter__(self): for name in self._registered: if self.is_available(name): yield name def list(self): return [*self] def __getitem__(self, name): if self.is_available(name): return self._registered[name] raise RuntimeError(f'Requested MovieWriter ({name}) not available') writers = MovieWriterRegistry() class AbstractMovieWriter(abc.ABC): def __init__(self, fps=5, metadata=None, codec=None, bitrate=None): self.fps = fps self.metadata = metadata if metadata is not None else {} self.codec = mpl._val_or_rc(codec, 'animation.codec') self.bitrate = mpl._val_or_rc(bitrate, 'animation.bitrate') @abc.abstractmethod def setup(self, fig, outfile, dpi=None): Path(outfile).parent.resolve(strict=True) self.outfile = outfile self.fig = fig if dpi is None: dpi = self.fig.dpi self.dpi = dpi @property def frame_size(self): (w, h) = self.fig.get_size_inches() return (int(w * self.dpi), int(h * self.dpi)) @abc.abstractmethod def grab_frame(self, **savefig_kwargs): @abc.abstractmethod def finish(self): @contextlib.contextmanager def saving(self, fig, outfile, dpi, *args, **kwargs): if mpl.rcParams['savefig.bbox'] == 'tight': _log.info("Disabling savefig.bbox = 'tight', as it may cause frame size to vary, which is inappropriate for animation.") self.setup(fig, outfile, dpi, *args, **kwargs) with mpl.rc_context({'savefig.bbox': None}): try: yield self finally: self.finish() class MovieWriter(AbstractMovieWriter): supported_formats = ['rgba'] def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None, metadata=None): if type(self) is MovieWriter: raise TypeError('MovieWriter cannot be instantiated directly. Please use one of its subclasses.') super().__init__(fps=fps, metadata=metadata, codec=codec, bitrate=bitrate) self.frame_format = self.supported_formats[0] self.extra_args = extra_args def _adjust_frame_size(self): if self.codec == 'h264': (wo, ho) = self.fig.get_size_inches() (w, h) = adjusted_figsize(wo, ho, self.dpi, 2) if (wo, ho) != (w, h): self.fig.set_size_inches(w, h, forward=True) _log.info('figure size in inches has been adjusted from %s x %s to %s x %s', wo, ho, w, h) else: (w, h) = self.fig.get_size_inches() _log.debug('frame size in pixels is %s x %s', *self.frame_size) return (w, h) def setup(self, fig, outfile, dpi=None): super().setup(fig, outfile, dpi=dpi) (self._w, self._h) = self._adjust_frame_size() self._run() def _run(self): command = self._args() _log.info('MovieWriter._run: running command: %s', cbook._pformat_subprocess(command)) PIPE = subprocess.PIPE self._proc = subprocess.Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, creationflags=subprocess_creation_flags) def finish(self): (out, err) = self._proc.communicate() out = TextIOWrapper(BytesIO(out)).read() err = TextIOWrapper(BytesIO(err)).read() if out: _log.log(logging.WARNING if self._proc.returncode else logging.DEBUG, 'MovieWriter stdout:\n%s', out) if err: _log.log(logging.WARNING if self._proc.returncode else logging.DEBUG, 'MovieWriter stderr:\n%s', err) if self._proc.returncode: raise subprocess.CalledProcessError(self._proc.returncode, self._proc.args, out, err) def grab_frame(self, **savefig_kwargs): _validate_grabframe_kwargs(savefig_kwargs) _log.debug('MovieWriter.grab_frame: Grabbing frame.') self.fig.set_size_inches(self._w, self._h) self.fig.savefig(self._proc.stdin, format=self.frame_format, dpi=self.dpi, **savefig_kwargs) def _args(self): return NotImplementedError('args needs to be implemented by subclass.') @classmethod def bin_path(cls): return str(mpl.rcParams[cls._exec_key]) @classmethod def isAvailable(cls): return shutil.which(cls.bin_path()) is not None class FileMovieWriter(MovieWriter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.frame_format = mpl.rcParams['animation.frame_format'] def setup(self, fig, outfile, dpi=None, frame_prefix=None): Path(outfile).parent.resolve(strict=True) self.fig = fig self.outfile = outfile if dpi is None: dpi = self.fig.dpi self.dpi = dpi self._adjust_frame_size() if frame_prefix is None: self._tmpdir = TemporaryDirectory() self.temp_prefix = str(Path(self._tmpdir.name, 'tmp')) else: self._tmpdir = None self.temp_prefix = frame_prefix self._frame_counter = 0 self._temp_paths = list() self.fname_format_str = '%s%%07d.%s' def __del__(self): if hasattr(self, '_tmpdir') and self._tmpdir: self._tmpdir.cleanup() @property def frame_format(self): return self._frame_format @frame_format.setter def frame_format(self, frame_format): if frame_format in self.supported_formats: self._frame_format = frame_format else: _api.warn_external(f'Ignoring file format {frame_format!r} which is not supported by {type(self).__name__}; using {self.supported_formats[0]} instead.') self._frame_format = self.supported_formats[0] def _base_temp_name(self): return self.fname_format_str % (self.temp_prefix, self.frame_format) def grab_frame(self, **savefig_kwargs): _validate_grabframe_kwargs(savefig_kwargs) path = Path(self._base_temp_name() % self._frame_counter) self._temp_paths.append(path) self._frame_counter += 1 _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s', self._frame_counter, path) with open(path, 'wb') as sink: self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi, **savefig_kwargs) def finish(self): try: self._run() super().finish() finally: if self._tmpdir: _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir) self._tmpdir.cleanup() @writers.register('pillow') class PillowWriter(AbstractMovieWriter): @classmethod def isAvailable(cls): return True def setup(self, fig, outfile, dpi=None): super().setup(fig, outfile, dpi=dpi) self._frames = [] def grab_frame(self, **savefig_kwargs): _validate_grabframe_kwargs(savefig_kwargs) buf = BytesIO() self.fig.savefig(buf, **{**savefig_kwargs, 'format': 'rgba', 'dpi': self.dpi}) self._frames.append(Image.frombuffer('RGBA', self.frame_size, buf.getbuffer(), 'raw', 'RGBA', 0, 1)) def finish(self): self._frames[0].save(self.outfile, save_all=True, append_images=self._frames[1:], duration=int(1000 / self.fps), loop=0) class FFMpegBase: _exec_key = 'animation.ffmpeg_path' _args_key = 'animation.ffmpeg_args' @property def output_args(self): args = [] if Path(self.outfile).suffix == '.gif': self.codec = 'gif' else: args.extend(['-vcodec', self.codec]) extra_args = self.extra_args if self.extra_args is not None else mpl.rcParams[self._args_key] if self.codec == 'h264' and '-pix_fmt' not in extra_args: args.extend(['-pix_fmt', 'yuv420p']) elif self.codec == 'gif' and '-filter_complex' not in extra_args: args.extend(['-filter_complex', 'split [a][b];[a] palettegen [p];[b][p] paletteuse']) if self.bitrate > 0: args.extend(['-b', '%dk' % self.bitrate]) for (k, v) in self.metadata.items(): args.extend(['-metadata', f'{k}={v}']) args.extend(extra_args) return args + ['-y', self.outfile] @writers.register('ffmpeg') class FFMpegWriter(FFMpegBase, MovieWriter): def _args(self): args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format, '-framerate', str(self.fps)] if _log.getEffectiveLevel() > logging.DEBUG: args += ['-loglevel', 'error'] args += ['-i', 'pipe:'] + self.output_args return args @writers.register('ffmpeg_file') class FFMpegFileWriter(FFMpegBase, FileMovieWriter): supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba'] def _args(self): args = [] if self.frame_format in {'raw', 'rgba'}: args += ['-f', 'image2', '-vcodec', 'rawvideo', '-video_size', '%dx%d' % self.frame_size, '-pixel_format', 'rgba'] args += ['-framerate', str(self.fps), '-i', self._base_temp_name()] if not self._tmpdir: args += ['-frames:v', str(self._frame_counter)] if _log.getEffectiveLevel() > logging.DEBUG: args += ['-loglevel', 'error'] return [self.bin_path(), *args, *self.output_args] class ImageMagickBase: _exec_key = 'animation.convert_path' _args_key = 'animation.convert_args' def _args(self): fmt = 'rgba' if self.frame_format == 'raw' else self.frame_format extra_args = self.extra_args if self.extra_args is not None else mpl.rcParams[self._args_key] return [self.bin_path(), '-size', '%ix%i' % self.frame_size, '-depth', '8', '-delay', str(100 / self.fps), '-loop', '0', f'{fmt}:{self.input_names}', *extra_args, self.outfile] @classmethod def bin_path(cls): binpath = super().bin_path() if binpath == 'convert': binpath = mpl._get_executable_info('magick').executable return binpath @classmethod def isAvailable(cls): try: return super().isAvailable() except mpl.ExecutableNotFoundError as _enf: _log.debug('ImageMagick unavailable due to: %s', _enf) return False @writers.register('imagemagick') class ImageMagickWriter(ImageMagickBase, MovieWriter): input_names = '-' @writers.register('imagemagick_file') class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter): supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba'] input_names = property(lambda self: f'{self.temp_prefix}*.{self.frame_format}') def _included_frames(frame_count, frame_format, frame_dir): return INCLUDED_FRAMES.format(Nframes=frame_count, frame_dir=frame_dir, frame_format=frame_format) def _embedded_frames(frame_list, frame_format): if frame_format == 'svg': frame_format = 'svg+xml' template = ' frames[{0}] = "data:image/{1};base64,{2}"\n' return '\n' + ''.join((template.format(i, frame_format, frame_data.replace('\n', '\\\n')) for (i, frame_data) in enumerate(frame_list))) @writers.register('html') class HTMLWriter(FileMovieWriter): supported_formats = ['png', 'jpeg', 'tiff', 'svg'] @classmethod def isAvailable(cls): return True def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None, metadata=None, embed_frames=False, default_mode='loop', embed_limit=None): if extra_args: _log.warning("HTMLWriter ignores 'extra_args'") extra_args = () self.embed_frames = embed_frames self.default_mode = default_mode.lower() _api.check_in_list(['loop', 'once', 'reflect'], default_mode=self.default_mode) self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit') self._bytes_limit *= 1024 * 1024 super().__init__(fps, codec, bitrate, extra_args, metadata) def setup(self, fig, outfile, dpi=None, frame_dir=None): outfile = Path(outfile) _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix) self._saved_frames = [] self._total_bytes = 0 self._hit_limit = False if not self.embed_frames: if frame_dir is None: frame_dir = outfile.with_name(outfile.stem + '_frames') frame_dir.mkdir(parents=True, exist_ok=True) frame_prefix = frame_dir / 'frame' else: frame_prefix = None super().setup(fig, outfile, dpi, frame_prefix) self._clear_temp = False def grab_frame(self, **savefig_kwargs): _validate_grabframe_kwargs(savefig_kwargs) if self.embed_frames: if self._hit_limit: return f = BytesIO() self.fig.savefig(f, format=self.frame_format, dpi=self.dpi, **savefig_kwargs) imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii') self._total_bytes += len(imgdata64) if self._total_bytes >= self._bytes_limit: _log.warning("Animation size has reached %s bytes, exceeding the limit of %s. If you're sure you want a larger animation embedded, set the animation.embed_limit rc parameter to a larger value (in MB). This and further frames will be dropped.", self._total_bytes, self._bytes_limit) self._hit_limit = True else: self._saved_frames.append(imgdata64) else: return super().grab_frame(**savefig_kwargs) def finish(self): if self.embed_frames: fill_frames = _embedded_frames(self._saved_frames, self.frame_format) frame_count = len(self._saved_frames) else: frame_count = len(self._temp_paths) fill_frames = _included_frames(frame_count, self.frame_format, self._temp_paths[0].parent.relative_to(self.outfile.parent)) mode_dict = dict(once_checked='', loop_checked='', reflect_checked='') mode_dict[self.default_mode + '_checked'] = 'checked' interval = 1000 // self.fps with open(self.outfile, 'w') as of: of.write(JS_INCLUDE + STYLE_INCLUDE) of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex, Nframes=frame_count, fill_frames=fill_frames, interval=interval, **mode_dict)) if self._tmpdir: _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir) self._tmpdir.cleanup() class Animation: def __init__(self, fig, event_source=None, blit=False): self._draw_was_started = False self._fig = fig self._blit = blit and fig.canvas.supports_blit self.frame_seq = self.new_frame_seq() self.event_source = event_source self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start) self._close_id = self._fig.canvas.mpl_connect('close_event', self._stop) if self._blit: self._setup_blit() def __del__(self): if not getattr(self, '_draw_was_started', True): warnings.warn('Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you output the Animation using `plt.show()` or `anim.save()`.') def _start(self, *args): if self._fig.canvas.is_saving(): return self._fig.canvas.mpl_disconnect(self._first_draw_id) self._init_draw() self.event_source.add_callback(self._step) self.event_source.start() def _stop(self, *args): if self._blit: self._fig.canvas.mpl_disconnect(self._resize_id) self._fig.canvas.mpl_disconnect(self._close_id) self.event_source.remove_callback(self._step) self.event_source = None def save(self, filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None, *, progress_callback=None): all_anim = [self] if extra_anim is not None: all_anim.extend((anim for anim in extra_anim if anim._fig is self._fig)) for anim in all_anim: anim._draw_was_started = True if writer is None: writer = mpl.rcParams['animation.writer'] elif not isinstance(writer, str) and any((arg is not None for arg in (fps, codec, bitrate, extra_args, metadata))): raise RuntimeError('Passing in values for arguments fps, codec, bitrate, extra_args, or metadata is not supported when writer is an existing MovieWriter instance. These should instead be passed as arguments when creating the MovieWriter instance.') if savefig_kwargs is None: savefig_kwargs = {} else: savefig_kwargs = dict(savefig_kwargs) if fps is None and hasattr(self, '_interval'): fps = 1000.0 / self._interval dpi = mpl._val_or_rc(dpi, 'savefig.dpi') if dpi == 'figure': dpi = self._fig.dpi writer_kwargs = {} if codec is not None: writer_kwargs['codec'] = codec if bitrate is not None: writer_kwargs['bitrate'] = bitrate if extra_args is not None: writer_kwargs['extra_args'] = extra_args if metadata is not None: writer_kwargs['metadata'] = metadata if isinstance(writer, str): try: writer_cls = writers[writer] except RuntimeError: writer_cls = PillowWriter _log.warning('MovieWriter %s unavailable; using Pillow instead.', writer) writer = writer_cls(fps, **writer_kwargs) _log.info('Animation.save using %s', type(writer)) if 'bbox_inches' in savefig_kwargs: _log.warning("Warning: discarding the 'bbox_inches' argument in 'savefig_kwargs' as it may cause frame size to vary, which is inappropriate for animation.") savefig_kwargs.pop('bbox_inches') facecolor = savefig_kwargs.get('facecolor', mpl.rcParams['savefig.facecolor']) if facecolor == 'auto': facecolor = self._fig.get_facecolor() def _pre_composite_to_white(color): (r, g, b, a) = mcolors.to_rgba(color) return a * np.array([r, g, b]) + 1 - a savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor) savefig_kwargs['transparent'] = False with writer.saving(self._fig, filename, dpi), cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None): for anim in all_anim: anim._init_draw() frame_number = 0 save_count_list = [getattr(a, '_save_count', None) for a in all_anim] if None in save_count_list: total_frames = None else: total_frames = sum(save_count_list) for data in zip(*[a.new_saved_frame_seq() for a in all_anim]): for (anim, d) in zip(all_anim, data): anim._draw_next_frame(d, blit=False) if progress_callback is not None: progress_callback(frame_number, total_frames) frame_number += 1 writer.grab_frame(**savefig_kwargs) def _step(self, *args): try: framedata = next(self.frame_seq) self._draw_next_frame(framedata, self._blit) return True except StopIteration: return False def new_frame_seq(self): return iter(self._framedata) def new_saved_frame_seq(self): return self.new_frame_seq() def _draw_next_frame(self, framedata, blit): self._pre_draw(framedata, blit) self._draw_frame(framedata) self._post_draw(framedata, blit) def _init_draw(self): self._draw_was_started = True def _pre_draw(self, framedata, blit): if blit: self._blit_clear(self._drawn_artists) def _draw_frame(self, framedata): raise NotImplementedError('Needs to be implemented by subclasses to actually make an animation.') def _post_draw(self, framedata, blit): if blit and self._drawn_artists: self._blit_draw(self._drawn_artists) else: self._fig.canvas.draw_idle() def _blit_draw(self, artists): updated_ax = {a.axes for a in artists} for ax in updated_ax: cur_view = ax._get_view() (view, bg) = self._blit_cache.get(ax, (object(), None)) if cur_view != view: self._blit_cache[ax] = (cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox)) for a in artists: a.axes.draw_artist(a) for ax in updated_ax: ax.figure.canvas.blit(ax.bbox) def _blit_clear(self, artists): axes = {a.axes for a in artists} for ax in axes: try: (view, bg) = self._blit_cache[ax] except KeyError: continue if ax._get_view() == view: ax.figure.canvas.restore_region(bg) else: self._blit_cache.pop(ax) def _setup_blit(self): self._blit_cache = dict() self._drawn_artists = [] self._post_draw(None, self._blit) self._init_draw() self._resize_id = self._fig.canvas.mpl_connect('resize_event', self._on_resize) def _on_resize(self, event): self._fig.canvas.mpl_disconnect(self._resize_id) self.event_source.stop() self._blit_cache.clear() self._init_draw() self._resize_id = self._fig.canvas.mpl_connect('draw_event', self._end_redraw) def _end_redraw(self, event): self._post_draw(None, False) self.event_source.start() self._fig.canvas.mpl_disconnect(self._resize_id) self._resize_id = self._fig.canvas.mpl_connect('resize_event', self._on_resize) def to_html5_video(self, embed_limit=None): VIDEO_TAG = '' if not hasattr(self, '_base64_video'): embed_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit') embed_limit *= 1024 * 1024 with TemporaryDirectory() as tmpdir: path = Path(tmpdir, 'temp.m4v') Writer = writers[mpl.rcParams['animation.writer']] writer = Writer(codec='h264', bitrate=mpl.rcParams['animation.bitrate'], fps=1000.0 / self._interval) self.save(str(path), writer=writer) vid64 = base64.encodebytes(path.read_bytes()) vid_len = len(vid64) if vid_len >= embed_limit: _log.warning("Animation movie is %s bytes, exceeding the limit of %s. If you're sure you want a large animation embedded, set the animation.embed_limit rc parameter to a larger value (in MB).", vid_len, embed_limit) else: self._base64_video = vid64.decode('ascii') self._video_size = 'width="{}" height="{}"'.format(*writer.frame_size) if hasattr(self, '_base64_video'): options = ['controls', 'autoplay'] if getattr(self, '_repeat', False): options.append('loop') return VIDEO_TAG.format(video=self._base64_video, size=self._video_size, options=' '.join(options)) else: return 'Video too large to embed.' def to_jshtml(self, fps=None, embed_frames=True, default_mode=None): if fps is None and hasattr(self, '_interval'): fps = 1000 / self._interval if default_mode is None: default_mode = 'loop' if getattr(self, '_repeat', False) else 'once' if not hasattr(self, '_html_representation'): with TemporaryDirectory() as tmpdir: path = Path(tmpdir, 'temp.html') writer = HTMLWriter(fps=fps, embed_frames=embed_frames, default_mode=default_mode) self.save(str(path), writer=writer) self._html_representation = path.read_text() return self._html_representation def _repr_html_(self): fmt = mpl.rcParams['animation.html'] if fmt == 'html5': return self.to_html5_video() elif fmt == 'jshtml': return self.to_jshtml() def pause(self): self.event_source.stop() if self._blit: for artist in self._drawn_artists: artist.set_animated(False) def resume(self): self.event_source.start() if self._blit: for artist in self._drawn_artists: artist.set_animated(True) class TimedAnimation(Animation): def __init__(self, fig, interval=200, repeat_delay=0, repeat=True, event_source=None, *args, **kwargs): self._interval = interval self._repeat_delay = repeat_delay if repeat_delay is not None else 0 self._repeat = repeat if event_source is None: event_source = fig.canvas.new_timer(interval=self._interval) super().__init__(fig, *args, event_source=event_source, **kwargs) def _step(self, *args): still_going = super()._step(*args) if not still_going: if self._repeat: self._init_draw() self.frame_seq = self.new_frame_seq() self.event_source.interval = self._repeat_delay return True else: self.pause() if self._blit: self._fig.canvas.mpl_disconnect(self._resize_id) self._fig.canvas.mpl_disconnect(self._close_id) self.event_source = None return False self.event_source.interval = self._interval return True class ArtistAnimation(TimedAnimation): def __init__(self, fig, artists, *args, **kwargs): self._drawn_artists = [] self._framedata = artists super().__init__(fig, *args, **kwargs) def _init_draw(self): super()._init_draw() figs = set() for f in self.new_frame_seq(): for artist in f: artist.set_visible(False) artist.set_animated(self._blit) if artist.get_figure() not in figs: figs.add(artist.get_figure()) for fig in figs: fig.canvas.draw_idle() def _pre_draw(self, framedata, blit): if blit: self._blit_clear(self._drawn_artists) else: for artist in self._drawn_artists: artist.set_visible(False) def _draw_frame(self, artists): self._drawn_artists = artists for artist in artists: artist.set_visible(True) class FuncAnimation(TimedAnimation): def __init__(self, fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs): if fargs: self._args = fargs else: self._args = () self._func = func self._init_func = init_func self._save_count = save_count if frames is None: self._iter_gen = itertools.count elif callable(frames): self._iter_gen = frames elif np.iterable(frames): if kwargs.get('repeat', True): self._tee_from = frames def iter_frames(frames=frames): (this, self._tee_from) = itertools.tee(self._tee_from, 2) yield from this self._iter_gen = iter_frames else: self._iter_gen = lambda : iter(frames) if hasattr(frames, '__len__'): self._save_count = len(frames) if save_count is not None: _api.warn_external(f'You passed in an explicit save_count={save_count!r} which is being ignored in favor of len(frames)={len(frames)!r}.') else: self._iter_gen = lambda : iter(range(frames)) self._save_count = frames if save_count is not None: _api.warn_external(f'You passed in an explicit save_count={save_count!r} which is being ignored in favor of frames={frames!r}.') if self._save_count is None and cache_frame_data: _api.warn_external(f'frames={frames!r} which we can infer the length of, did not pass an explicit *save_count* and passed cache_frame_data={cache_frame_data!r}. To avoid a possibly unbounded cache, frame data caching has been disabled. To suppress this warning either pass `cache_frame_data=False` or `save_count=MAX_FRAMES`.') cache_frame_data = False self._cache_frame_data = cache_frame_data self._save_seq = [] super().__init__(fig, **kwargs) self._save_seq = [] def new_frame_seq(self): return self._iter_gen() def new_saved_frame_seq(self): if self._save_seq: self._old_saved_seq = list(self._save_seq) return iter(self._old_saved_seq) elif self._save_count is None: frame_seq = self.new_frame_seq() def gen(): try: while True: yield next(frame_seq) except StopIteration: pass return gen() else: return itertools.islice(self.new_frame_seq(), self._save_count) def _init_draw(self): super()._init_draw() if self._init_func is None: try: frame_data = next(self.new_frame_seq()) except StopIteration: warnings.warn('Can not start iterating the frames for the initial draw. This can be caused by passing in a 0 length sequence for *frames*.\n\nIf you passed *frames* as a generator it may be exhausted due to a previous display or save.') return self._draw_frame(frame_data) else: self._drawn_artists = self._init_func() if self._blit: if self._drawn_artists is None: raise RuntimeError('The init_func must return a sequence of Artist objects.') for a in self._drawn_artists: a.set_animated(self._blit) self._save_seq = [] def _draw_frame(self, framedata): if self._cache_frame_data: self._save_seq.append(framedata) self._save_seq = self._save_seq[-self._save_count:] self._drawn_artists = self._func(framedata, *self._args) if self._blit: err = RuntimeError('The animation function must return a sequence of Artist objects.') try: iter(self._drawn_artists) except TypeError: raise err from None for i in self._drawn_artists: if not isinstance(i, mpl.artist.Artist): raise err self._drawn_artists = sorted(self._drawn_artists, key=lambda x: x.get_zorder()) for a in self._drawn_artists: a.set_animated(self._blit) def _validate_grabframe_kwargs(savefig_kwargs): if mpl.rcParams['savefig.bbox'] == 'tight': raise ValueError(f"mpl.rcParams['savefig.bbox']={mpl.rcParams['savefig.bbox']!r} must not be 'tight' as it may cause frame size to vary, which is inappropriate for animation.") for k in ('dpi', 'bbox_inches', 'format'): if k in savefig_kwargs: raise TypeError(f'grab_frame got an unexpected keyword argument {k!r}') # File: matplotlib-main/lib/matplotlib/artist.py from collections import namedtuple import contextlib from functools import cache, reduce, wraps import inspect from inspect import Signature, Parameter import logging from numbers import Number, Real import operator import re import warnings import numpy as np import matplotlib as mpl from . import _api, cbook from .path import Path from .transforms import BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox, TransformedPatchPath, TransformedPath _log = logging.getLogger(__name__) def _prevent_rasterization(draw): @wraps(draw) def draw_wrapper(artist, renderer, *args, **kwargs): if renderer._raster_depth == 0 and renderer._rasterizing: renderer.stop_rasterizing() renderer._rasterizing = False return draw(artist, renderer, *args, **kwargs) draw_wrapper._supports_rasterization = False return draw_wrapper def allow_rasterization(draw): @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 elif renderer._raster_depth == 0 and renderer._rasterizing: 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: renderer.stop_rasterizing() renderer.start_rasterizing() draw_wrapper._supports_rasterization = True return draw_wrapper def _finalize_rasterization(draw): @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() class Artist: zorder = 0 def __init_subclass__(cls): if not hasattr(cls.draw, '_supports_rasterization'): cls.draw = _prevent_rasterization(cls.draw) if not hasattr(cls.set, '_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', 'figure', '3d_properties'] @classmethod def _update_set_signature_and_docstring(cls): 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\nSupported 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 self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data self._callbacks = cbook.CallbackRegistry(signals=['pchanged']) try: self.axes = None except AttributeError: 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): if self._remove_method is not None: self._remove_method(self) self.stale_callback = None _ax_flag = False if hasattr(self, 'axes') and self.axes: self.axes._mouseover_set.discard(self) self.axes.stale = True self.axes = None _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') def have_units(self): ax = self.axes return ax and any((axis.have_units() for axis in ax._axis_map.values())) def convert_xunits(self, x): 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): 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): 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): return self._stale @stale.setter def stale(self, val): self._stale = val 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): return Bbox([[0, 0], [0, 0]]) def get_tightbbox(self, renderer=None): 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): return self._callbacks.connect('pchanged', lambda : func(self)) def remove_callback(self, oid): self._callbacks.disconnect(oid) def pchanged(self): self._callbacks.process('pchanged') def is_transform_set(self): return self._transformSet def set_transform(self, t): self._transform = t self._transformSet = True self.pchanged() self.stale = True def get_transform(self): 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): return [] def _different_canvas(self, event): 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): _log.warning("%r needs 'contains' method", self.__class__.__name__) return (False, {}) def pickable(self): return self.get_figure(root=False) is not None and self._picker is not None def pick(self, mouseevent): from .backend_bases import PickEvent 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() for a in self.get_children(): ax = getattr(a, 'axes', None) if isinstance(a, mpl.figure.SubFigure) or mouseevent.inaxes is None or ax is None or (mouseevent.inaxes == ax): a.pick(mouseevent) def set_picker(self, picker): self._picker = picker def get_picker(self): return self._picker def get_url(self): return self._url def set_url(self, url): self._url = url def get_gid(self): return self._gid def set_gid(self, gid): self._gid = gid def get_snap(self): if mpl.rcParams['path.snap']: return self._snap else: return False def set_snap(self, snap): self._snap = snap self.stale = True def get_sketch_params(self): return self._sketch def set_sketch_params(self, scale=None, length=None, randomness=None): 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): self._path_effects = path_effects self.stale = True def get_path_effects(self): return self._path_effects def get_figure(self, root=False): 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): if self._parent_figure is fig: return 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): _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): 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(f'Invalid arguments to set_clip_path, of type {type(path).__name__} and {type(transform).__name__}') self.pchanged() self.stale = True def get_alpha(self): return self._alpha def get_visible(self): return self._visible def get_animated(self): return self._animated def get_in_layout(self): return self._in_layout def _fully_clipped_to_axes(self): 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 self._clipon def get_clip_box(self): return self.clipbox def get_clip_path(self): return self._clippath def get_transformed_clip_path_and_affine(self): if self._clippath is not None: return self._clippath.get_transformed_path_and_affine() return (None, None) def set_clip_on(self, b): self._clipon = b self.pchanged() self.stale = True def _set_gc_clip(self, 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 self._rasterized def set_rasterized(self, rasterized): 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 self._agg_filter def set_agg_filter(self, filter_func): self._agg_filter = filter_func self.stale = True def draw(self, renderer): if not self.get_visible(): return self.stale = False def set_alpha(self, alpha): 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): 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(f'alpha must be between 0 and 1, inclusive, but min is {alpha.min()}, max is {alpha.max()}') self._alpha = alpha self.pchanged() self.stale = True def set_visible(self, b): if b != self._visible: self._visible = b self.pchanged() self.stale = True def set_animated(self, b): if self._animated != b: self._animated = b self.pchanged() def set_in_layout(self, in_layout): self._in_layout = in_layout def get_label(self): return self._label def set_label(self, s): 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 self.zorder def set_zorder(self, level): 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): return self._sticky_edges def update_from(self, other): 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 ArtistInspector(self).properties() def _update_props(self, props, errfmt): ret = [] with cbook._setattr_cm(self, eventson=False): for (k, v) in props.items(): 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): return self._update_props(props, '{cls.__name__!r} object has no property {prop_name!r}') def _internal_update(self, kwargs): return self._update_props(kwargs, '{cls.__name__}.set() got an unexpected keyword argument {prop_name!r}') def set(self, **kwargs): return self._internal_update(cbook.normalize_kwargs(kwargs, self)) @contextlib.contextmanager def _cm_set(self, **kwargs): 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): if match is None: 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 None def format_cursor_data(self, data): if np.ndim(data) == 0 and hasattr(self, '_format_cursor_data_override'): 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 self._mouseover def set_mouseover(self, mouseover): 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) def _get_tightbbox_for_layout_only(obj, *args, **kwargs): try: return obj.get_tightbbox(*args, **{**kwargs, 'for_layout_only': True}) except TypeError: return obj.get_tightbbox(*args, **kwargs) class ArtistInspector: def __init__(self, o): 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): 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]}.*)`', inspect.getdoc(func)).group(1) aliases.setdefault(propname[4:], set()).add(name[4:]) return aliases _get_valid_values_regex = re.compile('\\n\\s*(?:\\.\\.\\s+)?ACCEPTS:\\s*((?:.|\\n)*?)(?:$|(?:\\n\\n))') def get_valid_values(self, attr): 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)) param_name = func.__code__.co_varnames[1] match = re.search(f'(?m)^ *\\*?{param_name} : (.+)', docstring) if match: return match.group(1) return 'unknown' def _replace_path(self, source_class): 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): 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 len(inspect.signature(func).parameters) @staticmethod @cache def is_alias(method): ds = inspect.getdoc(method) if ds is None: return False return ds.startswith('Alias for ') def aliased_name(self, s): aliases = ''.join((' or %s' % x for x in sorted(self.aliasd.get(s, [])))) return s + aliases _NOT_LINKABLE = {'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): if target in self._NOT_LINKABLE: return f'``{s}``' aliases = ''.join((' or %s' % x for x in sorted(self.aliasd.get(s, [])))) return f':meth:`{s} <{target}>`{aliases}' def pprint_setters(self, prop=None, leadingspace=2): 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 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()): for cls in self.o.__mro__: method = getattr(cls, f'set_{prop}', None) if method and method.__doc__ is not None: break else: 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): 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): 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): if property is None: insp = ArtistInspector(obj) ret = insp.pprint_getters() print('\n'.join(ret)) return return getattr(obj, 'get_' + property)() get = getp def setp(obj, *args, file=None, **kwargs): 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): 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)) Artist._update_set_signature_and_docstring() # File: matplotlib-main/lib/matplotlib/axes/__init__.py from . import _base from ._axes import Axes Subplot = Axes class _SubplotBaseMeta(type): def __instancecheck__(self, obj): return isinstance(obj, _base._AxesBase) and obj.get_subplotspec() is not None class SubplotBase(metaclass=_SubplotBaseMeta): pass def subplot_class_factory(cls): return cls # File: matplotlib-main/lib/matplotlib/axes/_axes.py import functools import itertools import logging import math from numbers import Integral, Number, Real import re import numpy as np from numpy import ma import matplotlib as mpl import matplotlib.category import matplotlib.cbook as cbook import matplotlib.collections as mcoll import matplotlib.colors as mcolors import matplotlib.contour as mcontour import matplotlib.dates import matplotlib.image as mimage import matplotlib.legend as mlegend import matplotlib.lines as mlines import matplotlib.markers as mmarkers import matplotlib.mlab as mlab import matplotlib.patches as mpatches import matplotlib.path as mpath import matplotlib.quiver as mquiver import matplotlib.stackplot as mstack import matplotlib.streamplot as mstream import matplotlib.table as mtable import matplotlib.text as mtext import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.tri as mtri import matplotlib.units as munits from matplotlib import _api, _docstring, _preprocess_data from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator, _process_plot_format from matplotlib.axes._secondary_axes import SecondaryAxis from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer _log = logging.getLogger(__name__) def _make_axes_method(func): func.__qualname__ = f'Axes.{func.__name__}' return func @_docstring.interpd class Axes(_AxesBase): def get_title(self, loc='center'): titles = {'left': self._left_title, 'center': self.title, 'right': self._right_title} title = _api.check_getitem(titles, loc=loc.lower()) return title.get_text() def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs): if loc is None: loc = mpl.rcParams['axes.titlelocation'] if y is None: y = mpl.rcParams['axes.titley'] if y is None: y = 1.0 else: self._autotitlepos = False kwargs['y'] = y titles = {'left': self._left_title, 'center': self.title, 'right': self._right_title} title = _api.check_getitem(titles, loc=loc.lower()) default = {'fontsize': mpl.rcParams['axes.titlesize'], 'fontweight': mpl.rcParams['axes.titleweight'], 'verticalalignment': 'baseline', 'horizontalalignment': loc.lower()} titlecolor = mpl.rcParams['axes.titlecolor'] if not cbook._str_lower_equal(titlecolor, 'auto'): default['color'] = titlecolor if pad is None: pad = mpl.rcParams['axes.titlepad'] self._set_title_offset_trans(float(pad)) title.set_text(label) title.update(default) if fontdict is not None: title.update(fontdict) title._internal_update(kwargs) return title def get_legend_handles_labels(self, legend_handler_map=None): (handles, labels) = mlegend._get_legend_handles_labels([self], legend_handler_map) return (handles, labels) @_docstring.dedent_interpd def legend(self, *args, **kwargs): (handles, labels, kwargs) = mlegend._parse_legend_args([self], *args, **kwargs) self.legend_ = mlegend.Legend(self, handles, labels, **kwargs) self.legend_._remove_method = self._remove_legend return self.legend_ def _remove_legend(self, legend): self.legend_ = None def inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs): if transform is None: transform = self.transAxes kwargs.setdefault('label', 'inset_axes') inset_locator = _TransformedBoundsLocator(bounds, transform) bounds = inset_locator(self, None).bounds fig = self.get_figure(root=False) (projection_class, pkw) = fig._process_projection_requirements(**kwargs) inset_ax = projection_class(fig, bounds, zorder=zorder, **pkw) inset_ax.set_axes_locator(inset_locator) self.add_child_axes(inset_ax) return inset_ax @_docstring.dedent_interpd def indicate_inset(self, bounds, inset_ax=None, *, transform=None, facecolor='none', edgecolor='0.5', alpha=0.5, zorder=4.99, **kwargs): self.apply_aspect() if transform is None: transform = self.transData kwargs.setdefault('label', '_indicate_inset') (x, y, width, height) = bounds rectangle_patch = mpatches.Rectangle((x, y), width, height, facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, zorder=zorder, transform=transform, **kwargs) self.add_patch(rectangle_patch) connects = [] if inset_ax is not None: for xy_inset_ax in [(0, 0), (0, 1), (1, 0), (1, 1)]: (ex, ey) = xy_inset_ax if self.xaxis.get_inverted(): ex = 1 - ex if self.yaxis.get_inverted(): ey = 1 - ey xy_data = (x + ex * width, y + ey * height) p = mpatches.ConnectionPatch(xyA=xy_inset_ax, coordsA=inset_ax.transAxes, xyB=xy_data, coordsB=self.transData, arrowstyle='-', zorder=zorder, edgecolor=edgecolor, alpha=alpha) connects.append(p) self.add_patch(p) pos = inset_ax.get_position() bboxins = pos.transformed(self.get_figure(root=False).transSubfigure) rectbbox = mtransforms.Bbox.from_bounds(*bounds).transformed(transform) x0 = rectbbox.x0 < bboxins.x0 x1 = rectbbox.x1 < bboxins.x1 y0 = rectbbox.y0 < bboxins.y0 y1 = rectbbox.y1 < bboxins.y1 connects[0].set_visible(x0 ^ y0) connects[1].set_visible(x0 == y1) connects[2].set_visible(x1 == y0) connects[3].set_visible(x1 ^ y1) return (rectangle_patch, tuple(connects) if connects else None) def indicate_inset_zoom(self, inset_ax, **kwargs): xlim = inset_ax.get_xlim() ylim = inset_ax.get_ylim() rect = (xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0]) return self.indicate_inset(rect, inset_ax, **kwargs) @_docstring.dedent_interpd def secondary_xaxis(self, location, functions=None, *, transform=None, **kwargs): if not (location in ['top', 'bottom'] or isinstance(location, Real)): raise ValueError('secondary_xaxis location must be either a float or "top"/"bottom"') secondary_ax = SecondaryAxis(self, 'x', location, functions, transform, **kwargs) self.add_child_axes(secondary_ax) return secondary_ax @_docstring.dedent_interpd def secondary_yaxis(self, location, functions=None, *, transform=None, **kwargs): if not (location in ['left', 'right'] or isinstance(location, Real)): raise ValueError('secondary_yaxis location must be either a float or "left"/"right"') secondary_ax = SecondaryAxis(self, 'y', location, functions, transform, **kwargs) self.add_child_axes(secondary_ax) return secondary_ax @_docstring.dedent_interpd def text(self, x, y, s, fontdict=None, **kwargs): effective_kwargs = {'verticalalignment': 'baseline', 'horizontalalignment': 'left', 'transform': self.transData, 'clip_on': False, **(fontdict if fontdict is not None else {}), **kwargs} t = mtext.Text(x, y, text=s, **effective_kwargs) if t.get_clip_path() is None: t.set_clip_path(self.patch) self._add_text(t) return t @_docstring.dedent_interpd def annotate(self, text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs): a = mtext.Annotation(text, xy, xytext=xytext, xycoords=xycoords, textcoords=textcoords, arrowprops=arrowprops, annotation_clip=annotation_clip, **kwargs) a.set_transform(mtransforms.IdentityTransform()) if kwargs.get('clip_on', False) and a.get_clip_path() is None: a.set_clip_path(self.patch) self._add_text(a) return a annotate.__doc__ = mtext.Annotation.__init__.__doc__ @_docstring.dedent_interpd def axhline(self, y=0, xmin=0, xmax=1, **kwargs): self._check_no_units([xmin, xmax], ['xmin', 'xmax']) if 'transform' in kwargs: raise ValueError("'transform' is not allowed as a keyword argument; axhline generates its own transform.") (ymin, ymax) = self.get_ybound() (yy,) = self._process_unit_info([('y', y)], kwargs) scaley = yy < ymin or yy > ymax trans = self.get_yaxis_transform(which='grid') l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs) self.add_line(l) l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS if scaley: self._request_autoscale_view('y') return l @_docstring.dedent_interpd def axvline(self, x=0, ymin=0, ymax=1, **kwargs): self._check_no_units([ymin, ymax], ['ymin', 'ymax']) if 'transform' in kwargs: raise ValueError("'transform' is not allowed as a keyword argument; axvline generates its own transform.") (xmin, xmax) = self.get_xbound() (xx,) = self._process_unit_info([('x', x)], kwargs) scalex = xx < xmin or xx > xmax trans = self.get_xaxis_transform(which='grid') l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs) self.add_line(l) l.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS if scalex: self._request_autoscale_view('x') return l @staticmethod def _check_no_units(vals, names): for (val, name) in zip(vals, names): if not munits._is_natively_supported(val): raise ValueError(f'{name} must be a single scalar value, but got {val}') @_docstring.dedent_interpd def axline(self, xy1, xy2=None, *, slope=None, **kwargs): if slope is not None and (self.get_xscale() != 'linear' or self.get_yscale() != 'linear'): raise TypeError("'slope' cannot be used with non-linear scales") datalim = [xy1] if xy2 is None else [xy1, xy2] if 'transform' in kwargs: datalim = [] line = mlines.AxLine(xy1, xy2, slope, **kwargs) self._set_artist_props(line) if line.get_clip_path() is None: line.set_clip_path(self.patch) if not line.get_label(): line.set_label(f'_child{len(self._children)}') self._children.append(line) line._remove_method = self._children.remove self.update_datalim(datalim) self._request_autoscale_view() return line @_docstring.dedent_interpd def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs): self._check_no_units([xmin, xmax], ['xmin', 'xmax']) ((ymin, ymax),) = self._process_unit_info([('y', [ymin, ymax])], kwargs) p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) p.set_transform(self.get_yaxis_transform(which='grid')) ix = self.dataLim.intervalx.copy() mx = self.dataLim.minposx self.add_patch(p) self.dataLim.intervalx = ix self.dataLim.minposx = mx p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS self._request_autoscale_view('y') return p @_docstring.dedent_interpd def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs): self._check_no_units([ymin, ymax], ['ymin', 'ymax']) ((xmin, xmax),) = self._process_unit_info([('x', [xmin, xmax])], kwargs) p = mpatches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, **kwargs) p.set_transform(self.get_xaxis_transform(which='grid')) iy = self.dataLim.intervaly.copy() my = self.dataLim.minposy self.add_patch(p) self.dataLim.intervaly = iy self.dataLim.minposy = my p.get_path()._interpolation_steps = mpl.axis.GRIDLINE_INTERPOLATION_STEPS self._request_autoscale_view('x') return p @_api.make_keyword_only('3.9', 'label') @_preprocess_data(replace_names=['y', 'xmin', 'xmax', 'colors'], label_namer='y') def hlines(self, y, xmin, xmax, colors=None, linestyles='solid', label='', **kwargs): (xmin, xmax, y) = self._process_unit_info([('x', xmin), ('x', xmax), ('y', y)], kwargs) if not np.iterable(y): y = [y] if not np.iterable(xmin): xmin = [xmin] if not np.iterable(xmax): xmax = [xmax] (y, xmin, xmax) = cbook._combine_masks(y, xmin, xmax) y = np.ravel(y) xmin = np.ravel(xmin) xmax = np.ravel(xmax) masked_verts = np.ma.empty((len(y), 2, 2)) masked_verts[:, 0, 0] = xmin masked_verts[:, 0, 1] = y masked_verts[:, 1, 0] = xmax masked_verts[:, 1, 1] = y lines = mcoll.LineCollection(masked_verts, colors=colors, linestyles=linestyles, label=label) self.add_collection(lines, autolim=False) lines._internal_update(kwargs) if len(y) > 0: updatex = True updatey = True if self.name == 'rectilinear': datalim = lines.get_datalim(self.transData) t = lines.get_transform() (updatex, updatey) = t.contains_branch_seperately(self.transData) minx = np.nanmin(datalim.xmin) maxx = np.nanmax(datalim.xmax) miny = np.nanmin(datalim.ymin) maxy = np.nanmax(datalim.ymax) else: minx = np.nanmin(masked_verts[..., 0]) maxx = np.nanmax(masked_verts[..., 0]) miny = np.nanmin(masked_verts[..., 1]) maxy = np.nanmax(masked_verts[..., 1]) corners = ((minx, miny), (maxx, maxy)) self.update_datalim(corners, updatex, updatey) self._request_autoscale_view() return lines @_api.make_keyword_only('3.9', 'label') @_preprocess_data(replace_names=['x', 'ymin', 'ymax', 'colors'], label_namer='x') def vlines(self, x, ymin, ymax, colors=None, linestyles='solid', label='', **kwargs): (x, ymin, ymax) = self._process_unit_info([('x', x), ('y', ymin), ('y', ymax)], kwargs) if not np.iterable(x): x = [x] if not np.iterable(ymin): ymin = [ymin] if not np.iterable(ymax): ymax = [ymax] (x, ymin, ymax) = cbook._combine_masks(x, ymin, ymax) x = np.ravel(x) ymin = np.ravel(ymin) ymax = np.ravel(ymax) masked_verts = np.ma.empty((len(x), 2, 2)) masked_verts[:, 0, 0] = x masked_verts[:, 0, 1] = ymin masked_verts[:, 1, 0] = x masked_verts[:, 1, 1] = ymax lines = mcoll.LineCollection(masked_verts, colors=colors, linestyles=linestyles, label=label) self.add_collection(lines, autolim=False) lines._internal_update(kwargs) if len(x) > 0: updatex = True updatey = True if self.name == 'rectilinear': datalim = lines.get_datalim(self.transData) t = lines.get_transform() (updatex, updatey) = t.contains_branch_seperately(self.transData) minx = np.nanmin(datalim.xmin) maxx = np.nanmax(datalim.xmax) miny = np.nanmin(datalim.ymin) maxy = np.nanmax(datalim.ymax) else: minx = np.nanmin(masked_verts[..., 0]) maxx = np.nanmax(masked_verts[..., 0]) miny = np.nanmin(masked_verts[..., 1]) maxy = np.nanmax(masked_verts[..., 1]) corners = ((minx, miny), (maxx, maxy)) self.update_datalim(corners, updatex, updatey) self._request_autoscale_view() return lines @_api.make_keyword_only('3.9', 'orientation') @_preprocess_data(replace_names=['positions', 'lineoffsets', 'linelengths', 'linewidths', 'colors', 'linestyles']) @_docstring.dedent_interpd def eventplot(self, positions, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, alpha=None, linestyles='solid', **kwargs): (lineoffsets, linelengths) = self._process_unit_info([('y', lineoffsets), ('y', linelengths)], kwargs) if not np.iterable(positions): positions = [positions] elif any((np.iterable(position) for position in positions)): positions = [np.asanyarray(position) for position in positions] else: positions = [np.asanyarray(positions)] poss = [] for position in positions: poss += self._process_unit_info([('x', position)], kwargs) positions = poss colors = cbook._local_over_kwdict(colors, kwargs, 'color') linewidths = cbook._local_over_kwdict(linewidths, kwargs, 'linewidth') linestyles = cbook._local_over_kwdict(linestyles, kwargs, 'linestyle') if not np.iterable(lineoffsets): lineoffsets = [lineoffsets] if not np.iterable(linelengths): linelengths = [linelengths] if not np.iterable(linewidths): linewidths = [linewidths] if not np.iterable(colors): colors = [colors] if not np.iterable(alpha): alpha = [alpha] if hasattr(linestyles, 'lower') or not np.iterable(linestyles): linestyles = [linestyles] lineoffsets = np.asarray(lineoffsets) linelengths = np.asarray(linelengths) linewidths = np.asarray(linewidths) if len(lineoffsets) == 0: raise ValueError('lineoffsets cannot be empty') if len(linelengths) == 0: raise ValueError('linelengths cannot be empty') if len(linestyles) == 0: raise ValueError('linestyles cannot be empty') if len(linewidths) == 0: raise ValueError('linewidths cannot be empty') if len(alpha) == 0: raise ValueError('alpha cannot be empty') if len(colors) == 0: colors = [None] try: colors = mcolors.to_rgba_array(colors) except ValueError: pass if len(lineoffsets) == 1 and len(positions) != 1: lineoffsets = np.tile(lineoffsets, len(positions)) lineoffsets[0] = 0 lineoffsets = np.cumsum(lineoffsets) if len(linelengths) == 1: linelengths = np.tile(linelengths, len(positions)) if len(linewidths) == 1: linewidths = np.tile(linewidths, len(positions)) if len(colors) == 1: colors = list(colors) * len(positions) if len(alpha) == 1: alpha = list(alpha) * len(positions) if len(linestyles) == 1: linestyles = [linestyles] * len(positions) if len(lineoffsets) != len(positions): raise ValueError('lineoffsets and positions are unequal sized sequences') if len(linelengths) != len(positions): raise ValueError('linelengths and positions are unequal sized sequences') if len(linewidths) != len(positions): raise ValueError('linewidths and positions are unequal sized sequences') if len(colors) != len(positions): raise ValueError('colors and positions are unequal sized sequences') if len(alpha) != len(positions): raise ValueError('alpha and positions are unequal sized sequences') if len(linestyles) != len(positions): raise ValueError('linestyles and positions are unequal sized sequences') colls = [] for (position, lineoffset, linelength, linewidth, color, alpha_, linestyle) in zip(positions, lineoffsets, linelengths, linewidths, colors, alpha, linestyles): coll = mcoll.EventCollection(position, orientation=orientation, lineoffset=lineoffset, linelength=linelength, linewidth=linewidth, color=color, alpha=alpha_, linestyle=linestyle) self.add_collection(coll, autolim=False) coll._internal_update(kwargs) colls.append(coll) if len(positions) > 0: min_max = [(np.min(_p), np.max(_p)) for _p in positions if len(_p) > 0] if len(min_max) > 0: (mins, maxes) = zip(*min_max) minpos = np.min(mins) maxpos = np.max(maxes) minline = (lineoffsets - linelengths).min() maxline = (lineoffsets + linelengths).max() if orientation == 'vertical': corners = ((minline, minpos), (maxline, maxpos)) else: corners = ((minpos, minline), (maxpos, maxline)) self.update_datalim(corners) self._request_autoscale_view() return colls @_docstring.dedent_interpd def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs): kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) lines = [*self._get_lines(self, *args, data=data, **kwargs)] for line in lines: self.add_line(line) if scalex: self._request_autoscale_view('x') if scaley: self._request_autoscale_view('y') return lines @_api.deprecated('3.9', alternative='plot') @_preprocess_data(replace_names=['x', 'y'], label_namer='y') @_docstring.dedent_interpd def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False, **kwargs): if xdate: self.xaxis_date(tz) if ydate: self.yaxis_date(tz) return self.plot(x, y, fmt, **kwargs) @_docstring.dedent_interpd def loglog(self, *args, **kwargs): dx = {k: v for (k, v) in kwargs.items() if k in ['base', 'subs', 'nonpositive', 'basex', 'subsx', 'nonposx']} self.set_xscale('log', **dx) dy = {k: v for (k, v) in kwargs.items() if k in ['base', 'subs', 'nonpositive', 'basey', 'subsy', 'nonposy']} self.set_yscale('log', **dy) return self.plot(*args, **{k: v for (k, v) in kwargs.items() if k not in {*dx, *dy}}) @_docstring.dedent_interpd def semilogx(self, *args, **kwargs): d = {k: v for (k, v) in kwargs.items() if k in ['base', 'subs', 'nonpositive', 'basex', 'subsx', 'nonposx']} self.set_xscale('log', **d) return self.plot(*args, **{k: v for (k, v) in kwargs.items() if k not in d}) @_docstring.dedent_interpd def semilogy(self, *args, **kwargs): d = {k: v for (k, v) in kwargs.items() if k in ['base', 'subs', 'nonpositive', 'basey', 'subsy', 'nonposy']} self.set_yscale('log', **d) return self.plot(*args, **{k: v for (k, v) in kwargs.items() if k not in d}) @_preprocess_data(replace_names=['x'], label_namer='x') def acorr(self, x, **kwargs): return self.xcorr(x, x, **kwargs) @_api.make_keyword_only('3.9', 'normed') @_preprocess_data(replace_names=['x', 'y'], label_namer='y') def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, usevlines=True, maxlags=10, **kwargs): Nx = len(x) if Nx != len(y): raise ValueError('x and y must be equal length') x = detrend(np.asarray(x)) y = detrend(np.asarray(y)) correls = np.correlate(x, y, mode='full') if normed: correls = correls / np.sqrt(np.dot(x, x) * np.dot(y, y)) if maxlags is None: maxlags = Nx - 1 if maxlags >= Nx or maxlags < 1: raise ValueError('maxlags must be None or strictly positive < %d' % Nx) lags = np.arange(-maxlags, maxlags + 1) correls = correls[Nx - 1 - maxlags:Nx + maxlags] if usevlines: a = self.vlines(lags, [0], correls, **kwargs) kwargs.pop('label', '') b = self.axhline(**kwargs) else: kwargs.setdefault('marker', 'o') kwargs.setdefault('linestyle', 'None') (a,) = self.plot(lags, correls, **kwargs) b = None return (lags, correls, a, b) def step(self, x, y, *args, where='pre', data=None, **kwargs): _api.check_in_list(('pre', 'post', 'mid'), where=where) kwargs['drawstyle'] = 'steps-' + where return self.plot(x, y, *args, data=data, **kwargs) @staticmethod def _convert_dx(dx, x0, xconv, convert): assert type(xconv) is np.ndarray if xconv.size == 0: return convert(dx) try: try: x0 = cbook._safe_first_finite(x0) except (TypeError, IndexError, KeyError): pass try: x = cbook._safe_first_finite(xconv) except (TypeError, IndexError, KeyError): x = xconv delist = False if not np.iterable(dx): dx = [dx] delist = True dx = [convert(x0 + ddx) - x for ddx in dx] if delist: dx = dx[0] except (ValueError, TypeError, AttributeError): dx = convert(dx) return dx @_preprocess_data() @_docstring.dedent_interpd def bar(self, x, height, width=0.8, bottom=None, *, align='center', **kwargs): kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch) color = kwargs.pop('color', None) if color is None: color = self._get_patches_for_fill.get_next_color() edgecolor = kwargs.pop('edgecolor', None) linewidth = kwargs.pop('linewidth', None) hatch = kwargs.pop('hatch', None) xerr = kwargs.pop('xerr', None) yerr = kwargs.pop('yerr', None) error_kw = kwargs.pop('error_kw', None) error_kw = {} if error_kw is None else error_kw.copy() ezorder = error_kw.pop('zorder', None) if ezorder is None: ezorder = kwargs.get('zorder', None) if ezorder is not None: ezorder += 0.01 error_kw.setdefault('zorder', ezorder) ecolor = kwargs.pop('ecolor', 'k') capsize = kwargs.pop('capsize', mpl.rcParams['errorbar.capsize']) error_kw.setdefault('ecolor', ecolor) error_kw.setdefault('capsize', capsize) orientation = kwargs.pop('orientation', 'vertical') _api.check_in_list(['vertical', 'horizontal'], orientation=orientation) log = kwargs.pop('log', False) label = kwargs.pop('label', '') tick_labels = kwargs.pop('tick_label', None) y = bottom if orientation == 'vertical': if y is None: y = 0 elif x is None: x = 0 if orientation == 'vertical': self._process_unit_info([('x', x), ('y', y), ('y', height)], kwargs, convert=False) if log: self.set_yscale('log', nonpositive='clip') else: self._process_unit_info([('x', x), ('x', width), ('y', y)], kwargs, convert=False) if log: self.set_xscale('log', nonpositive='clip') if self.xaxis is not None: x0 = x x = np.asarray(self.convert_xunits(x)) width = self._convert_dx(width, x0, x, self.convert_xunits) if xerr is not None: xerr = self._convert_dx(xerr, x0, x, self.convert_xunits) if self.yaxis is not None: y0 = y y = np.asarray(self.convert_yunits(y)) height = self._convert_dx(height, y0, y, self.convert_yunits) if yerr is not None: yerr = self._convert_dx(yerr, y0, y, self.convert_yunits) (x, height, width, y, linewidth, hatch) = np.broadcast_arrays(np.atleast_1d(x), height, width, y, linewidth, hatch) if orientation == 'vertical': tick_label_axis = self.xaxis tick_label_position = x else: tick_label_axis = self.yaxis tick_label_position = y if not isinstance(label, str) and np.iterable(label): bar_container_label = '_nolegend_' patch_labels = label else: bar_container_label = label patch_labels = ['_nolegend_'] * len(x) if len(patch_labels) != len(x): raise ValueError(f'number of labels ({len(patch_labels)}) does not match number of bars ({len(x)}).') linewidth = itertools.cycle(np.atleast_1d(linewidth)) hatch = itertools.cycle(np.atleast_1d(hatch)) color = itertools.chain(itertools.cycle(mcolors.to_rgba_array(color)), itertools.repeat('none')) if edgecolor is None: edgecolor = itertools.repeat(None) else: edgecolor = itertools.chain(itertools.cycle(mcolors.to_rgba_array(edgecolor)), itertools.repeat('none')) _api.check_in_list(['center', 'edge'], align=align) if align == 'center': if orientation == 'vertical': try: left = x - width / 2 except TypeError as e: raise TypeError(f'the dtypes of parameters x ({x.dtype}) and width ({width.dtype}) are incompatible') from e bottom = y else: try: bottom = y - height / 2 except TypeError as e: raise TypeError(f'the dtypes of parameters y ({y.dtype}) and height ({height.dtype}) are incompatible') from e left = x else: left = x bottom = y patches = [] args = zip(left, bottom, width, height, color, edgecolor, linewidth, hatch, patch_labels) for (l, b, w, h, c, e, lw, htch, lbl) in args: r = mpatches.Rectangle(xy=(l, b), width=w, height=h, facecolor=c, edgecolor=e, linewidth=lw, label=lbl, hatch=htch) r._internal_update(kwargs) r.get_path()._interpolation_steps = 100 if orientation == 'vertical': r.sticky_edges.y.append(b) else: r.sticky_edges.x.append(l) self.add_patch(r) patches.append(r) if xerr is not None or yerr is not None: if orientation == 'vertical': ex = [l + 0.5 * w for (l, w) in zip(left, width)] ey = [b + h for (b, h) in zip(bottom, height)] else: ex = [l + w for (l, w) in zip(left, width)] ey = [b + 0.5 * h for (b, h) in zip(bottom, height)] error_kw.setdefault('label', '_nolegend_') errorbar = self.errorbar(ex, ey, yerr=yerr, xerr=xerr, fmt='none', **error_kw) else: errorbar = None self._request_autoscale_view() if orientation == 'vertical': datavalues = height else: datavalues = width bar_container = BarContainer(patches, errorbar, datavalues=datavalues, orientation=orientation, label=bar_container_label) self.add_container(bar_container) if tick_labels is not None: tick_labels = np.broadcast_to(tick_labels, len(patches)) tick_label_axis.set_ticks(tick_label_position) tick_label_axis.set_ticklabels(tick_labels) return bar_container @_docstring.dedent_interpd def barh(self, y, width, height=0.8, left=None, *, align='center', data=None, **kwargs): kwargs.setdefault('orientation', 'horizontal') patches = self.bar(x=left, height=height, width=width, bottom=y, align=align, data=data, **kwargs) return patches def bar_label(self, container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs): for key in ['horizontalalignment', 'ha', 'verticalalignment', 'va']: if key in kwargs: raise ValueError(f'Passing {key!r} to bar_label() is not supported.') (a, b) = self.yaxis.get_view_interval() y_inverted = a > b (c, d) = self.xaxis.get_view_interval() x_inverted = c > d def sign(x): return 1 if x >= 0 else -1 _api.check_in_list(['edge', 'center'], label_type=label_type) bars = container.patches errorbar = container.errorbar datavalues = container.datavalues orientation = container.orientation if errorbar: lines = errorbar.lines barlinecols = lines[2] barlinecol = barlinecols[0] errs = barlinecol.get_segments() else: errs = [] if labels is None: labels = [] annotations = [] for (bar, err, dat, lbl) in itertools.zip_longest(bars, errs, datavalues, labels): ((x0, y0), (x1, y1)) = bar.get_bbox().get_points() (xc, yc) = ((x0 + x1) / 2, (y0 + y1) / 2) if orientation == 'vertical': extrema = max(y0, y1) if dat >= 0 else min(y0, y1) length = abs(y0 - y1) else: extrema = max(x0, x1) if dat >= 0 else min(x0, x1) length = abs(x0 - x1) if err is None or np.size(err) == 0: endpt = extrema elif orientation == 'vertical': endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min() else: endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min() if label_type == 'center': value = sign(dat) * length else: value = extrema if label_type == 'center': xy = (0.5, 0.5) kwargs['xycoords'] = lambda r, b=bar: mtransforms.Bbox.intersection(b.get_window_extent(r), b.get_clip_box()) or mtransforms.Bbox.null() elif orientation == 'vertical': xy = (xc, endpt) else: xy = (endpt, yc) if orientation == 'vertical': y_direction = -1 if y_inverted else 1 xytext = (0, y_direction * sign(dat) * padding) else: x_direction = -1 if x_inverted else 1 xytext = (x_direction * sign(dat) * padding, 0) if label_type == 'center': (ha, va) = ('center', 'center') elif orientation == 'vertical': ha = 'center' if y_inverted: va = 'top' if dat > 0 else 'bottom' else: va = 'top' if dat < 0 else 'bottom' else: if x_inverted: ha = 'right' if dat > 0 else 'left' else: ha = 'right' if dat < 0 else 'left' va = 'center' if np.isnan(dat): lbl = '' if lbl is None: if isinstance(fmt, str): lbl = cbook._auto_format_str(fmt, value) elif callable(fmt): lbl = fmt(value) else: raise TypeError('fmt must be a str or callable') annotation = self.annotate(lbl, xy, xytext, textcoords='offset points', ha=ha, va=va, **kwargs) annotations.append(annotation) return annotations @_preprocess_data() @_docstring.dedent_interpd def broken_barh(self, xranges, yrange, **kwargs): xdata = cbook._safe_first_finite(xranges) if len(xranges) else None ydata = cbook._safe_first_finite(yrange) if len(yrange) else None self._process_unit_info([('x', xdata), ('y', ydata)], kwargs, convert=False) vertices = [] (y0, dy) = yrange (y0, y1) = self.convert_yunits((y0, y0 + dy)) for xr in xranges: try: (x0, dx) = xr except Exception: raise ValueError('each range in xrange must be a sequence with two elements (i.e. xrange must be an (N, 2) array)') from None (x0, x1) = self.convert_xunits((x0, x0 + dx)) vertices.append([(x0, y0), (x0, y1), (x1, y1), (x1, y0)]) col = mcoll.PolyCollection(np.array(vertices), **kwargs) self.add_collection(col, autolim=True) self._request_autoscale_view() return col @_preprocess_data() def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, orientation='vertical'): if not 1 <= len(args) <= 3: raise _api.nargs_error('stem', '1-3', len(args)) _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) if len(args) == 1: (heads,) = args locs = np.arange(len(heads)) args = () elif isinstance(args[1], str): (heads, *args) = args locs = np.arange(len(heads)) else: (locs, heads, *args) = args if orientation == 'vertical': (locs, heads) = self._process_unit_info([('x', locs), ('y', heads)]) else: (heads, locs) = self._process_unit_info([('x', heads), ('y', locs)]) if linefmt is None: linefmt = args[0] if len(args) > 0 else 'C0-' (linestyle, linemarker, linecolor) = _process_plot_format(linefmt) if markerfmt is None: markerfmt = 'o' if markerfmt == '': markerfmt = ' ' (markerstyle, markermarker, markercolor) = _process_plot_format(markerfmt) if markermarker is None: markermarker = 'o' if markerstyle is None: markerstyle = 'None' if markercolor is None: markercolor = linecolor if basefmt is None: basefmt = 'C2-' if mpl.rcParams['_internal.classic_mode'] else 'C3-' (basestyle, basemarker, basecolor) = _process_plot_format(basefmt) if linestyle is None: linestyle = mpl.rcParams['lines.linestyle'] xlines = self.vlines if orientation == 'vertical' else self.hlines stemlines = xlines(locs, bottom, heads, colors=linecolor, linestyles=linestyle, label='_nolegend_') if orientation == 'horizontal': marker_x = heads marker_y = locs baseline_x = [bottom, bottom] baseline_y = [np.min(locs), np.max(locs)] else: marker_x = locs marker_y = heads baseline_x = [np.min(locs), np.max(locs)] baseline_y = [bottom, bottom] (markerline,) = self.plot(marker_x, marker_y, color=markercolor, linestyle=markerstyle, marker=markermarker, label='_nolegend_') (baseline,) = self.plot(baseline_x, baseline_y, color=basecolor, linestyle=basestyle, marker=basemarker, label='_nolegend_') stem_container = StemContainer((markerline, stemlines, baseline), label=label) self.add_container(stem_container) return stem_container @_api.make_keyword_only('3.9', 'explode') @_preprocess_data(replace_names=['x', 'explode', 'labels', 'colors']) def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=True, hatch=None): self.set_aspect('equal') x = np.asarray(x, np.float32) if x.ndim > 1: raise ValueError('x must be 1D') if np.any(x < 0): raise ValueError("Wedge sizes 'x' must be non negative values") sx = x.sum() if normalize: x = x / sx elif sx > 1: raise ValueError('Cannot plot an unnormalized pie with sum(x) > 1') if labels is None: labels = [''] * len(x) if explode is None: explode = [0] * len(x) if len(x) != len(labels): raise ValueError("'label' must be of length 'x'") if len(x) != len(explode): raise ValueError("'explode' must be of length 'x'") if colors is None: get_next_color = self._get_patches_for_fill.get_next_color else: color_cycle = itertools.cycle(colors) def get_next_color(): return next(color_cycle) hatch_cycle = itertools.cycle(np.atleast_1d(hatch)) _api.check_isinstance(Real, radius=radius, startangle=startangle) if radius <= 0: raise ValueError(f'radius must be a positive number, not {radius}') theta1 = startangle / 360 if wedgeprops is None: wedgeprops = {} if textprops is None: textprops = {} texts = [] slices = [] autotexts = [] for (frac, label, expl) in zip(x, labels, explode): (x, y) = center theta2 = theta1 + frac if counterclock else theta1 - frac thetam = 2 * np.pi * 0.5 * (theta1 + theta2) x += expl * math.cos(thetam) y += expl * math.sin(thetam) w = mpatches.Wedge((x, y), radius, 360.0 * min(theta1, theta2), 360.0 * max(theta1, theta2), facecolor=get_next_color(), hatch=next(hatch_cycle), clip_on=False, label=label) w.set(**wedgeprops) slices.append(w) self.add_patch(w) if shadow: shadow_dict = {'ox': -0.02, 'oy': -0.02, 'label': '_nolegend_'} if isinstance(shadow, dict): shadow_dict.update(shadow) self.add_patch(mpatches.Shadow(w, **shadow_dict)) if labeldistance is not None: xt = x + labeldistance * radius * math.cos(thetam) yt = y + labeldistance * radius * math.sin(thetam) label_alignment_h = 'left' if xt > 0 else 'right' label_alignment_v = 'center' label_rotation = 'horizontal' if rotatelabels: label_alignment_v = 'bottom' if yt > 0 else 'top' label_rotation = np.rad2deg(thetam) + (0 if xt > 0 else 180) t = self.text(xt, yt, label, clip_on=False, horizontalalignment=label_alignment_h, verticalalignment=label_alignment_v, rotation=label_rotation, size=mpl.rcParams['xtick.labelsize']) t.set(**textprops) texts.append(t) if autopct is not None: xt = x + pctdistance * radius * math.cos(thetam) yt = y + pctdistance * radius * math.sin(thetam) if isinstance(autopct, str): s = autopct % (100.0 * frac) elif callable(autopct): s = autopct(100.0 * frac) else: raise TypeError('autopct must be callable or a format string') if mpl._val_or_rc(textprops.get('usetex'), 'text.usetex'): s = re.sub('([^\\\\])%', '\\1\\\\%', s) t = self.text(xt, yt, s, clip_on=False, horizontalalignment='center', verticalalignment='center') t.set(**textprops) autotexts.append(t) theta1 = theta2 if frame: self._request_autoscale_view() else: self.set(frame_on=False, xticks=[], yticks=[], xlim=(-1.25 + center[0], 1.25 + center[0]), ylim=(-1.25 + center[1], 1.25 + center[1])) if autopct is None: return (slices, texts) else: return (slices, texts, autotexts) @staticmethod def _errorevery_to_mask(x, errorevery): if isinstance(errorevery, Integral): errorevery = (0, errorevery) if isinstance(errorevery, tuple): if len(errorevery) == 2 and isinstance(errorevery[0], Integral) and isinstance(errorevery[1], Integral): errorevery = slice(errorevery[0], None, errorevery[1]) else: raise ValueError(f'errorevery={errorevery!r} is a not a tuple of two integers') elif isinstance(errorevery, slice): pass elif not isinstance(errorevery, str) and np.iterable(errorevery): try: x[errorevery] except (ValueError, IndexError) as err: raise ValueError(f"errorevery={errorevery!r} is iterable but not a valid NumPy fancy index to match 'xerr'/'yerr'") from err else: raise ValueError(f'errorevery={errorevery!r} is not a recognized value') everymask = np.zeros(len(x), bool) everymask[errorevery] = True return everymask @_api.make_keyword_only('3.9', 'ecolor') @_preprocess_data(replace_names=['x', 'y', 'xerr', 'yerr'], label_namer='y') @_docstring.dedent_interpd def errorbar(self, x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, **kwargs): kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) kwargs = {k: v for (k, v) in kwargs.items() if v is not None} kwargs.setdefault('zorder', 2) if not isinstance(x, np.ndarray): x = np.asarray(x, dtype=object) if not isinstance(y, np.ndarray): y = np.asarray(y, dtype=object) def _upcast_err(err): if np.iterable(err) and len(err) > 0 and isinstance(cbook._safe_first_finite(err), np.ndarray): atype = type(cbook._safe_first_finite(err)) if atype is np.ndarray: return np.asarray(err, dtype=object) return atype(err) return np.asarray(err, dtype=object) if xerr is not None and (not isinstance(xerr, np.ndarray)): xerr = _upcast_err(xerr) if yerr is not None and (not isinstance(yerr, np.ndarray)): yerr = _upcast_err(yerr) (x, y) = np.atleast_1d(x, y) if len(x) != len(y): raise ValueError("'x' and 'y' must have the same size") everymask = self._errorevery_to_mask(x, errorevery) label = kwargs.pop('label', None) kwargs['label'] = '_nolegend_' ((data_line, base_style),) = self._get_lines._plot_args(self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True) if barsabove: data_line.set_zorder(kwargs['zorder'] - 0.1) else: data_line.set_zorder(kwargs['zorder'] + 0.1) if fmt.lower() != 'none': self.add_line(data_line) else: data_line = None base_style.pop('color') if 'color' in kwargs: base_style['color'] = kwargs.pop('color') if 'color' not in base_style: base_style['color'] = 'C0' if ecolor is None: ecolor = base_style['color'] for key in ['marker', 'markersize', 'markerfacecolor', 'markerfacecoloralt', 'markeredgewidth', 'markeredgecolor', 'markevery', 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle', 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle', 'dashes']: base_style.pop(key, None) eb_lines_style = {**base_style, 'color': ecolor} if elinewidth is not None: eb_lines_style['linewidth'] = elinewidth elif 'linewidth' in kwargs: eb_lines_style['linewidth'] = kwargs['linewidth'] for key in ('transform', 'alpha', 'zorder', 'rasterized'): if key in kwargs: eb_lines_style[key] = kwargs[key] eb_cap_style = {**base_style, 'linestyle': 'none'} if capsize is None: capsize = mpl.rcParams['errorbar.capsize'] if capsize > 0: eb_cap_style['markersize'] = 2.0 * capsize if capthick is not None: eb_cap_style['markeredgewidth'] = capthick for key in ('markeredgewidth', 'transform', 'alpha', 'zorder', 'rasterized'): if key in kwargs: eb_cap_style[key] = kwargs[key] eb_cap_style['color'] = ecolor barcols = [] caplines = {'x': [], 'y': []} def apply_mask(arrays, mask): return [array[mask] for array in arrays] for (dep_axis, dep, err, lolims, uplims, indep, lines_func, marker, lomarker, himarker) in [('x', x, xerr, xlolims, xuplims, y, self.hlines, '|', mlines.CARETRIGHTBASE, mlines.CARETLEFTBASE), ('y', y, yerr, lolims, uplims, x, self.vlines, '_', mlines.CARETUPBASE, mlines.CARETDOWNBASE)]: if err is None: continue lolims = np.broadcast_to(lolims, len(dep)).astype(bool) uplims = np.broadcast_to(uplims, len(dep)).astype(bool) try: np.broadcast_to(err, (2, len(dep))) except ValueError: raise ValueError(f"'{dep_axis}err' (shape: {np.shape(err)}) must be a scalar or a 1D or (2, n) array-like whose shape matches '{dep_axis}' (shape: {np.shape(dep)})") from None if err.dtype is np.dtype(object) and np.any(err == None): raise ValueError(f"'{dep_axis}err' must not contain None. Use NaN if you want to skip a value.") res = np.zeros(err.shape, dtype=bool) if np.any(np.less(err, -err, out=res, where=err == err)): raise ValueError(f"'{dep_axis}err' must not contain negative values") (low, high) = dep + np.vstack([-(1 - lolims), 1 - uplims]) * err barcols.append(lines_func(*apply_mask([indep, low, high], everymask), **eb_lines_style)) if self.name == 'polar' and dep_axis == 'x': for b in barcols: for p in b.get_paths(): p._interpolation_steps = 2 nolims = ~(lolims | uplims) if nolims.any() and capsize > 0: (indep_masked, lo_masked, hi_masked) = apply_mask([indep, low, high], nolims & everymask) for lh_masked in [lo_masked, hi_masked]: line = mlines.Line2D(indep_masked, indep_masked, marker=marker, **eb_cap_style) line.set(**{f'{dep_axis}data': lh_masked}) caplines[dep_axis].append(line) for (idx, (lims, hl)) in enumerate([(lolims, high), (uplims, low)]): if not lims.any(): continue hlmarker = himarker if self._axis_map[dep_axis].get_inverted() ^ idx else lomarker (x_masked, y_masked, hl_masked) = apply_mask([x, y, hl], lims & everymask) line = mlines.Line2D(x_masked, y_masked, marker=hlmarker, **eb_cap_style) line.set(**{f'{dep_axis}data': hl_masked}) caplines[dep_axis].append(line) if capsize > 0: caplines[dep_axis].append(mlines.Line2D(x_masked, y_masked, marker=marker, **eb_cap_style)) if self.name == 'polar': for axis in caplines: for l in caplines[axis]: for (theta, r) in zip(l.get_xdata(), l.get_ydata()): rotation = mtransforms.Affine2D().rotate(theta) if axis == 'y': rotation.rotate(-np.pi / 2) ms = mmarkers.MarkerStyle(marker=marker, transform=rotation) self.add_line(mlines.Line2D([theta], [r], marker=ms, **eb_cap_style)) else: for axis in caplines: for l in caplines[axis]: self.add_line(l) self._request_autoscale_view() caplines = caplines['x'] + caplines['y'] errorbar_container = ErrorbarContainer((data_line, tuple(caplines), tuple(barcols)), has_xerr=xerr is not None, has_yerr=yerr is not None, label=label) self.containers.append(errorbar_container) return errorbar_container @_api.make_keyword_only('3.9', 'notch') @_preprocess_data() @_api.rename_parameter('3.9', 'labels', 'tick_labels') def boxplot(self, x, notch=None, sym=None, vert=None, orientation='vertical', whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, tick_labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, capwidths=None, label=None): if whis is None: whis = mpl.rcParams['boxplot.whiskers'] if bootstrap is None: bootstrap = mpl.rcParams['boxplot.bootstrap'] bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap, labels=tick_labels, autorange=autorange) if notch is None: notch = mpl.rcParams['boxplot.notch'] if patch_artist is None: patch_artist = mpl.rcParams['boxplot.patchartist'] if meanline is None: meanline = mpl.rcParams['boxplot.meanline'] if showmeans is None: showmeans = mpl.rcParams['boxplot.showmeans'] if showcaps is None: showcaps = mpl.rcParams['boxplot.showcaps'] if showbox is None: showbox = mpl.rcParams['boxplot.showbox'] if showfliers is None: showfliers = mpl.rcParams['boxplot.showfliers'] if boxprops is None: boxprops = {} if whiskerprops is None: whiskerprops = {} if capprops is None: capprops = {} if medianprops is None: medianprops = {} if meanprops is None: meanprops = {} if flierprops is None: flierprops = {} if patch_artist: boxprops['linestyle'] = 'solid' if 'color' in boxprops: boxprops['edgecolor'] = boxprops.pop('color') if sym is not None: if sym == '': flierprops = dict(linestyle='none', marker='', color='none') showfliers = False else: (_, marker, color) = _process_plot_format(sym) if marker is not None: flierprops['marker'] = marker if color is not None: flierprops['color'] = color flierprops['markerfacecolor'] = color flierprops['markeredgecolor'] = color if usermedians is not None: if len(np.ravel(usermedians)) != len(bxpstats) or np.shape(usermedians)[0] != len(bxpstats): raise ValueError("'usermedians' and 'x' have different lengths") else: for (stats, med) in zip(bxpstats, usermedians): if med is not None: stats['med'] = med if conf_intervals is not None: if len(conf_intervals) != len(bxpstats): raise ValueError("'conf_intervals' and 'x' have different lengths") else: for (stats, ci) in zip(bxpstats, conf_intervals): if ci is not None: if len(ci) != 2: raise ValueError('each confidence interval must have two values') else: if ci[0] is not None: stats['cilo'] = ci[0] if ci[1] is not None: stats['cihi'] = ci[1] artists = self.bxp(bxpstats, positions=positions, widths=widths, vert=vert, patch_artist=patch_artist, shownotches=notch, showmeans=showmeans, showcaps=showcaps, showbox=showbox, boxprops=boxprops, flierprops=flierprops, medianprops=medianprops, meanprops=meanprops, meanline=meanline, showfliers=showfliers, capprops=capprops, whiskerprops=whiskerprops, manage_ticks=manage_ticks, zorder=zorder, capwidths=capwidths, label=label, orientation=orientation) return artists @_api.make_keyword_only('3.9', 'widths') def bxp(self, bxpstats, positions=None, widths=None, vert=None, orientation='vertical', patch_artist=False, shownotches=False, showmeans=False, showcaps=True, showbox=True, showfliers=True, boxprops=None, whiskerprops=None, flierprops=None, medianprops=None, capprops=None, meanprops=None, meanline=False, manage_ticks=True, zorder=None, capwidths=None, label=None): medianprops = {'solid_capstyle': 'butt', 'dash_capstyle': 'butt', **(medianprops or {})} meanprops = {'solid_capstyle': 'butt', 'dash_capstyle': 'butt', **(meanprops or {})} whiskers = [] caps = [] boxes = [] medians = [] means = [] fliers = [] datalabels = [] if zorder is None: zorder = mlines.Line2D.zorder zdelta = 0.1 def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True): d = {k.split('.')[-1]: v for (k, v) in mpl.rcParams.items() if k.startswith(f'boxplot.{subkey}props')} d['zorder'] = zorder + zdelta if not usemarker: d['marker'] = '' d.update(cbook.normalize_kwargs(explicit, mlines.Line2D)) return d box_kw = {'linestyle': mpl.rcParams['boxplot.boxprops.linestyle'], 'linewidth': mpl.rcParams['boxplot.boxprops.linewidth'], 'edgecolor': mpl.rcParams['boxplot.boxprops.color'], 'facecolor': 'white' if mpl.rcParams['_internal.classic_mode'] else mpl.rcParams['patch.facecolor'], 'zorder': zorder, **cbook.normalize_kwargs(boxprops, mpatches.PathPatch)} if patch_artist else merge_kw_rc('box', boxprops, usemarker=False) whisker_kw = merge_kw_rc('whisker', whiskerprops, usemarker=False) cap_kw = merge_kw_rc('cap', capprops, usemarker=False) flier_kw = merge_kw_rc('flier', flierprops) median_kw = merge_kw_rc('median', medianprops, zdelta, usemarker=False) mean_kw = merge_kw_rc('mean', meanprops, zdelta) removed_prop = 'marker' if meanline else 'linestyle' if meanprops is None or removed_prop not in meanprops: mean_kw[removed_prop] = '' if vert is None: vert = mpl.rcParams['boxplot.vertical'] else: _api.warn_deprecated('3.10', name='vert: bool', alternative="orientation: {'vertical', 'horizontal'}") if vert is False: orientation = 'horizontal' _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) if not mpl.rcParams['boxplot.vertical']: _api.warn_deprecated('3.10', name='boxplot.vertical', obj_type='rcparam') maybe_swap = slice(None) if orientation == 'vertical' else slice(None, None, -1) def do_plot(xs, ys, **kwargs): return self.plot(*[xs, ys][maybe_swap], **kwargs)[0] def do_patch(xs, ys, **kwargs): path = mpath.Path._create_closed(np.column_stack([xs, ys][maybe_swap])) patch = mpatches.PathPatch(path, **kwargs) self.add_artist(patch) return patch N = len(bxpstats) datashape_message = 'List of boxplot statistics and `{0}` values must have same the length' if positions is None: positions = list(range(1, N + 1)) elif len(positions) != N: raise ValueError(datashape_message.format('positions')) positions = np.array(positions) if len(positions) > 0 and (not all((isinstance(p, Real) for p in positions))): raise TypeError('positions should be an iterable of numbers') if widths is None: widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N elif np.isscalar(widths): widths = [widths] * N elif len(widths) != N: raise ValueError(datashape_message.format('widths')) if capwidths is None: capwidths = 0.5 * np.array(widths) elif np.isscalar(capwidths): capwidths = [capwidths] * N elif len(capwidths) != N: raise ValueError(datashape_message.format('capwidths')) for (pos, width, stats, capwidth) in zip(positions, widths, bxpstats, capwidths): datalabels.append(stats.get('label', pos)) whis_x = [pos, pos] whislo_y = [stats['q1'], stats['whislo']] whishi_y = [stats['q3'], stats['whishi']] cap_left = pos - capwidth * 0.5 cap_right = pos + capwidth * 0.5 cap_x = [cap_left, cap_right] cap_lo = np.full(2, stats['whislo']) cap_hi = np.full(2, stats['whishi']) box_left = pos - width * 0.5 box_right = pos + width * 0.5 med_y = [stats['med'], stats['med']] if shownotches: notch_left = pos - width * 0.25 notch_right = pos + width * 0.25 box_x = [box_left, box_right, box_right, notch_right, box_right, box_right, box_left, box_left, notch_left, box_left, box_left] box_y = [stats['q1'], stats['q1'], stats['cilo'], stats['med'], stats['cihi'], stats['q3'], stats['q3'], stats['cihi'], stats['med'], stats['cilo'], stats['q1']] med_x = [notch_left, notch_right] else: box_x = [box_left, box_right, box_right, box_left, box_left] box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'], stats['q1']] med_x = [box_left, box_right] if showbox: do_box = do_patch if patch_artist else do_plot boxes.append(do_box(box_x, box_y, **box_kw)) median_kw.setdefault('label', '_nolegend_') whisker_kw.setdefault('label', '_nolegend_') whiskers.append(do_plot(whis_x, whislo_y, **whisker_kw)) whiskers.append(do_plot(whis_x, whishi_y, **whisker_kw)) if showcaps: cap_kw.setdefault('label', '_nolegend_') caps.append(do_plot(cap_x, cap_lo, **cap_kw)) caps.append(do_plot(cap_x, cap_hi, **cap_kw)) medians.append(do_plot(med_x, med_y, **median_kw)) if showmeans: if meanline: means.append(do_plot([box_left, box_right], [stats['mean'], stats['mean']], **mean_kw)) else: means.append(do_plot([pos], [stats['mean']], **mean_kw)) if showfliers: flier_kw.setdefault('label', '_nolegend_') flier_x = np.full(len(stats['fliers']), pos, dtype=np.float64) flier_y = stats['fliers'] fliers.append(do_plot(flier_x, flier_y, **flier_kw)) if label: box_or_med = boxes if showbox and patch_artist else medians if cbook.is_scalar_or_string(label): box_or_med[0].set_label(label) else: if len(box_or_med) != len(label): raise ValueError(datashape_message.format('label')) for (artist, lbl) in zip(box_or_med, label): artist.set_label(lbl) if manage_ticks: axis_name = 'x' if orientation == 'vertical' else 'y' interval = getattr(self.dataLim, f'interval{axis_name}') axis = self._axis_map[axis_name] positions = axis.convert_units(positions) interval[:] = (min(interval[0], min(positions) - 0.5), max(interval[1], max(positions) + 0.5)) for (median, position) in zip(medians, positions): getattr(median.sticky_edges, axis_name).extend([position - 0.5, position + 0.5]) locator = axis.get_major_locator() if not isinstance(axis.get_major_locator(), mticker.FixedLocator): locator = mticker.FixedLocator([]) axis.set_major_locator(locator) locator.locs = np.array([*locator.locs, *positions]) formatter = axis.get_major_formatter() if not isinstance(axis.get_major_formatter(), mticker.FixedFormatter): formatter = mticker.FixedFormatter([]) axis.set_major_formatter(formatter) formatter.seq = [*formatter.seq, *datalabels] self._request_autoscale_view() return dict(whiskers=whiskers, caps=caps, boxes=boxes, medians=medians, fliers=fliers, means=means) @staticmethod def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, get_next_color_func): facecolors = kwargs.pop('facecolors', None) facecolors = kwargs.pop('facecolor', facecolors) edgecolors = kwargs.pop('edgecolor', edgecolors) kwcolor = kwargs.pop('color', None) if kwcolor is not None and c is not None: raise ValueError("Supply a 'c' argument or a 'color' kwarg but not both; they differ but their functionalities overlap.") if kwcolor is not None: try: mcolors.to_rgba_array(kwcolor) except ValueError as err: raise ValueError("'color' kwarg must be a color or sequence of color specs. For a sequence of values to be color-mapped, use the 'c' argument instead.") from err if edgecolors is None: edgecolors = kwcolor if facecolors is None: facecolors = kwcolor if edgecolors is None and (not mpl.rcParams['_internal.classic_mode']): edgecolors = mpl.rcParams['scatter.edgecolors'] c_was_none = c is None if c is None: c = facecolors if facecolors is not None else 'b' if mpl.rcParams['_internal.classic_mode'] else get_next_color_func() c_is_string_or_strings = isinstance(c, str) or (np.iterable(c) and len(c) > 0 and isinstance(cbook._safe_first_finite(c), str)) def invalid_shape_exception(csize, xsize): return ValueError(f"'c' argument has {csize} elements, which is inconsistent with 'x' and 'y' with size {xsize}.") c_is_mapped = False valid_shape = True if not c_was_none and kwcolor is None and (not c_is_string_or_strings): try: c = np.asanyarray(c, dtype=float) except ValueError: pass else: if c.shape == (1, 4) or c.shape == (1, 3): c_is_mapped = False if c.size != xsize: valid_shape = False elif c.size == xsize: c = c.ravel() c_is_mapped = True else: if c.shape in ((3,), (4,)): _api.warn_external('*c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*. Please use the *color* keyword-argument or provide a 2D array with a single row if you intend to specify the same RGB or RGBA value for all points.') valid_shape = False if not c_is_mapped: try: colors = mcolors.to_rgba_array(c) except (TypeError, ValueError) as err: if 'RGBA values should be within 0-1 range' in str(err): raise else: if not valid_shape: raise invalid_shape_exception(c.size, xsize) from err raise ValueError(f"'c' argument must be a color, a sequence of colors, or a sequence of numbers, not {c!r}") from err else: if len(colors) not in (0, 1, xsize): raise invalid_shape_exception(len(colors), xsize) else: colors = None return (c, colors, edgecolors) @_api.make_keyword_only('3.9', 'marker') @_preprocess_data(replace_names=['x', 'y', 's', 'linewidths', 'edgecolors', 'c', 'facecolor', 'facecolors', 'color'], label_namer='y') @_docstring.interpd def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, **kwargs): if edgecolors is not None: kwargs.update({'edgecolors': edgecolors}) if linewidths is not None: kwargs.update({'linewidths': linewidths}) kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) linewidths = kwargs.pop('linewidth', None) edgecolors = kwargs.pop('edgecolor', None) (x, y) = self._process_unit_info([('x', x), ('y', y)], kwargs) x = np.ma.ravel(x) y = np.ma.ravel(y) if x.size != y.size: raise ValueError('x and y must be the same size') if s is None: s = 20 if mpl.rcParams['_internal.classic_mode'] else mpl.rcParams['lines.markersize'] ** 2.0 s = np.ma.ravel(s) if len(s) not in (1, x.size) or (not np.issubdtype(s.dtype, np.floating) and (not np.issubdtype(s.dtype, np.integer))): raise ValueError('s must be a scalar, or float array-like with the same size as x and y') orig_edgecolor = edgecolors if edgecolors is None: orig_edgecolor = kwargs.get('edgecolor', None) (c, colors, edgecolors) = self._parse_scatter_color_args(c, edgecolors, kwargs, x.size, get_next_color_func=self._get_patches_for_fill.get_next_color) if plotnonfinite and colors is None: c = np.ma.masked_invalid(c) (x, y, s, edgecolors, linewidths) = cbook._combine_masks(x, y, s, edgecolors, linewidths) else: (x, y, s, c, colors, edgecolors, linewidths) = cbook._combine_masks(x, y, s, c, colors, edgecolors, linewidths) if x.size in (3, 4) and np.ma.is_masked(edgecolors) and (not np.ma.is_masked(orig_edgecolor)): edgecolors = edgecolors.data scales = s if marker is None: marker = mpl.rcParams['scatter.marker'] if isinstance(marker, mmarkers.MarkerStyle): marker_obj = marker else: marker_obj = mmarkers.MarkerStyle(marker) path = marker_obj.get_path().transformed(marker_obj.get_transform()) if not marker_obj.is_filled(): if orig_edgecolor is not None: _api.warn_external(f'You passed a edgecolor/edgecolors ({orig_edgecolor!r}) for an unfilled marker ({marker!r}). Matplotlib is ignoring the edgecolor in favor of the facecolor. This behavior may change in the future.') if marker_obj.get_fillstyle() == 'none': edgecolors = colors colors = 'none' else: edgecolors = 'face' if linewidths is None: linewidths = mpl.rcParams['lines.linewidth'] elif np.iterable(linewidths): linewidths = [lw if lw is not None else mpl.rcParams['lines.linewidth'] for lw in linewidths] offsets = np.ma.column_stack([x, y]) collection = mcoll.PathCollection((path,), scales, facecolors=colors, edgecolors=edgecolors, linewidths=linewidths, offsets=offsets, offset_transform=kwargs.pop('transform', self.transData), alpha=alpha) collection.set_transform(mtransforms.IdentityTransform()) if colors is None: collection.set_array(c) collection.set_cmap(cmap) collection.set_norm(norm) collection._scale_norm(norm, vmin, vmax) else: extra_kwargs = {'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax} extra_keys = [k for (k, v) in extra_kwargs.items() if v is not None] if any(extra_keys): keys_str = ', '.join((f"'{k}'" for k in extra_keys)) _api.warn_external(f"No data for colormapping provided via 'c'. Parameters {keys_str} will be ignored") collection._internal_update(kwargs) if mpl.rcParams['_internal.classic_mode']: if self._xmargin < 0.05 and x.size > 0: self.set_xmargin(0.05) if self._ymargin < 0.05 and x.size > 0: self.set_ymargin(0.05) self.add_collection(collection) self._request_autoscale_view() return collection @_api.make_keyword_only('3.9', 'gridsize') @_preprocess_data(replace_names=['x', 'y', 'C'], label_namer='y') @_docstring.dedent_interpd def hexbin(self, x, y, C=None, gridsize=100, bins=None, xscale='linear', yscale='linear', extent=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors='face', reduce_C_function=np.mean, mincnt=None, marginals=False, **kwargs): self._process_unit_info([('x', x), ('y', y)], kwargs, convert=False) (x, y, C) = cbook.delete_masked_points(x, y, C) if np.iterable(gridsize): (nx, ny) = gridsize else: nx = gridsize ny = int(nx / math.sqrt(3)) x = np.asarray(x, float) y = np.asarray(y, float) tx = x ty = y if xscale == 'log': if np.any(x <= 0.0): raise ValueError('x contains non-positive values, so cannot be log-scaled') tx = np.log10(tx) if yscale == 'log': if np.any(y <= 0.0): raise ValueError('y contains non-positive values, so cannot be log-scaled') ty = np.log10(ty) if extent is not None: (xmin, xmax, ymin, ymax) = extent if xmin > xmax: raise ValueError('In extent, xmax must be greater than xmin') if ymin > ymax: raise ValueError('In extent, ymax must be greater than ymin') else: (xmin, xmax) = (tx.min(), tx.max()) if len(x) else (0, 1) (ymin, ymax) = (ty.min(), ty.max()) if len(y) else (0, 1) (xmin, xmax) = mtransforms.nonsingular(xmin, xmax, expander=0.1) (ymin, ymax) = mtransforms.nonsingular(ymin, ymax, expander=0.1) nx1 = nx + 1 ny1 = ny + 1 nx2 = nx ny2 = ny n = nx1 * ny1 + nx2 * ny2 padding = 1e-09 * (xmax - xmin) xmin -= padding xmax += padding sx = (xmax - xmin) / nx sy = (ymax - ymin) / ny ix = (tx - xmin) / sx iy = (ty - ymin) / sy ix1 = np.round(ix).astype(int) iy1 = np.round(iy).astype(int) ix2 = np.floor(ix).astype(int) iy2 = np.floor(iy).astype(int) i1 = np.where((0 <= ix1) & (ix1 < nx1) & (0 <= iy1) & (iy1 < ny1), ix1 * ny1 + iy1 + 1, 0) i2 = np.where((0 <= ix2) & (ix2 < nx2) & (0 <= iy2) & (iy2 < ny2), ix2 * ny2 + iy2 + 1, 0) d1 = (ix - ix1) ** 2 + 3.0 * (iy - iy1) ** 2 d2 = (ix - ix2 - 0.5) ** 2 + 3.0 * (iy - iy2 - 0.5) ** 2 bdist = d1 < d2 if C is None: counts1 = np.bincount(i1[bdist], minlength=1 + nx1 * ny1)[1:] counts2 = np.bincount(i2[~bdist], minlength=1 + nx2 * ny2)[1:] accum = np.concatenate([counts1, counts2]).astype(float) if mincnt is not None: accum[accum < mincnt] = np.nan C = np.ones(len(x)) else: Cs_at_i1 = [[] for _ in range(1 + nx1 * ny1)] Cs_at_i2 = [[] for _ in range(1 + nx2 * ny2)] for i in range(len(x)): if bdist[i]: Cs_at_i1[i1[i]].append(C[i]) else: Cs_at_i2[i2[i]].append(C[i]) if mincnt is None: mincnt = 1 accum = np.array([reduce_C_function(acc) if len(acc) >= mincnt else np.nan for Cs_at_i in [Cs_at_i1, Cs_at_i2] for acc in Cs_at_i[1:]], float) good_idxs = ~np.isnan(accum) offsets = np.zeros((n, 2), float) offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1) offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1) offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2) offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5 offsets[:, 0] *= sx offsets[:, 1] *= sy offsets[:, 0] += xmin offsets[:, 1] += ymin offsets = offsets[good_idxs, :] accum = accum[good_idxs] polygon = [sx, sy / 3] * np.array([[0.5, -0.5], [0.5, 0.5], [0.0, 1.0], [-0.5, 0.5], [-0.5, -0.5], [0.0, -1.0]]) if linewidths is None: linewidths = [mpl.rcParams['patch.linewidth']] if xscale == 'log' or yscale == 'log': polygons = np.expand_dims(polygon, 0) if xscale == 'log': polygons[:, :, 0] = 10.0 ** polygons[:, :, 0] xmin = 10.0 ** xmin xmax = 10.0 ** xmax self.set_xscale(xscale) if yscale == 'log': polygons[:, :, 1] = 10.0 ** polygons[:, :, 1] ymin = 10.0 ** ymin ymax = 10.0 ** ymax self.set_yscale(yscale) else: polygons = [polygon] collection = mcoll.PolyCollection(polygons, edgecolors=edgecolors, linewidths=linewidths, offsets=offsets, offset_transform=mtransforms.AffineDeltaTransform(self.transData)) if cbook._str_equal(bins, 'log'): if norm is not None: _api.warn_external(f"Only one of 'bins' and 'norm' arguments can be supplied, ignoring bins={bins!r}") else: norm = mcolors.LogNorm(vmin=vmin, vmax=vmax) vmin = vmax = None bins = None if bins is not None: if not np.iterable(bins): (minimum, maximum) = (min(accum), max(accum)) bins -= 1 bins = minimum + (maximum - minimum) * np.arange(bins) / bins bins = np.sort(bins) accum = bins.searchsorted(accum) collection.set_array(accum) collection.set_cmap(cmap) collection.set_norm(norm) collection.set_alpha(alpha) collection._internal_update(kwargs) collection._scale_norm(norm, vmin, vmax) if norm is not None: if collection.norm.vmin is None and collection.norm.vmax is None: collection.norm.autoscale() corners = ((xmin, ymin), (xmax, ymax)) self.update_datalim(corners) self._request_autoscale_view(tight=True) self.add_collection(collection, autolim=False) if not marginals: return collection bars = [] for (zname, z, zmin, zmax, zscale, nbins) in [('x', x, xmin, xmax, xscale, nx), ('y', y, ymin, ymax, yscale, 2 * ny)]: if zscale == 'log': bin_edges = np.geomspace(zmin, zmax, nbins + 1) else: bin_edges = np.linspace(zmin, zmax, nbins + 1) verts = np.empty((nbins, 4, 2)) verts[:, 0, 0] = verts[:, 1, 0] = bin_edges[:-1] verts[:, 2, 0] = verts[:, 3, 0] = bin_edges[1:] verts[:, 0, 1] = verts[:, 3, 1] = 0.0 verts[:, 1, 1] = verts[:, 2, 1] = 0.05 if zname == 'y': verts = verts[:, :, ::-1] bin_idxs = np.searchsorted(bin_edges, z) - 1 values = np.empty(nbins) for i in range(nbins): ci = C[bin_idxs == i] values[i] = reduce_C_function(ci) if len(ci) > 0 else np.nan mask = ~np.isnan(values) verts = verts[mask] values = values[mask] trans = getattr(self, f'get_{zname}axis_transform')(which='grid') bar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face') bar.set_array(values) bar.set_cmap(cmap) bar.set_norm(norm) bar.set_alpha(alpha) bar._internal_update(kwargs) bars.append(self.add_collection(bar, autolim=False)) (collection.hbar, collection.vbar) = bars def on_changed(collection): collection.hbar.set_cmap(collection.get_cmap()) collection.hbar.set_cmap(collection.get_cmap()) collection.vbar.set_clim(collection.get_clim()) collection.vbar.set_clim(collection.get_clim()) collection.callbacks.connect('changed', on_changed) return collection @_docstring.dedent_interpd def arrow(self, x, y, dx, dy, **kwargs): x = self.convert_xunits(x) y = self.convert_yunits(y) dx = self.convert_xunits(dx) dy = self.convert_yunits(dy) a = mpatches.FancyArrow(x, y, dx, dy, **kwargs) self.add_patch(a) self._request_autoscale_view() return a @_docstring.copy(mquiver.QuiverKey.__init__) def quiverkey(self, Q, X, Y, U, label, **kwargs): qk = mquiver.QuiverKey(Q, X, Y, U, label, **kwargs) self.add_artist(qk) return qk def _quiver_units(self, args, kwargs): if len(args) > 3: (x, y) = args[0:2] (x, y) = self._process_unit_info([('x', x), ('y', y)], kwargs) return (x, y) + args[2:] return args @_preprocess_data() @_docstring.dedent_interpd def quiver(self, *args, **kwargs): args = self._quiver_units(args, kwargs) q = mquiver.Quiver(self, *args, **kwargs) self.add_collection(q, autolim=True) self._request_autoscale_view() return q @_preprocess_data() @_docstring.dedent_interpd def barbs(self, *args, **kwargs): args = self._quiver_units(args, kwargs) b = mquiver.Barbs(self, *args, **kwargs) self.add_collection(b, autolim=True) self._request_autoscale_view() return b def fill(self, *args, data=None, **kwargs): kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) patches = [*self._get_patches_for_fill(self, *args, data=data, **kwargs)] for poly in patches: self.add_patch(poly) self._request_autoscale_view() return patches def _fill_between_x_or_y(self, ind_dir, ind, dep1, dep2=0, *, where=None, interpolate=False, step=None, **kwargs): dep_dir = {'x': 'y', 'y': 'x'}[ind_dir] if not mpl.rcParams['_internal.classic_mode']: kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection) if not any((c in kwargs for c in ('color', 'facecolor'))): kwargs['facecolor'] = self._get_patches_for_fill.get_next_color() (ind, dep1, dep2) = map(ma.masked_invalid, self._process_unit_info([(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs)) for (name, array) in [(ind_dir, ind), (f'{dep_dir}1', dep1), (f'{dep_dir}2', dep2)]: if array.ndim > 1: raise ValueError(f'{name!r} is not 1-dimensional') if where is None: where = True else: where = np.asarray(where, dtype=bool) if where.size != ind.size: raise ValueError(f'where size ({where.size}) does not match {ind_dir} size ({ind.size})') where = where & ~functools.reduce(np.logical_or, map(np.ma.getmaskarray, [ind, dep1, dep2])) (ind, dep1, dep2) = np.broadcast_arrays(np.atleast_1d(ind), dep1, dep2, subok=True) polys = [] for (idx0, idx1) in cbook.contiguous_regions(where): indslice = ind[idx0:idx1] dep1slice = dep1[idx0:idx1] dep2slice = dep2[idx0:idx1] if step is not None: step_func = cbook.STEP_LOOKUP_MAP['steps-' + step] (indslice, dep1slice, dep2slice) = step_func(indslice, dep1slice, dep2slice) if not len(indslice): continue N = len(indslice) pts = np.zeros((2 * N + 2, 2)) if interpolate: def get_interp_point(idx): im1 = max(idx - 1, 0) ind_values = ind[im1:idx + 1] diff_values = dep1[im1:idx + 1] - dep2[im1:idx + 1] dep1_values = dep1[im1:idx + 1] if len(diff_values) == 2: if np.ma.is_masked(diff_values[1]): return (ind[im1], dep1[im1]) elif np.ma.is_masked(diff_values[0]): return (ind[idx], dep1[idx]) diff_order = diff_values.argsort() diff_root_ind = np.interp(0, diff_values[diff_order], ind_values[diff_order]) ind_order = ind_values.argsort() diff_root_dep = np.interp(diff_root_ind, ind_values[ind_order], dep1_values[ind_order]) return (diff_root_ind, diff_root_dep) start = get_interp_point(idx0) end = get_interp_point(idx1) else: start = (indslice[0], dep2slice[0]) end = (indslice[-1], dep2slice[-1]) pts[0] = start pts[N + 1] = end pts[1:N + 1, 0] = indslice pts[1:N + 1, 1] = dep1slice pts[N + 2:, 0] = indslice[::-1] pts[N + 2:, 1] = dep2slice[::-1] if ind_dir == 'y': pts = pts[:, ::-1] polys.append(pts) collection = mcoll.PolyCollection(polys, **kwargs) pts = np.vstack([np.hstack([ind[where, None], dep1[where, None]]), np.hstack([ind[where, None], dep2[where, None]])]) if ind_dir == 'y': pts = pts[:, ::-1] up_x = up_y = True if 'transform' in kwargs: (up_x, up_y) = kwargs['transform'].contains_branch_seperately(self.transData) self.update_datalim(pts, updatex=up_x, updatey=up_y) self.add_collection(collection, autolim=False) self._request_autoscale_view() return collection def fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, **kwargs): return self._fill_between_x_or_y('x', x, y1, y2, where=where, interpolate=interpolate, step=step, **kwargs) if _fill_between_x_or_y.__doc__: fill_between.__doc__ = _fill_between_x_or_y.__doc__.format(dir='horizontal', ind='x', dep='y') fill_between = _preprocess_data(_docstring.dedent_interpd(fill_between), replace_names=['x', 'y1', 'y2', 'where']) def fill_betweenx(self, y, x1, x2=0, where=None, step=None, interpolate=False, **kwargs): return self._fill_between_x_or_y('y', y, x1, x2, where=where, interpolate=interpolate, step=step, **kwargs) if _fill_between_x_or_y.__doc__: fill_betweenx.__doc__ = _fill_between_x_or_y.__doc__.format(dir='vertical', ind='y', dep='x') fill_betweenx = _preprocess_data(_docstring.dedent_interpd(fill_betweenx), replace_names=['y', 'x1', 'x2', 'where']) @_preprocess_data() @_docstring.interpd def imshow(self, X, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, **kwargs): im = mimage.AxesImage(self, cmap=cmap, norm=norm, interpolation=interpolation, origin=origin, extent=extent, filternorm=filternorm, filterrad=filterrad, resample=resample, interpolation_stage=interpolation_stage, **kwargs) if aspect is None and (not (im.is_transform_set() and (not im.get_transform().contains_branch(self.transData)))): aspect = mpl.rcParams['image.aspect'] if aspect is not None: self.set_aspect(aspect) im.set_data(X) im.set_alpha(alpha) if im.get_clip_path() is None: im.set_clip_path(self.patch) im._scale_norm(norm, vmin, vmax) im.set_url(url) im.set_extent(im.get_extent()) self.add_image(im) return im def _pcolorargs(self, funcname, *args, shading='auto', **kwargs): _valid_shading = ['gouraud', 'nearest', 'flat', 'auto'] try: _api.check_in_list(_valid_shading, shading=shading) except ValueError: _api.warn_external(f"shading value '{shading}' not in list of valid values {_valid_shading}. Setting shading='auto'.") shading = 'auto' if len(args) == 1: C = np.asanyarray(args[0]) (nrows, ncols) = C.shape[:2] if shading in ['gouraud', 'nearest']: (X, Y) = np.meshgrid(np.arange(ncols), np.arange(nrows)) else: (X, Y) = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1)) shading = 'flat' C = cbook.safe_masked_invalid(C, copy=True) return (X, Y, C, shading) if len(args) == 3: C = np.asanyarray(args[2]) (X, Y) = args[:2] (X, Y) = self._process_unit_info([('x', X), ('y', Y)], kwargs) (X, Y) = (cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]) if funcname == 'pcolormesh': if np.ma.is_masked(X) or np.ma.is_masked(Y): raise ValueError('x and y arguments to pcolormesh cannot have non-finite values or be of type numpy.ma.MaskedArray with masked values') (nrows, ncols) = C.shape[:2] else: raise _api.nargs_error(funcname, takes='1 or 3', given=len(args)) Nx = X.shape[-1] Ny = Y.shape[0] if X.ndim != 2 or X.shape[0] == 1: x = X.reshape(1, Nx) X = x.repeat(Ny, axis=0) if Y.ndim != 2 or Y.shape[1] == 1: y = Y.reshape(Ny, 1) Y = y.repeat(Nx, axis=1) if X.shape != Y.shape: raise TypeError(f'Incompatible X, Y inputs to {funcname}; see help({funcname})') if shading == 'auto': if ncols == Nx and nrows == Ny: shading = 'nearest' else: shading = 'flat' if shading == 'flat': if (Nx, Ny) != (ncols + 1, nrows + 1): raise TypeError(f"Dimensions of C {C.shape} should be one smaller than X({Nx}) and Y({Ny}) while using shading='flat' see help({funcname})") else: if (Nx, Ny) != (ncols, nrows): raise TypeError('Dimensions of C %s are incompatible with X (%d) and/or Y (%d); see help(%s)' % (C.shape, Nx, Ny, funcname)) if shading == 'nearest': def _interp_grid(X): if np.shape(X)[1] > 1: dX = np.diff(X, axis=1) * 0.5 if not (np.all(dX >= 0) or np.all(dX <= 0)): _api.warn_external(f'The input coordinates to {funcname} are interpreted as cell centers, but are not monotonically increasing or decreasing. This may lead to incorrectly calculated cell edges, in which case, please supply explicit cell edges to {funcname}.') hstack = np.ma.hstack if np.ma.isMA(X) else np.hstack X = hstack((X[:, [0]] - dX[:, [0]], X[:, :-1] + dX, X[:, [-1]] + dX[:, [-1]])) else: X = np.hstack((X, X)) return X if ncols == Nx: X = _interp_grid(X) Y = _interp_grid(Y) if nrows == Ny: X = _interp_grid(X.T).T Y = _interp_grid(Y.T).T shading = 'flat' C = cbook.safe_masked_invalid(C, copy=True) return (X, Y, C, shading) @_preprocess_data() @_docstring.dedent_interpd def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, **kwargs): if shading is None: shading = mpl.rcParams['pcolor.shading'] shading = shading.lower() (X, Y, C, shading) = self._pcolorargs('pcolor', *args, shading=shading, kwargs=kwargs) linewidths = (0.25,) if 'linewidth' in kwargs: kwargs['linewidths'] = kwargs.pop('linewidth') kwargs.setdefault('linewidths', linewidths) if 'edgecolor' in kwargs: kwargs['edgecolors'] = kwargs.pop('edgecolor') ec = kwargs.setdefault('edgecolors', 'none') if 'antialiaseds' in kwargs: kwargs['antialiased'] = kwargs.pop('antialiaseds') if 'antialiased' not in kwargs and cbook._str_lower_equal(ec, 'none'): kwargs['antialiased'] = False kwargs.setdefault('snap', False) if np.ma.isMaskedArray(X) or np.ma.isMaskedArray(Y): stack = np.ma.stack X = np.ma.asarray(X) Y = np.ma.asarray(Y) x = X.compressed() y = Y.compressed() else: stack = np.stack x = X y = Y coords = stack([X, Y], axis=-1) collection = mcoll.PolyQuadMesh(coords, array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs) collection._scale_norm(norm, vmin, vmax) t = collection._transform if not isinstance(t, mtransforms.Transform) and hasattr(t, '_as_mpl_transform'): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): trans_to_data = t - self.transData pts = np.vstack([x, y]).T.astype(float) transformed_pts = trans_to_data.transform(pts) x = transformed_pts[..., 0] y = transformed_pts[..., 1] self.add_collection(collection, autolim=False) minx = np.min(x) maxx = np.max(x) miny = np.min(y) maxy = np.max(y) collection.sticky_edges.x[:] = [minx, maxx] collection.sticky_edges.y[:] = [miny, maxy] corners = ((minx, miny), (maxx, maxy)) self.update_datalim(corners) self._request_autoscale_view() return collection @_preprocess_data() @_docstring.dedent_interpd def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, shading=None, antialiased=False, **kwargs): if shading is None: shading = mpl.rcParams['pcolor.shading'] shading = shading.lower() kwargs.setdefault('edgecolors', 'none') (X, Y, C, shading) = self._pcolorargs('pcolormesh', *args, shading=shading, kwargs=kwargs) coords = np.stack([X, Y], axis=-1) kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap']) collection = mcoll.QuadMesh(coords, antialiased=antialiased, shading=shading, array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs) collection._scale_norm(norm, vmin, vmax) coords = coords.reshape(-1, 2) t = collection._transform if not isinstance(t, mtransforms.Transform) and hasattr(t, '_as_mpl_transform'): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): trans_to_data = t - self.transData coords = trans_to_data.transform(coords) self.add_collection(collection, autolim=False) (minx, miny) = np.min(coords, axis=0) (maxx, maxy) = np.max(coords, axis=0) collection.sticky_edges.x[:] = [minx, maxx] collection.sticky_edges.y[:] = [miny, maxy] corners = ((minx, miny), (maxx, maxy)) self.update_datalim(corners) self._request_autoscale_view() return collection @_preprocess_data() @_docstring.dedent_interpd def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, **kwargs): C = args[-1] (nr, nc) = np.shape(C)[:2] if len(args) == 1: style = 'image' x = [0, nc] y = [0, nr] elif len(args) == 3: (x, y) = args[:2] x = np.asarray(x) y = np.asarray(y) if x.ndim == 1 and y.ndim == 1: if x.size == 2 and y.size == 2: style = 'image' else: dx = np.diff(x) dy = np.diff(y) if np.ptp(dx) < 0.01 * abs(dx.mean()) and np.ptp(dy) < 0.01 * abs(dy.mean()): style = 'image' else: style = 'pcolorimage' elif x.ndim == 2 and y.ndim == 2: style = 'quadmesh' else: raise TypeError(f'When 3 positional parameters are passed to pcolorfast, the first two (X and Y) must be both 1D or both 2D; the given X was {x.ndim}D and the given Y was {y.ndim}D') else: raise _api.nargs_error('pcolorfast', '1 or 3', len(args)) if style == 'quadmesh': coords = np.stack([x, y], axis=-1) if np.ndim(C) not in {2, 3}: raise ValueError('C must be 2D or 3D') collection = mcoll.QuadMesh(coords, array=C, alpha=alpha, cmap=cmap, norm=norm, antialiased=False, edgecolors='none') self.add_collection(collection, autolim=False) (xl, xr, yb, yt) = (x.min(), x.max(), y.min(), y.max()) ret = collection else: extent = (xl, xr, yb, yt) = (x[0], x[-1], y[0], y[-1]) if style == 'image': im = mimage.AxesImage(self, cmap=cmap, norm=norm, data=C, alpha=alpha, extent=extent, interpolation='nearest', origin='lower', **kwargs) elif style == 'pcolorimage': im = mimage.PcolorImage(self, x, y, C, cmap=cmap, norm=norm, alpha=alpha, extent=extent, **kwargs) self.add_image(im) ret = im if np.ndim(C) == 2: ret._scale_norm(norm, vmin, vmax) if ret.get_clip_path() is None: ret.set_clip_path(self.patch) ret.sticky_edges.x[:] = [xl, xr] ret.sticky_edges.y[:] = [yb, yt] self.update_datalim(np.array([[xl, yb], [xr, yt]])) self._request_autoscale_view(tight=True) return ret @_preprocess_data() @_docstring.dedent_interpd def contour(self, *args, **kwargs): kwargs['filled'] = False contours = mcontour.QuadContourSet(self, *args, **kwargs) self._request_autoscale_view() return contours @_preprocess_data() @_docstring.dedent_interpd def contourf(self, *args, **kwargs): kwargs['filled'] = True contours = mcontour.QuadContourSet(self, *args, **kwargs) self._request_autoscale_view() return contours def clabel(self, CS, levels=None, **kwargs): return CS.clabel(levels, **kwargs) @_api.make_keyword_only('3.9', 'range') @_preprocess_data(replace_names=['x', 'weights'], label_namer='x') def hist(self, x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, **kwargs): bin_range = range from builtins import range if np.isscalar(x): x = [x] if bins is None: bins = mpl.rcParams['hist.bins'] _api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'], histtype=histtype) _api.check_in_list(['left', 'mid', 'right'], align=align) _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) if histtype == 'barstacked' and (not stacked): stacked = True x = cbook._reshape_2D(x, 'x') nx = len(x) if orientation == 'vertical': convert_units = self.convert_xunits x = [*self._process_unit_info([('x', x[0])], kwargs), *map(convert_units, x[1:])] else: convert_units = self.convert_yunits x = [*self._process_unit_info([('y', x[0])], kwargs), *map(convert_units, x[1:])] if bin_range is not None: bin_range = convert_units(bin_range) if not cbook.is_scalar_or_string(bins): bins = convert_units(bins) if weights is not None: w = cbook._reshape_2D(weights, 'weights') else: w = [None] * nx if len(w) != nx: raise ValueError('weights should have the same shape as x') input_empty = True for (xi, wi) in zip(x, w): len_xi = len(xi) if wi is not None and len(wi) != len_xi: raise ValueError('weights should have the same shape as x') if len_xi: input_empty = False if color is None: colors = [self._get_lines.get_next_color() for i in range(nx)] else: colors = mcolors.to_rgba_array(color) if len(colors) != nx: raise ValueError(f"The 'color' keyword argument must have one color per dataset, but {nx} datasets and {len(colors)} colors were provided") hist_kwargs = dict() if bin_range is None: xmin = np.inf xmax = -np.inf for xi in x: if len(xi): xmin = min(xmin, np.nanmin(xi)) xmax = max(xmax, np.nanmax(xi)) if xmin <= xmax: bin_range = (xmin, xmax) if not input_empty and len(x) > 1: if weights is not None: _w = np.concatenate(w) else: _w = None bins = np.histogram_bin_edges(np.concatenate(x), bins, bin_range, _w) else: hist_kwargs['range'] = bin_range density = bool(density) if density and (not stacked): hist_kwargs['density'] = density tops = [] for i in range(nx): (m, bins) = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) tops.append(m) tops = np.array(tops, float) bins = np.array(bins, float) if stacked: tops = tops.cumsum(axis=0) if density: tops = tops / np.diff(bins) / tops[-1].sum() if cumulative: slc = slice(None) if isinstance(cumulative, Number) and cumulative < 0: slc = slice(None, None, -1) if density: tops = (tops * np.diff(bins))[:, slc].cumsum(axis=1)[:, slc] else: tops = tops[:, slc].cumsum(axis=1)[:, slc] patches = [] if histtype.startswith('bar'): totwidth = np.diff(bins) if rwidth is not None: dr = np.clip(rwidth, 0, 1) elif len(tops) > 1 and (not stacked or mpl.rcParams['_internal.classic_mode']): dr = 0.8 else: dr = 1.0 if histtype == 'bar' and (not stacked): width = dr * totwidth / nx dw = width boffset = -0.5 * dr * totwidth * (1 - 1 / nx) elif histtype == 'barstacked' or stacked: width = dr * totwidth (boffset, dw) = (0.0, 0.0) if align == 'mid': boffset += 0.5 * totwidth elif align == 'right': boffset += totwidth if orientation == 'horizontal': _barfunc = self.barh bottom_kwarg = 'left' else: _barfunc = self.bar bottom_kwarg = 'bottom' for (top, color) in zip(tops, colors): if bottom is None: bottom = np.zeros(len(top)) if stacked: height = top - bottom else: height = top bars = _barfunc(bins[:-1] + boffset, height, width, align='center', log=log, color=color, **{bottom_kwarg: bottom}) patches.append(bars) if stacked: bottom = top boffset += dw for bars in patches[1:]: for patch in bars: patch.sticky_edges.x[:] = patch.sticky_edges.y[:] = [] elif histtype.startswith('step'): x = np.zeros(4 * len(bins) - 3) y = np.zeros(4 * len(bins) - 3) (x[0:2 * len(bins) - 1:2], x[1:2 * len(bins) - 1:2]) = (bins, bins[:-1]) x[2 * len(bins) - 1:] = x[1:2 * len(bins) - 1][::-1] if bottom is None: bottom = 0 y[1:2 * len(bins) - 1:2] = y[2:2 * len(bins):2] = bottom y[2 * len(bins) - 1:] = y[1:2 * len(bins) - 1][::-1] if log: if orientation == 'horizontal': self.set_xscale('log', nonpositive='clip') else: self.set_yscale('log', nonpositive='clip') if align == 'left': x -= 0.5 * (bins[1] - bins[0]) elif align == 'right': x += 0.5 * (bins[1] - bins[0]) fill = histtype == 'stepfilled' (xvals, yvals) = ([], []) for top in tops: if stacked: y[2 * len(bins) - 1:] = y[1:2 * len(bins) - 1][::-1] y[1:2 * len(bins) - 1:2] = y[2:2 * len(bins):2] = top + bottom y[0] = y[-1] if orientation == 'horizontal': xvals.append(y.copy()) yvals.append(x.copy()) else: xvals.append(x.copy()) yvals.append(y.copy()) split = -1 if fill else 2 * len(bins) for (x, y, color) in reversed(list(zip(xvals, yvals, colors))): patches.append(self.fill(x[:split], y[:split], closed=True if fill else None, facecolor=color, edgecolor=None if fill else color, fill=fill if fill else None, zorder=None if fill else mlines.Line2D.zorder)) for patch_list in patches: for patch in patch_list: if orientation == 'vertical': patch.sticky_edges.y.append(0) elif orientation == 'horizontal': patch.sticky_edges.x.append(0) patches.reverse() labels = [] if label is None else np.atleast_1d(np.asarray(label, str)) if histtype == 'step': edgecolors = itertools.cycle(np.atleast_1d(kwargs.get('edgecolor', colors))) else: edgecolors = itertools.cycle(np.atleast_1d(kwargs.get('edgecolor', None))) facecolors = itertools.cycle(np.atleast_1d(kwargs.get('facecolor', colors))) hatches = itertools.cycle(np.atleast_1d(kwargs.get('hatch', None))) linewidths = itertools.cycle(np.atleast_1d(kwargs.get('linewidth', None))) linestyles = itertools.cycle(np.atleast_1d(kwargs.get('linestyle', None))) for (patch, lbl) in itertools.zip_longest(patches, labels): if not patch: continue p = patch[0] kwargs.update({'hatch': next(hatches), 'linewidth': next(linewidths), 'linestyle': next(linestyles), 'edgecolor': next(edgecolors), 'facecolor': next(facecolors)}) p._internal_update(kwargs) if lbl is not None: p.set_label(lbl) for p in patch[1:]: p._internal_update(kwargs) p.set_label('_nolegend_') if nx == 1: return (tops[0], bins, patches[0]) else: patch_type = 'BarContainer' if histtype.startswith('bar') else 'list[Polygon]' return (tops, bins, cbook.silent_list(patch_type, patches)) @_preprocess_data() def stairs(self, values, edges=None, *, orientation='vertical', baseline=0, fill=False, **kwargs): if 'color' in kwargs: _color = kwargs.pop('color') else: _color = self._get_lines.get_next_color() if fill: kwargs.setdefault('linewidth', 0) kwargs.setdefault('facecolor', _color) else: kwargs.setdefault('edgecolor', _color) if edges is None: edges = np.arange(len(values) + 1) (edges, values, baseline) = self._process_unit_info([('x', edges), ('y', values), ('y', baseline)], kwargs) patch = mpatches.StepPatch(values, edges, baseline=baseline, orientation=orientation, fill=fill, **kwargs) self.add_patch(patch) if baseline is None and fill: _api.warn_external(f'Both baseline={baseline!r} and fill={fill!r} have been passed. baseline=None is only intended for unfilled stair plots. Because baseline is None, the Path used to draw the stairs will not be closed, thus because fill is True the polygon will be closed by drawing an (unstroked) edge from the first to last point. It is very likely that the resulting fill patterns is not the desired result.') if baseline is not None: if orientation == 'vertical': patch.sticky_edges.y.append(np.min(baseline)) self.update_datalim([(edges[0], np.min(baseline))]) else: patch.sticky_edges.x.append(np.min(baseline)) self.update_datalim([(np.min(baseline), edges[0])]) self._request_autoscale_view() return patch @_api.make_keyword_only('3.9', 'range') @_preprocess_data(replace_names=['x', 'y', 'weights']) @_docstring.dedent_interpd def hist2d(self, x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, **kwargs): (h, xedges, yedges) = np.histogram2d(x, y, bins=bins, range=range, density=density, weights=weights) if cmin is not None: h[h < cmin] = None if cmax is not None: h[h > cmax] = None pc = self.pcolormesh(xedges, yedges, h.T, **kwargs) self.set_xlim(xedges[0], xedges[-1]) self.set_ylim(yedges[0], yedges[-1]) return (h, xedges, yedges, pc) @_preprocess_data(replace_names=['x', 'weights'], label_namer='x') @_docstring.dedent_interpd def ecdf(self, x, weights=None, *, complementary=False, orientation='vertical', compress=False, **kwargs): _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) if 'drawstyle' in kwargs or 'ds' in kwargs: raise TypeError("Cannot pass 'drawstyle' or 'ds' to ecdf()") if np.ma.getmask(x).any(): raise ValueError('ecdf() does not support masked entries') x = np.asarray(x) if np.isnan(x).any(): raise ValueError('ecdf() does not support NaNs') argsort = np.argsort(x) x = x[argsort] if weights is None: cum_weights = (1 + np.arange(len(x))) / len(x) else: weights = np.take(weights, argsort) cum_weights = np.cumsum(weights / np.sum(weights)) if compress: compress_idxs = [0, *(x[:-1] != x[1:]).nonzero()[0] + 1] x = x[compress_idxs] cum_weights = cum_weights[compress_idxs] if orientation == 'vertical': if not complementary: (line,) = self.plot([x[0], *x], [0, *cum_weights], drawstyle='steps-post', **kwargs) else: (line,) = self.plot([*x, x[-1]], [1, *1 - cum_weights], drawstyle='steps-pre', **kwargs) line.sticky_edges.y[:] = [0, 1] else: if not complementary: (line,) = self.plot([0, *cum_weights], [x[0], *x], drawstyle='steps-pre', **kwargs) else: (line,) = self.plot([1, *1 - cum_weights], [*x, x[-1]], drawstyle='steps-post', **kwargs) line.sticky_edges.x[:] = [0, 1] return line @_api.make_keyword_only('3.9', 'NFFT') @_preprocess_data(replace_names=['x']) @_docstring.dedent_interpd def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, **kwargs): if Fc is None: Fc = 0 (pxx, freqs) = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq) freqs += Fc if scale_by_freq in (None, True): psd_units = 'dB/Hz' else: psd_units = 'dB' line = self.plot(freqs, 10 * np.log10(pxx), **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Power Spectral Density (%s)' % psd_units) self.grid(True) (vmin, vmax) = self.get_ybound() step = max(10 * int(np.log10(vmax - vmin)), 1) ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) self.set_yticks(ticks) if return_line is None or not return_line: return (pxx, freqs) else: return (pxx, freqs, line) @_api.make_keyword_only('3.9', 'NFFT') @_preprocess_data(replace_names=['x', 'y'], label_namer='y') @_docstring.dedent_interpd def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, **kwargs): if Fc is None: Fc = 0 (pxy, freqs) = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq) freqs += Fc line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Cross Spectrum Magnitude (dB)') self.grid(True) (vmin, vmax) = self.get_ybound() step = max(10 * int(np.log10(vmax - vmin)), 1) ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) self.set_yticks(ticks) if return_line is None or not return_line: return (pxy, freqs) else: return (pxy, freqs, line) @_api.make_keyword_only('3.9', 'Fs') @_preprocess_data(replace_names=['x']) @_docstring.dedent_interpd def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, scale=None, **kwargs): if Fc is None: Fc = 0 (spec, freqs) = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window, pad_to=pad_to, sides=sides) freqs += Fc yunits = _api.check_getitem({None: 'energy', 'default': 'energy', 'linear': 'energy', 'dB': 'dB'}, scale=scale) if yunits == 'energy': Z = spec else: Z = 20.0 * np.log10(spec) (line,) = self.plot(freqs, Z, **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Magnitude (%s)' % yunits) return (spec, freqs, line) @_api.make_keyword_only('3.9', 'Fs') @_preprocess_data(replace_names=['x']) @_docstring.dedent_interpd def angle_spectrum(self, x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, **kwargs): if Fc is None: Fc = 0 (spec, freqs) = mlab.angle_spectrum(x=x, Fs=Fs, window=window, pad_to=pad_to, sides=sides) freqs += Fc lines = self.plot(freqs, spec, **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Angle (radians)') return (spec, freqs, lines[0]) @_api.make_keyword_only('3.9', 'Fs') @_preprocess_data(replace_names=['x']) @_docstring.dedent_interpd def phase_spectrum(self, x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, **kwargs): if Fc is None: Fc = 0 (spec, freqs) = mlab.phase_spectrum(x=x, Fs=Fs, window=window, pad_to=pad_to, sides=sides) freqs += Fc lines = self.plot(freqs, spec, **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Phase (radians)') return (spec, freqs, lines[0]) @_api.make_keyword_only('3.9', 'NFFT') @_preprocess_data(replace_names=['x', 'y']) @_docstring.dedent_interpd def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None, **kwargs): (cxy, freqs) = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, scale_by_freq=scale_by_freq, sides=sides, pad_to=pad_to) freqs += Fc self.plot(freqs, cxy, **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Coherence') self.grid(True) return (cxy, freqs) @_api.make_keyword_only('3.9', 'NFFT') @_preprocess_data(replace_names=['x']) @_docstring.dedent_interpd def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, **kwargs): if NFFT is None: NFFT = 256 if Fc is None: Fc = 0 if noverlap is None: noverlap = 128 if Fs is None: Fs = 2 if mode == 'complex': raise ValueError('Cannot plot a complex specgram') if scale is None or scale == 'default': if mode in ['angle', 'phase']: scale = 'linear' else: scale = 'dB' elif mode in ['angle', 'phase'] and scale == 'dB': raise ValueError('Cannot use dB scale with angle or phase mode') (spec, freqs, t) = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, mode=mode) if scale == 'linear': Z = spec elif scale == 'dB': if mode is None or mode == 'default' or mode == 'psd': Z = 10.0 * np.log10(spec) else: Z = 20.0 * np.log10(spec) else: raise ValueError(f'Unknown scale {scale!r}') Z = np.flipud(Z) if xextent is None: pad_xextent = (NFFT - noverlap) / Fs / 2 xextent = (np.min(t) - pad_xextent, np.max(t) + pad_xextent) (xmin, xmax) = xextent freqs += Fc extent = (xmin, xmax, freqs[0], freqs[-1]) if 'origin' in kwargs: raise _api.kwarg_error('specgram', 'origin') im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax, origin='upper', **kwargs) self.axis('auto') return (spec, freqs, t, im) @_api.make_keyword_only('3.9', 'precision') @_docstring.dedent_interpd def spy(self, Z, precision=0, marker=None, markersize=None, aspect='equal', origin='upper', **kwargs): if marker is None and markersize is None and hasattr(Z, 'tocoo'): marker = 's' _api.check_in_list(['upper', 'lower'], origin=origin) if marker is None and markersize is None: Z = np.asarray(Z) mask = np.abs(Z) > precision if 'cmap' not in kwargs: kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], name='binary') if 'interpolation' in kwargs: raise _api.kwarg_error('spy', 'interpolation') if 'norm' not in kwargs: kwargs['norm'] = mcolors.NoNorm() ret = self.imshow(mask, interpolation='nearest', aspect=aspect, origin=origin, **kwargs) else: if hasattr(Z, 'tocoo'): c = Z.tocoo() if precision == 'present': y = c.row x = c.col else: nonzero = np.abs(c.data) > precision y = c.row[nonzero] x = c.col[nonzero] else: Z = np.asarray(Z) nonzero = np.abs(Z) > precision (y, x) = np.nonzero(nonzero) if marker is None: marker = 's' if markersize is None: markersize = 10 if 'linestyle' in kwargs: raise _api.kwarg_error('spy', 'linestyle') ret = mlines.Line2D(x, y, linestyle='None', marker=marker, markersize=markersize, **kwargs) self.add_line(ret) (nr, nc) = Z.shape self.set_xlim(-0.5, nc - 0.5) if origin == 'upper': self.set_ylim(nr - 0.5, -0.5) else: self.set_ylim(-0.5, nr - 0.5) self.set_aspect(aspect) self.title.set_y(1.05) if origin == 'upper': self.xaxis.tick_top() else: self.xaxis.tick_bottom() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) return ret def matshow(self, Z, **kwargs): Z = np.asanyarray(Z) kw = {'origin': 'upper', 'interpolation': 'nearest', 'aspect': 'equal', **kwargs} im = self.imshow(Z, **kw) self.title.set_y(1.05) self.xaxis.tick_top() self.xaxis.set_ticks_position('both') self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True)) return im @_api.make_keyword_only('3.9', 'vert') @_preprocess_data(replace_names=['dataset']) def violinplot(self, dataset, positions=None, vert=None, orientation='vertical', widths=0.5, showmeans=False, showextrema=True, showmedians=False, quantiles=None, points=100, bw_method=None, side='both'): def _kde_method(X, coords): X = cbook._unpack_to_numpy(X) if np.all(X[0] == X): return (X[0] == coords).astype(float) kde = mlab.GaussianKDE(X, bw_method) return kde.evaluate(coords) vpstats = cbook.violin_stats(dataset, _kde_method, points=points, quantiles=quantiles) return self.violin(vpstats, positions=positions, vert=vert, orientation=orientation, widths=widths, showmeans=showmeans, showextrema=showextrema, showmedians=showmedians, side=side) @_api.make_keyword_only('3.9', 'vert') def violin(self, vpstats, positions=None, vert=None, orientation='vertical', widths=0.5, showmeans=False, showextrema=True, showmedians=False, side='both'): means = [] mins = [] maxes = [] medians = [] quantiles = [] qlens = [] artists = {} N = len(vpstats) datashape_message = 'List of violinplot statistics and `{0}` values must have the same length' if vert is not None: _api.warn_deprecated('3.10', name='vert: bool', alternative="orientation: {'vertical', 'horizontal'}") orientation = 'vertical' if vert else 'horizontal' _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) if positions is None: positions = range(1, N + 1) elif len(positions) != N: raise ValueError(datashape_message.format('positions')) if np.isscalar(widths): widths = [widths] * N elif len(widths) != N: raise ValueError(datashape_message.format('widths')) _api.check_in_list(['both', 'low', 'high'], side=side) line_ends = [[-0.25 if side in ['both', 'low'] else 0], [0.25 if side in ['both', 'high'] else 0]] * np.array(widths) + positions if mpl.rcParams['_internal.classic_mode']: fillcolor = 'y' linecolor = 'r' else: fillcolor = linecolor = self._get_lines.get_next_color() if orientation == 'vertical': fill = self.fill_betweenx if side in ['low', 'high']: perp_lines = functools.partial(self.hlines, colors=linecolor, capstyle='projecting') par_lines = functools.partial(self.vlines, colors=linecolor, capstyle='projecting') else: perp_lines = functools.partial(self.hlines, colors=linecolor) par_lines = functools.partial(self.vlines, colors=linecolor) else: fill = self.fill_between if side in ['low', 'high']: perp_lines = functools.partial(self.vlines, colors=linecolor, capstyle='projecting') par_lines = functools.partial(self.hlines, colors=linecolor, capstyle='projecting') else: perp_lines = functools.partial(self.vlines, colors=linecolor) par_lines = functools.partial(self.hlines, colors=linecolor) bodies = [] for (stats, pos, width) in zip(vpstats, positions, widths): vals = np.array(stats['vals']) vals = 0.5 * width * vals / vals.max() bodies += [fill(stats['coords'], -vals + pos if side in ['both', 'low'] else pos, vals + pos if side in ['both', 'high'] else pos, facecolor=fillcolor, alpha=0.3)] means.append(stats['mean']) mins.append(stats['min']) maxes.append(stats['max']) medians.append(stats['median']) q = stats.get('quantiles') if q is None: q = [] quantiles.extend(q) qlens.append(len(q)) artists['bodies'] = bodies if showmeans: artists['cmeans'] = perp_lines(means, *line_ends) if showextrema: artists['cmaxes'] = perp_lines(maxes, *line_ends) artists['cmins'] = perp_lines(mins, *line_ends) artists['cbars'] = par_lines(positions, mins, maxes) if showmedians: artists['cmedians'] = perp_lines(medians, *line_ends) if quantiles: artists['cquantiles'] = perp_lines(quantiles, *np.repeat(line_ends, qlens, axis=1)) return artists table = _make_axes_method(mtable.table) stackplot = _preprocess_data()(_make_axes_method(mstack.stackplot)) streamplot = _preprocess_data(replace_names=['x', 'y', 'u', 'v', 'start_points'])(_make_axes_method(mstream.streamplot)) tricontour = _make_axes_method(mtri.tricontour) tricontourf = _make_axes_method(mtri.tricontourf) tripcolor = _make_axes_method(mtri.tripcolor) triplot = _make_axes_method(mtri.triplot) def _get_aspect_ratio(self): figure_size = self.get_figure().get_size_inches() (ll, ur) = self.get_position() * figure_size (width, height) = ur - ll return height / (width * self.get_data_ratio()) # File: matplotlib-main/lib/matplotlib/axes/_base.py from collections.abc import Iterable, Sequence from contextlib import ExitStack import functools import inspect import logging from numbers import Real from operator import attrgetter import re import types import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, _docstring, offsetbox import matplotlib.artist as martist import matplotlib.axis as maxis from matplotlib.cbook import _OrderedSet, _check_1d, index_of import matplotlib.collections as mcoll import matplotlib.colors as mcolors import matplotlib.font_manager as font_manager from matplotlib.gridspec import SubplotSpec import matplotlib.image as mimage import matplotlib.lines as mlines import matplotlib.patches as mpatches from matplotlib.rcsetup import cycler, validate_axisbelow import matplotlib.spines as mspines import matplotlib.table as mtable import matplotlib.text as mtext import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms _log = logging.getLogger(__name__) class _axis_method_wrapper: def __init__(self, attr_name, method_name, *, doc_sub=None): self.attr_name = attr_name self.method_name = method_name doc = inspect.getdoc(getattr(maxis.Axis, method_name)) self._missing_subs = [] if doc: doc_sub = {'this Axis': f'the {self.attr_name}', **(doc_sub or {})} for (k, v) in doc_sub.items(): if k not in doc: self._missing_subs.append(k) doc = doc.replace(k, v) self.__doc__ = doc def __set_name__(self, owner, name): get_method = attrgetter(f'{self.attr_name}.{self.method_name}') def wrapper(self, *args, **kwargs): return get_method(self)(*args, **kwargs) wrapper.__module__ = owner.__module__ wrapper.__name__ = name wrapper.__qualname__ = f'{owner.__qualname__}.{name}' wrapper.__doc__ = self.__doc__ wrapper.__signature__ = inspect.signature(getattr(maxis.Axis, self.method_name)) if self._missing_subs: raise ValueError('The definition of {} expected that the docstring of Axis.{} contains {!r} as substrings'.format(wrapper.__qualname__, self.method_name, ', '.join(map(repr, self._missing_subs)))) setattr(owner, name, wrapper) class _TransformedBoundsLocator: def __init__(self, bounds, transform): self._bounds = bounds self._transform = transform def __call__(self, ax, renderer): return mtransforms.TransformedBbox(mtransforms.Bbox.from_bounds(*self._bounds), self._transform - ax.get_figure(root=False).transSubfigure) def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False): linestyle = None marker = None color = None if fmt not in ['0', '1']: try: color = mcolors.to_rgba(fmt) return (linestyle, marker, color) except ValueError: pass errfmt = '{!r} is neither a data key nor a valid format string ({})' if ambiguous_fmt_datakey else '{!r} is not a valid format string ({})' i = 0 while i < len(fmt): c = fmt[i] if fmt[i:i + 2] in mlines.lineStyles: if linestyle is not None: raise ValueError(errfmt.format(fmt, 'two linestyle symbols')) linestyle = fmt[i:i + 2] i += 2 elif c in mlines.lineStyles: if linestyle is not None: raise ValueError(errfmt.format(fmt, 'two linestyle symbols')) linestyle = c i += 1 elif c in mlines.lineMarkers: if marker is not None: raise ValueError(errfmt.format(fmt, 'two marker symbols')) marker = c i += 1 elif c in mcolors.get_named_colors_mapping(): if color is not None: raise ValueError(errfmt.format(fmt, 'two color symbols')) color = c i += 1 elif c == 'C': cn_color = re.match('C\\d+', fmt[i:]) if not cn_color: raise ValueError(errfmt.format(fmt, "'C' must be followed by a number")) color = mcolors.to_rgba(cn_color[0]) i += len(cn_color[0]) else: raise ValueError(errfmt.format(fmt, f'unrecognized character {c!r}')) if linestyle is None and marker is None: linestyle = mpl.rcParams['lines.linestyle'] if linestyle is None: linestyle = 'None' if marker is None: marker = 'None' return (linestyle, marker, color) class _process_plot_var_args: def __init__(self, command='plot'): self.command = command self.set_prop_cycle(None) def set_prop_cycle(self, cycler): if cycler is None: cycler = mpl.rcParams['axes.prop_cycle'] self._idx = 0 self._cycler_items = [*cycler] def __call__(self, axes, *args, data=None, **kwargs): axes._process_unit_info(kwargs=kwargs) for pos_only in 'xy': if pos_only in kwargs: raise _api.kwarg_error(self.command, pos_only) if not args: return if data is None: args = [cbook.sanitize_sequence(a) for a in args] else: replaced = [mpl._replacer(data, arg) for arg in args] if len(args) == 1: label_namer_idx = 0 elif len(args) == 2: try: _process_plot_format(args[1]) except ValueError: label_namer_idx = 1 else: if replaced[1] is not args[1]: _api.warn_external(f"Second argument {args[1]!r} is ambiguous: could be a format string but is in 'data'; using as data. If it was intended as data, set the format string to an empty string to suppress this warning. If it was intended as a format string, explicitly pass the x-values as well. Alternatively, rename the entry in 'data'.", RuntimeWarning) label_namer_idx = 1 else: label_namer_idx = 0 elif len(args) == 3: label_namer_idx = 1 else: raise ValueError('Using arbitrary long args with data is not supported due to ambiguity of arguments; use multiple plotting calls instead') if kwargs.get('label') is None: kwargs['label'] = mpl._label_from_arg(replaced[label_namer_idx], args[label_namer_idx]) args = replaced ambiguous_fmt_datakey = data is not None and len(args) == 2 if len(args) >= 4 and (not cbook.is_scalar_or_string(kwargs.get('label'))): raise ValueError('plot() with multiple groups of data (i.e., pairs of x and y) does not support multiple labels') while args: (this, args) = (args[:2], args[2:]) if args and isinstance(args[0], str): this += (args[0],) args = args[1:] yield from self._plot_args(axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey) def get_next_color(self): entry = self._cycler_items[self._idx] if 'color' in entry: self._idx = (self._idx + 1) % len(self._cycler_items) return entry['color'] else: return 'k' def _getdefaults(self, kw, ignore=frozenset()): defaults = self._cycler_items[self._idx] if any((kw.get(k, None) is None for k in {*defaults} - ignore)): self._idx = (self._idx + 1) % len(self._cycler_items) return {k: v for (k, v) in defaults.items() if k not in ignore} else: return {} def _setdefaults(self, defaults, kw): for k in defaults: if kw.get(k, None) is None: kw[k] = defaults[k] def _makeline(self, axes, x, y, kw, kwargs): kw = {**kw, **kwargs} self._setdefaults(self._getdefaults(kw), kw) seg = mlines.Line2D(x, y, **kw) return (seg, kw) def _makefill(self, axes, x, y, kw, kwargs): x = axes.convert_xunits(x) y = axes.convert_yunits(y) kw = kw.copy() kwargs = kwargs.copy() ignores = {'marker', 'markersize', 'markeredgecolor', 'markerfacecolor', 'markeredgewidth'} | {k for (k, v) in kwargs.items() if v is not None} default_dict = self._getdefaults(kw, ignores) self._setdefaults(default_dict, kw) facecolor = kw.get('color', None) default_dict.pop('color', None) self._setdefaults(default_dict, kwargs) seg = mpatches.Polygon(np.column_stack((x, y)), facecolor=facecolor, fill=kwargs.get('fill', True), closed=kw['closed']) seg.set(**kwargs) return (seg, kwargs) def _plot_args(self, axes, tup, kwargs, *, return_kwargs=False, ambiguous_fmt_datakey=False): if len(tup) > 1 and isinstance(tup[-1], str): (*xy, fmt) = tup (linestyle, marker, color) = _process_plot_format(fmt, ambiguous_fmt_datakey=ambiguous_fmt_datakey) elif len(tup) == 3: raise ValueError('third arg must be a format string') else: xy = tup (linestyle, marker, color) = (None, None, None) if any((v is None for v in tup)): raise ValueError('x, y, and format string must not be None') kw = {} for (prop_name, val) in zip(('linestyle', 'marker', 'color'), (linestyle, marker, color)): if val is not None: if fmt.lower() != 'none' and prop_name in kwargs and (val != 'None'): _api.warn_external(f'''{prop_name} is redundantly defined by the '{prop_name}' keyword argument and the fmt string "{fmt}" (-> {prop_name}={val!r}). The keyword argument will take precedence.''') kw[prop_name] = val if len(xy) == 2: x = _check_1d(xy[0]) y = _check_1d(xy[1]) else: (x, y) = index_of(xy[-1]) if axes.xaxis is not None: axes.xaxis.update_units(x) if axes.yaxis is not None: axes.yaxis.update_units(y) if x.shape[0] != y.shape[0]: raise ValueError(f'x and y must have same first dimension, but have shapes {x.shape} and {y.shape}') if x.ndim > 2 or y.ndim > 2: raise ValueError(f'x and y can be no greater than 2D, but have shapes {x.shape} and {y.shape}') if x.ndim == 1: x = x[:, np.newaxis] if y.ndim == 1: y = y[:, np.newaxis] if self.command == 'plot': make_artist = self._makeline else: kw['closed'] = kwargs.get('closed', True) make_artist = self._makefill (ncx, ncy) = (x.shape[1], y.shape[1]) if ncx > 1 and ncy > 1 and (ncx != ncy): raise ValueError(f'x has {ncx} columns but y has {ncy} columns') if ncx == 0 or ncy == 0: return [] label = kwargs.get('label') n_datasets = max(ncx, ncy) if cbook.is_scalar_or_string(label): labels = [label] * n_datasets elif len(label) == n_datasets: labels = label elif n_datasets == 1: msg = f'Passing label as a length {len(label)} sequence when plotting a single dataset is deprecated in Matplotlib 3.9 and will error in 3.11. To keep the current behavior, cast the sequence to string before passing.' _api.warn_deprecated('3.9', message=msg) labels = [label] else: raise ValueError(f'label must be scalar or have the same length as the input data, but found {len(label)} for {n_datasets} datasets.') result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw, {**kwargs, 'label': label}) for (j, label) in enumerate(labels)) if return_kwargs: return list(result) else: return [l[0] for l in result] @_api.define_aliases({'facecolor': ['fc']}) class _AxesBase(martist.Artist): name = 'rectilinear' _axis_names = ('x', 'y') _shared_axes = {name: cbook.Grouper() for name in _axis_names} _twinned_axes = cbook.Grouper() _subclass_uses_cla = False @property def _axis_map(self): return {name: getattr(self, f'{name}axis') for name in self._axis_names} def __str__(self): return '{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})'.format(type(self).__name__, self._position.bounds) def __init__(self, fig, *args, facecolor=None, frameon=True, sharex=None, sharey=None, label='', xscale=None, yscale=None, box_aspect=None, forward_navigation_events='auto', **kwargs): super().__init__() if 'rect' in kwargs: if args: raise TypeError("'rect' cannot be used together with positional arguments") rect = kwargs.pop('rect') _api.check_isinstance((mtransforms.Bbox, Iterable), rect=rect) args = (rect,) subplotspec = None if len(args) == 1 and isinstance(args[0], mtransforms.Bbox): self._position = args[0] elif len(args) == 1 and np.iterable(args[0]): self._position = mtransforms.Bbox.from_bounds(*args[0]) else: self._position = self._originalPosition = mtransforms.Bbox.unit() subplotspec = SubplotSpec._from_subplot_args(fig, args) if self._position.width < 0 or self._position.height < 0: raise ValueError('Width and height specified must be non-negative') self._originalPosition = self._position.frozen() self.axes = self self._aspect = 'auto' self._adjustable = 'box' self._anchor = 'C' self._stale_viewlims = dict.fromkeys(self._axis_names, False) self._forward_navigation_events = forward_navigation_events self._sharex = sharex self._sharey = sharey self.set_label(label) self.set_figure(fig) if subplotspec: self.set_subplotspec(subplotspec) else: self._subplotspec = None self.set_box_aspect(box_aspect) self._axes_locator = None self._children = [] self._colorbars = [] self.spines = mspines.Spines.from_dict(self._gen_axes_spines()) self._init_axis() if facecolor is None: facecolor = mpl.rcParams['axes.facecolor'] self._facecolor = facecolor self._frameon = frameon self.set_axisbelow(mpl.rcParams['axes.axisbelow']) self._rasterization_zorder = None self.clear() self.fmt_xdata = None self.fmt_ydata = None self.set_navigate(True) self.set_navigate_mode(None) if xscale: self.set_xscale(xscale) if yscale: self.set_yscale(yscale) self._internal_update(kwargs) for (name, axis) in self._axis_map.items(): axis.callbacks._connect_picklable('units', self._unit_change_handler(name)) rcParams = mpl.rcParams self.tick_params(top=rcParams['xtick.top'] and rcParams['xtick.minor.top'], bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'], labeltop=rcParams['xtick.labeltop'] and rcParams['xtick.minor.top'], labelbottom=rcParams['xtick.labelbottom'] and rcParams['xtick.minor.bottom'], left=rcParams['ytick.left'] and rcParams['ytick.minor.left'], right=rcParams['ytick.right'] and rcParams['ytick.minor.right'], labelleft=rcParams['ytick.labelleft'] and rcParams['ytick.minor.left'], labelright=rcParams['ytick.labelright'] and rcParams['ytick.minor.right'], which='minor') self.tick_params(top=rcParams['xtick.top'] and rcParams['xtick.major.top'], bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'], labeltop=rcParams['xtick.labeltop'] and rcParams['xtick.major.top'], labelbottom=rcParams['xtick.labelbottom'] and rcParams['xtick.major.bottom'], left=rcParams['ytick.left'] and rcParams['ytick.major.left'], right=rcParams['ytick.right'] and rcParams['ytick.major.right'], labelleft=rcParams['ytick.labelleft'] and rcParams['ytick.major.left'], labelright=rcParams['ytick.labelright'] and rcParams['ytick.major.right'], which='major') def __init_subclass__(cls, **kwargs): parent_uses_cla = super(cls, cls)._subclass_uses_cla if 'cla' in cls.__dict__: _api.warn_deprecated('3.6', pending=True, message=f'Overriding `Axes.cla` in {cls.__qualname__} is pending deprecation in %(since)s and will be fully deprecated in favor of `Axes.clear` in the future. Please report this to the {cls.__module__!r} author.') cls._subclass_uses_cla = 'cla' in cls.__dict__ or parent_uses_cla super().__init_subclass__(**kwargs) def __getstate__(self): state = super().__getstate__() state['_shared_axes'] = {name: self._shared_axes[name].get_siblings(self) for name in self._axis_names if self in self._shared_axes[name]} state['_twinned_axes'] = self._twinned_axes.get_siblings(self) if self in self._twinned_axes else None return state def __setstate__(self, state): shared_axes = state.pop('_shared_axes') for (name, shared_siblings) in shared_axes.items(): self._shared_axes[name].join(*shared_siblings) twinned_siblings = state.pop('_twinned_axes') if twinned_siblings: self._twinned_axes.join(*twinned_siblings) self.__dict__ = state self._stale = True def __repr__(self): fields = [] if self.get_label(): fields += [f'label={self.get_label()!r}'] if hasattr(self, 'get_title'): titles = {} for k in ['left', 'center', 'right']: title = self.get_title(loc=k) if title: titles[k] = title if titles: fields += [f'title={titles}'] for (name, axis) in self._axis_map.items(): if axis.get_label() and axis.get_label().get_text(): fields += [f'{name}label={axis.get_label().get_text()!r}'] return f'<{self.__class__.__name__}: ' + ', '.join(fields) + '>' def get_subplotspec(self): return self._subplotspec def set_subplotspec(self, subplotspec): self._subplotspec = subplotspec self._set_position(subplotspec.get_position(self.get_figure(root=False))) def get_gridspec(self): return self._subplotspec.get_gridspec() if self._subplotspec else None def get_window_extent(self, renderer=None): return self.bbox def _init_axis(self): self.xaxis = maxis.XAxis(self, clear=False) self.spines.bottom.register_axis(self.xaxis) self.spines.top.register_axis(self.xaxis) self.yaxis = maxis.YAxis(self, clear=False) self.spines.left.register_axis(self.yaxis) self.spines.right.register_axis(self.yaxis) def set_figure(self, fig): super().set_figure(fig) self.bbox = mtransforms.TransformedBbox(self._position, fig.transSubfigure) self.dataLim = mtransforms.Bbox.null() self._viewLim = mtransforms.Bbox.unit() self.transScale = mtransforms.TransformWrapper(mtransforms.IdentityTransform()) self._set_lim_and_transforms() def _unstale_viewLim(self): need_scale = {name: any((ax._stale_viewlims[name] for ax in self._shared_axes[name].get_siblings(self))) for name in self._axis_names} if any(need_scale.values()): for name in need_scale: for ax in self._shared_axes[name].get_siblings(self): ax._stale_viewlims[name] = False self.autoscale_view(**{f'scale{name}': scale for (name, scale) in need_scale.items()}) @property def viewLim(self): self._unstale_viewLim() return self._viewLim def _request_autoscale_view(self, axis='all', tight=None): axis_names = _api.check_getitem({**{k: [k] for k in self._axis_names}, 'all': self._axis_names}, axis=axis) for name in axis_names: self._stale_viewlims[name] = True if tight is not None: self._tight = tight def _set_lim_and_transforms(self): self.transAxes = mtransforms.BboxTransformTo(self.bbox) self.transScale = mtransforms.TransformWrapper(mtransforms.IdentityTransform()) self.transLimits = mtransforms.BboxTransformFrom(mtransforms.TransformedBbox(self._viewLim, self.transScale)) self.transData = self.transScale + (self.transLimits + self.transAxes) self._xaxis_transform = mtransforms.blended_transform_factory(self.transData, self.transAxes) self._yaxis_transform = mtransforms.blended_transform_factory(self.transAxes, self.transData) def get_xaxis_transform(self, which='grid'): if which == 'grid': return self._xaxis_transform elif which == 'tick1': return self.spines.bottom.get_spine_transform() elif which == 'tick2': return self.spines.top.get_spine_transform() else: raise ValueError(f'unknown value for which: {which!r}') def get_xaxis_text1_transform(self, pad_points): labels_align = mpl.rcParams['xtick.alignment'] return (self.get_xaxis_transform(which='tick1') + mtransforms.ScaledTranslation(0, -1 * pad_points / 72, self.get_figure(root=False).dpi_scale_trans), 'top', labels_align) def get_xaxis_text2_transform(self, pad_points): labels_align = mpl.rcParams['xtick.alignment'] return (self.get_xaxis_transform(which='tick2') + mtransforms.ScaledTranslation(0, pad_points / 72, self.get_figure(root=False).dpi_scale_trans), 'bottom', labels_align) def get_yaxis_transform(self, which='grid'): if which == 'grid': return self._yaxis_transform elif which == 'tick1': return self.spines.left.get_spine_transform() elif which == 'tick2': return self.spines.right.get_spine_transform() else: raise ValueError(f'unknown value for which: {which!r}') def get_yaxis_text1_transform(self, pad_points): labels_align = mpl.rcParams['ytick.alignment'] return (self.get_yaxis_transform(which='tick1') + mtransforms.ScaledTranslation(-1 * pad_points / 72, 0, self.get_figure(root=False).dpi_scale_trans), labels_align, 'right') def get_yaxis_text2_transform(self, pad_points): labels_align = mpl.rcParams['ytick.alignment'] return (self.get_yaxis_transform(which='tick2') + mtransforms.ScaledTranslation(pad_points / 72, 0, self.get_figure(root=False).dpi_scale_trans), labels_align, 'left') def _update_transScale(self): self.transScale.set(mtransforms.blended_transform_factory(self.xaxis.get_transform(), self.yaxis.get_transform())) def get_position(self, original=False): if original: return self._originalPosition.frozen() else: locator = self.get_axes_locator() if not locator: self.apply_aspect() return self._position.frozen() def set_position(self, pos, which='both'): self._set_position(pos, which=which) self.set_in_layout(False) def _set_position(self, pos, which='both'): if not isinstance(pos, mtransforms.BboxBase): pos = mtransforms.Bbox.from_bounds(*pos) for ax in self._twinned_axes.get_siblings(self): if which in ('both', 'active'): ax._position.set(pos) if which in ('both', 'original'): ax._originalPosition.set(pos) self.stale = True def reset_position(self): for ax in self._twinned_axes.get_siblings(self): pos = ax.get_position(original=True) ax.set_position(pos, which='active') def set_axes_locator(self, locator): self._axes_locator = locator self.stale = True def get_axes_locator(self): return self._axes_locator def _set_artist_props(self, a): a.set_figure(self.get_figure(root=False)) if not a.is_transform_set(): a.set_transform(self.transData) a.axes = self if a.get_mouseover(): self._mouseover_set.add(a) def _gen_axes_patch(self): return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0) def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'): return {side: mspines.Spine.linear_spine(self, side) for side in ['left', 'right', 'bottom', 'top']} def sharex(self, other): _api.check_isinstance(_AxesBase, other=other) if self._sharex is not None and other is not self._sharex: raise ValueError('x-axis is already shared') self._shared_axes['x'].join(self, other) self._sharex = other self.xaxis.major = other.xaxis.major self.xaxis.minor = other.xaxis.minor (x0, x1) = other.get_xlim() self.set_xlim(x0, x1, emit=False, auto=other.get_autoscalex_on()) self.xaxis._scale = other.xaxis._scale def sharey(self, other): _api.check_isinstance(_AxesBase, other=other) if self._sharey is not None and other is not self._sharey: raise ValueError('y-axis is already shared') self._shared_axes['y'].join(self, other) self._sharey = other self.yaxis.major = other.yaxis.major self.yaxis.minor = other.yaxis.minor (y0, y1) = other.get_ylim() self.set_ylim(y0, y1, emit=False, auto=other.get_autoscaley_on()) self.yaxis._scale = other.yaxis._scale def __clear(self): if hasattr(self, 'patch'): patch_visible = self.patch.get_visible() else: patch_visible = True xaxis_visible = self.xaxis.get_visible() yaxis_visible = self.yaxis.get_visible() for axis in self._axis_map.values(): axis.clear() for spine in self.spines.values(): spine._clear() self.ignore_existing_data_limits = True self.callbacks = cbook.CallbackRegistry(signals=['xlim_changed', 'ylim_changed', 'zlim_changed']) if mpl.rcParams['xtick.minor.visible']: self.xaxis.set_minor_locator(mticker.AutoMinorLocator()) if mpl.rcParams['ytick.minor.visible']: self.yaxis.set_minor_locator(mticker.AutoMinorLocator()) self._xmargin = mpl.rcParams['axes.xmargin'] self._ymargin = mpl.rcParams['axes.ymargin'] self._tight = None self._use_sticky_edges = True self._get_lines = _process_plot_var_args() self._get_patches_for_fill = _process_plot_var_args('fill') self._gridOn = mpl.rcParams['axes.grid'] (old_children, self._children) = (self._children, []) for chld in old_children: chld.axes = chld._parent_figure = None self._mouseover_set = _OrderedSet() self.child_axes = [] self._current_image = None self._projection_init = None self.legend_ = None self.containers = [] self.grid(False) self.grid(self._gridOn, which=mpl.rcParams['axes.grid.which'], axis=mpl.rcParams['axes.grid.axis']) props = font_manager.FontProperties(size=mpl.rcParams['axes.titlesize'], weight=mpl.rcParams['axes.titleweight']) y = mpl.rcParams['axes.titley'] if y is None: y = 1.0 self._autotitlepos = True else: self._autotitlepos = False self.title = mtext.Text(x=0.5, y=y, text='', fontproperties=props, verticalalignment='baseline', horizontalalignment='center') self._left_title = mtext.Text(x=0.0, y=y, text='', fontproperties=props.copy(), verticalalignment='baseline', horizontalalignment='left') self._right_title = mtext.Text(x=1.0, y=y, text='', fontproperties=props.copy(), verticalalignment='baseline', horizontalalignment='right') title_offset_points = mpl.rcParams['axes.titlepad'] self._set_title_offset_trans(title_offset_points) for _title in (self.title, self._left_title, self._right_title): self._set_artist_props(_title) self.patch = self._gen_axes_patch() self.patch.set_figure(self.get_figure(root=False)) self.patch.set_facecolor(self._facecolor) self.patch.set_edgecolor('none') self.patch.set_linewidth(0) self.patch.set_transform(self.transAxes) self.set_axis_on() self.xaxis.set_clip_path(self.patch) self.yaxis.set_clip_path(self.patch) if self._sharex is not None: self.xaxis.set_visible(xaxis_visible) self.patch.set_visible(patch_visible) if self._sharey is not None: self.yaxis.set_visible(yaxis_visible) self.patch.set_visible(patch_visible) for (name, axis) in self._axis_map.items(): share = getattr(self, f'_share{name}') if share is not None: getattr(self, f'share{name}')(share) else: if self.name == 'polar': axis._set_scale('linear') axis._set_lim(0, 1, auto=True) self._update_transScale() self.stale = True def clear(self): if self._subclass_uses_cla: self.cla() else: self.__clear() def cla(self): if self._subclass_uses_cla: self.__clear() else: self.clear() class ArtistList(Sequence): def __init__(self, axes, prop_name, valid_types=None, invalid_types=None): self._axes = axes self._prop_name = prop_name self._type_check = lambda artist: (not valid_types or isinstance(artist, valid_types)) and (not invalid_types or not isinstance(artist, invalid_types)) def __repr__(self): return f'' def __len__(self): return sum((self._type_check(artist) for artist in self._axes._children)) def __iter__(self): for artist in list(self._axes._children): if self._type_check(artist): yield artist def __getitem__(self, key): return [artist for artist in self._axes._children if self._type_check(artist)][key] def __add__(self, other): if isinstance(other, (list, _AxesBase.ArtistList)): return [*self, *other] if isinstance(other, (tuple, _AxesBase.ArtistList)): return (*self, *other) return NotImplemented def __radd__(self, other): if isinstance(other, list): return other + list(self) if isinstance(other, tuple): return other + tuple(self) return NotImplemented @property def artists(self): return self.ArtistList(self, 'artists', invalid_types=(mcoll.Collection, mimage.AxesImage, mlines.Line2D, mpatches.Patch, mtable.Table, mtext.Text)) @property def collections(self): return self.ArtistList(self, 'collections', valid_types=mcoll.Collection) @property def images(self): return self.ArtistList(self, 'images', valid_types=mimage.AxesImage) @property def lines(self): return self.ArtistList(self, 'lines', valid_types=mlines.Line2D) @property def patches(self): return self.ArtistList(self, 'patches', valid_types=mpatches.Patch) @property def tables(self): return self.ArtistList(self, 'tables', valid_types=mtable.Table) @property def texts(self): return self.ArtistList(self, 'texts', valid_types=mtext.Text) def get_facecolor(self): return self.patch.get_facecolor() def set_facecolor(self, color): self._facecolor = color self.stale = True return self.patch.set_facecolor(color) def _set_title_offset_trans(self, title_offset_points): self.titleOffsetTrans = mtransforms.ScaledTranslation(0.0, title_offset_points / 72, self.get_figure(root=False).dpi_scale_trans) for _title in (self.title, self._left_title, self._right_title): _title.set_transform(self.transAxes + self.titleOffsetTrans) _title.set_clip_box(None) def set_prop_cycle(self, *args, **kwargs): if args and kwargs: raise TypeError('Cannot supply both positional and keyword arguments to this method.') if len(args) == 1 and args[0] is None: prop_cycle = None else: prop_cycle = cycler(*args, **kwargs) self._get_lines.set_prop_cycle(prop_cycle) self._get_patches_for_fill.set_prop_cycle(prop_cycle) def get_aspect(self): return self._aspect def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): if cbook._str_equal(aspect, 'equal'): aspect = 1 if not cbook._str_equal(aspect, 'auto'): aspect = float(aspect) if aspect <= 0 or not np.isfinite(aspect): raise ValueError('aspect must be finite and positive ') if share: axes = {sibling for name in self._axis_names for sibling in self._shared_axes[name].get_siblings(self)} else: axes = [self] for ax in axes: ax._aspect = aspect if adjustable is None: adjustable = self._adjustable self.set_adjustable(adjustable, share=share) if anchor is not None: self.set_anchor(anchor, share=share) self.stale = True def get_adjustable(self): return self._adjustable def set_adjustable(self, adjustable, share=False): _api.check_in_list(['box', 'datalim'], adjustable=adjustable) if share: axs = {sibling for name in self._axis_names for sibling in self._shared_axes[name].get_siblings(self)} else: axs = [self] if adjustable == 'datalim' and any((getattr(ax.get_data_ratio, '__func__', None) != _AxesBase.get_data_ratio for ax in axs)): raise ValueError("Cannot set Axes adjustable to 'datalim' for Axes which override 'get_data_ratio'") for ax in axs: ax._adjustable = adjustable self.stale = True def get_box_aspect(self): return self._box_aspect def set_box_aspect(self, aspect=None): axs = {*self._twinned_axes.get_siblings(self), *self._twinned_axes.get_siblings(self)} if aspect is not None: aspect = float(aspect) for ax in axs: ax.set_adjustable('datalim') for ax in axs: ax._box_aspect = aspect ax.stale = True def get_anchor(self): return self._anchor def set_anchor(self, anchor, share=False): if not (anchor in mtransforms.Bbox.coefs or len(anchor) == 2): raise ValueError('argument must be among %s' % ', '.join(mtransforms.Bbox.coefs)) if share: axes = {sibling for name in self._axis_names for sibling in self._shared_axes[name].get_siblings(self)} else: axes = [self] for ax in axes: ax._anchor = anchor self.stale = True def get_data_ratio(self): (txmin, txmax) = self.xaxis.get_transform().transform(self.get_xbound()) (tymin, tymax) = self.yaxis.get_transform().transform(self.get_ybound()) xsize = max(abs(txmax - txmin), 1e-30) ysize = max(abs(tymax - tymin), 1e-30) return ysize / xsize def apply_aspect(self, position=None): if position is None: position = self.get_position(original=True) aspect = self.get_aspect() if aspect == 'auto' and self._box_aspect is None: self._set_position(position, which='active') return trans = self.get_figure(root=False).transSubfigure bb = mtransforms.Bbox.unit().transformed(trans) fig_aspect = bb.height / bb.width if self._adjustable == 'box': if self in self._twinned_axes: raise RuntimeError("Adjustable 'box' is not allowed in a twinned Axes; use 'datalim' instead") box_aspect = aspect * self.get_data_ratio() pb = position.frozen() pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect) self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') return if self._box_aspect is not None: pb = position.frozen() pb1 = pb.shrunk_to_aspect(self._box_aspect, pb, fig_aspect) self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') if aspect == 'auto': return if self._box_aspect is None: self._set_position(position, which='active') else: position = pb1.anchored(self.get_anchor(), pb) x_trf = self.xaxis.get_transform() y_trf = self.yaxis.get_transform() (xmin, xmax) = x_trf.transform(self.get_xbound()) (ymin, ymax) = y_trf.transform(self.get_ybound()) xsize = max(abs(xmax - xmin), 1e-30) ysize = max(abs(ymax - ymin), 1e-30) box_aspect = fig_aspect * (position.height / position.width) data_ratio = box_aspect / aspect y_expander = data_ratio * xsize / ysize - 1 if abs(y_expander) < 0.005: return dL = self.dataLim (x0, x1) = x_trf.transform(dL.intervalx) (y0, y1) = y_trf.transform(dL.intervaly) xr = 1.05 * (x1 - x0) yr = 1.05 * (y1 - y0) xmarg = xsize - xr ymarg = ysize - yr Ysize = data_ratio * xsize Xsize = ysize / data_ratio Xmarg = Xsize - xr Ymarg = Ysize - yr xm = 0 ym = 0 shared_x = self in self._shared_axes['x'] shared_y = self in self._shared_axes['y'] if shared_x and shared_y: raise RuntimeError("set_aspect(..., adjustable='datalim') or axis('equal') are not allowed when both axes are shared. Try set_aspect(..., adjustable='box').") if shared_y: adjust_y = False else: if xmarg > xm and ymarg > ym: adjy = Ymarg > 0 and y_expander < 0 or (Xmarg < 0 and y_expander > 0) else: adjy = y_expander > 0 adjust_y = shared_x or adjy if adjust_y: yc = 0.5 * (ymin + ymax) y0 = yc - Ysize / 2.0 y1 = yc + Ysize / 2.0 self.set_ybound(y_trf.inverted().transform([y0, y1])) else: xc = 0.5 * (xmin + xmax) x0 = xc - Xsize / 2.0 x1 = xc + Xsize / 2.0 self.set_xbound(x_trf.inverted().transform([x0, x1])) def axis(self, arg=None, /, *, emit=True, **kwargs): if isinstance(arg, (str, bool)): if arg is True: arg = 'on' if arg is False: arg = 'off' arg = arg.lower() if arg == 'on': self.set_axis_on() elif arg == 'off': self.set_axis_off() elif arg in ['equal', 'tight', 'scaled', 'auto', 'image', 'square']: self.set_autoscale_on(True) self.set_aspect('auto') self.autoscale_view(tight=False) if arg == 'equal': self.set_aspect('equal', adjustable='datalim') elif arg == 'scaled': self.set_aspect('equal', adjustable='box', anchor='C') self.set_autoscale_on(False) elif arg == 'tight': self.autoscale_view(tight=True) self.set_autoscale_on(False) elif arg == 'image': self.autoscale_view(tight=True) self.set_autoscale_on(False) self.set_aspect('equal', adjustable='box', anchor='C') elif arg == 'square': self.set_aspect('equal', adjustable='box', anchor='C') self.set_autoscale_on(False) xlim = self.get_xlim() ylim = self.get_ylim() edge_size = max(np.diff(xlim), np.diff(ylim))[0] self.set_xlim([xlim[0], xlim[0] + edge_size], emit=emit, auto=False) self.set_ylim([ylim[0], ylim[0] + edge_size], emit=emit, auto=False) else: raise ValueError(f"Unrecognized string {arg!r} to axis; try 'on' or 'off'") else: if arg is not None: if len(arg) != 2 * len(self._axis_names): raise TypeError('The first argument to axis() must be an iterable of the form [{}]'.format(', '.join((f'{name}min, {name}max' for name in self._axis_names)))) limits = {name: arg[2 * i:2 * (i + 1)] for (i, name) in enumerate(self._axis_names)} else: limits = {} for name in self._axis_names: ax_min = kwargs.pop(f'{name}min', None) ax_max = kwargs.pop(f'{name}max', None) limits[name] = (ax_min, ax_max) for (name, (ax_min, ax_max)) in limits.items(): ax_auto = None if ax_min is None and ax_max is None else False set_ax_lim = getattr(self, f'set_{name}lim') set_ax_lim(ax_min, ax_max, emit=emit, auto=ax_auto) if kwargs: raise _api.kwarg_error('axis', kwargs) lims = () for name in self._axis_names: get_ax_lim = getattr(self, f'get_{name}lim') lims += get_ax_lim() return lims def get_legend(self): return self.legend_ def get_images(self): return cbook.silent_list('AxesImage', self.images) def get_lines(self): return cbook.silent_list('Line2D', self.lines) def get_xaxis(self): return self.xaxis def get_yaxis(self): return self.yaxis get_xgridlines = _axis_method_wrapper('xaxis', 'get_gridlines') get_xticklines = _axis_method_wrapper('xaxis', 'get_ticklines') get_ygridlines = _axis_method_wrapper('yaxis', 'get_gridlines') get_yticklines = _axis_method_wrapper('yaxis', 'get_ticklines') def _sci(self, im): _api.check_isinstance((mcoll.Collection, mimage.AxesImage), im=im) if im not in self._children: raise ValueError('Argument must be an image or collection in this Axes') self._current_image = im def _gci(self): return self._current_image def has_data(self): return any((isinstance(a, (mcoll.Collection, mimage.AxesImage, mlines.Line2D, mpatches.Patch)) for a in self._children)) def add_artist(self, a): a.axes = self self._children.append(a) a._remove_method = self._children.remove self._set_artist_props(a) if a.get_clip_path() is None: a.set_clip_path(self.patch) self.stale = True return a def add_child_axes(self, ax): ax._axes = self ax.stale_callback = martist._stale_axes_callback self.child_axes.append(ax) ax._remove_method = functools.partial(self.get_figure(root=False)._remove_axes, owners=[self.child_axes]) self.stale = True return ax def add_collection(self, collection, autolim=True): _api.check_isinstance(mcoll.Collection, collection=collection) if not collection.get_label(): collection.set_label(f'_child{len(self._children)}') self._children.append(collection) collection._remove_method = self._children.remove self._set_artist_props(collection) if collection.get_clip_path() is None: collection.set_clip_path(self.patch) if autolim: self._unstale_viewLim() datalim = collection.get_datalim(self.transData) points = datalim.get_points() if not np.isinf(datalim.minpos).all(): points = np.concatenate([points, [datalim.minpos]]) self.update_datalim(points) self.stale = True return collection def add_image(self, image): _api.check_isinstance(mimage.AxesImage, image=image) self._set_artist_props(image) if not image.get_label(): image.set_label(f'_child{len(self._children)}') self._children.append(image) image._remove_method = self._children.remove self.stale = True return image def _update_image_limits(self, image): (xmin, xmax, ymin, ymax) = image.get_extent() self.axes.update_datalim(((xmin, ymin), (xmax, ymax))) def add_line(self, line): _api.check_isinstance(mlines.Line2D, line=line) self._set_artist_props(line) if line.get_clip_path() is None: line.set_clip_path(self.patch) self._update_line_limits(line) if not line.get_label(): line.set_label(f'_child{len(self._children)}') self._children.append(line) line._remove_method = self._children.remove self.stale = True return line def _add_text(self, txt): _api.check_isinstance(mtext.Text, txt=txt) self._set_artist_props(txt) self._children.append(txt) txt._remove_method = self._children.remove self.stale = True return txt def _update_line_limits(self, line): path = line.get_path() if path.vertices.size == 0: return line_trf = line.get_transform() if line_trf == self.transData: data_path = path elif any(line_trf.contains_branch_seperately(self.transData)): trf_to_data = line_trf - self.transData if self.transData.is_affine: line_trans_path = line._get_transformed_path() (na_path, _) = line_trans_path.get_transformed_path_and_affine() data_path = trf_to_data.transform_path_affine(na_path) else: data_path = trf_to_data.transform_path(path) else: data_path = path if not data_path.vertices.size: return (updatex, updatey) = line_trf.contains_branch_seperately(self.transData) if self.name != 'rectilinear': if updatex and line_trf == self.get_yaxis_transform(): updatex = False if updatey and line_trf == self.get_xaxis_transform(): updatey = False self.dataLim.update_from_path(data_path, self.ignore_existing_data_limits, updatex=updatex, updatey=updatey) self.ignore_existing_data_limits = False def add_patch(self, p): _api.check_isinstance(mpatches.Patch, p=p) self._set_artist_props(p) if p.get_clip_path() is None: p.set_clip_path(self.patch) self._update_patch_limits(p) self._children.append(p) p._remove_method = self._children.remove return p def _update_patch_limits(self, patch): if isinstance(patch, mpatches.Rectangle) and (not patch.get_width() and (not patch.get_height())): return p = patch.get_path() vertices = [] for (curve, code) in p.iter_bezier(simplify=False): (_, dzeros) = curve.axis_aligned_extrema() vertices.append(curve([0, *dzeros, 1])) if len(vertices): vertices = np.vstack(vertices) patch_trf = patch.get_transform() (updatex, updatey) = patch_trf.contains_branch_seperately(self.transData) if not (updatex or updatey): return if self.name != 'rectilinear': if updatex and patch_trf == self.get_yaxis_transform(): updatex = False if updatey and patch_trf == self.get_xaxis_transform(): updatey = False trf_to_data = patch_trf - self.transData xys = trf_to_data.transform(vertices) self.update_datalim(xys, updatex=updatex, updatey=updatey) def add_table(self, tab): _api.check_isinstance(mtable.Table, tab=tab) self._set_artist_props(tab) self._children.append(tab) if tab.get_clip_path() is None: tab.set_clip_path(self.patch) tab._remove_method = self._children.remove return tab def add_container(self, container): label = container.get_label() if not label: container.set_label('_container%d' % len(self.containers)) self.containers.append(container) container._remove_method = self.containers.remove return container def _unit_change_handler(self, axis_name, event=None): if event is None: return functools.partial(self._unit_change_handler, axis_name, event=object()) _api.check_in_list(self._axis_map, axis_name=axis_name) for line in self.lines: line.recache_always() self.relim() self._request_autoscale_view(axis_name) def relim(self, visible_only=False): self.dataLim.ignore(True) self.dataLim.set_points(mtransforms.Bbox.null().get_points()) self.ignore_existing_data_limits = True for artist in self._children: if not visible_only or artist.get_visible(): if isinstance(artist, mlines.Line2D): self._update_line_limits(artist) elif isinstance(artist, mpatches.Patch): self._update_patch_limits(artist) elif isinstance(artist, mimage.AxesImage): self._update_image_limits(artist) def update_datalim(self, xys, updatex=True, updatey=True): xys = np.asarray(xys) if not np.any(np.isfinite(xys)): return self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits, updatex=updatex, updatey=updatey) self.ignore_existing_data_limits = False def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True): datasets = datasets or [] kwargs = kwargs or {} axis_map = self._axis_map for (axis_name, data) in datasets: try: axis = axis_map[axis_name] except KeyError: raise ValueError(f'Invalid axis name: {axis_name!r}') from None if axis is not None and data is not None and (not axis.have_units()): axis.update_units(data) for (axis_name, axis) in axis_map.items(): if axis is None: continue units = kwargs.pop(f'{axis_name}units', axis.units) if self.name == 'polar': polar_units = {'x': 'thetaunits', 'y': 'runits'} units = kwargs.pop(polar_units[axis_name], units) if units != axis.units and units is not None: axis.set_units(units) for (dataset_axis_name, data) in datasets: if dataset_axis_name == axis_name and data is not None: axis.update_units(data) return [axis_map[axis_name].convert_units(data) if convert and data is not None else data for (axis_name, data) in datasets] def in_axes(self, mouseevent): return self.patch.contains(mouseevent)[0] get_autoscalex_on = _axis_method_wrapper('xaxis', '_get_autoscale_on') get_autoscaley_on = _axis_method_wrapper('yaxis', '_get_autoscale_on') set_autoscalex_on = _axis_method_wrapper('xaxis', '_set_autoscale_on') set_autoscaley_on = _axis_method_wrapper('yaxis', '_set_autoscale_on') def get_autoscale_on(self): return all((axis._get_autoscale_on() for axis in self._axis_map.values())) def set_autoscale_on(self, b): for axis in self._axis_map.values(): axis._set_autoscale_on(b) @property def use_sticky_edges(self): return self._use_sticky_edges @use_sticky_edges.setter def use_sticky_edges(self, b): self._use_sticky_edges = bool(b) def get_xmargin(self): return self._xmargin def get_ymargin(self): return self._ymargin def set_xmargin(self, m): if m <= -0.5: raise ValueError('margin must be greater than -0.5') self._xmargin = m self._request_autoscale_view('x') self.stale = True def set_ymargin(self, m): if m <= -0.5: raise ValueError('margin must be greater than -0.5') self._ymargin = m self._request_autoscale_view('y') self.stale = True def margins(self, *margins, x=None, y=None, tight=True): if margins and (x is not None or y is not None): raise TypeError('Cannot pass both positional and keyword arguments for x and/or y.') elif len(margins) == 1: x = y = margins[0] elif len(margins) == 2: (x, y) = margins elif margins: raise TypeError('Must pass a single positional argument for all margins, or one for each margin (x, y).') if x is None and y is None: if tight is not True: _api.warn_external(f'ignoring tight={tight!r} in get mode') return (self._xmargin, self._ymargin) if tight is not None: self._tight = tight if x is not None: self.set_xmargin(x) if y is not None: self.set_ymargin(y) def set_rasterization_zorder(self, z): self._rasterization_zorder = z self.stale = True def get_rasterization_zorder(self): return self._rasterization_zorder def autoscale(self, enable=True, axis='both', tight=None): if enable is None: scalex = True scaley = True else: if axis in ['x', 'both']: self.set_autoscalex_on(bool(enable)) scalex = self.get_autoscalex_on() else: scalex = False if axis in ['y', 'both']: self.set_autoscaley_on(bool(enable)) scaley = self.get_autoscaley_on() else: scaley = False if tight and scalex: self._xmargin = 0 if tight and scaley: self._ymargin = 0 if scalex: self._request_autoscale_view('x', tight=tight) if scaley: self._request_autoscale_view('y', tight=tight) def autoscale_view(self, tight=None, scalex=True, scaley=True): if tight is not None: self._tight = bool(tight) x_stickies = y_stickies = np.array([]) if self.use_sticky_edges: if self._xmargin and scalex and self.get_autoscalex_on(): x_stickies = np.sort(np.concatenate([artist.sticky_edges.x for ax in self._shared_axes['x'].get_siblings(self) for artist in ax.get_children()])) if self._ymargin and scaley and self.get_autoscaley_on(): y_stickies = np.sort(np.concatenate([artist.sticky_edges.y for ax in self._shared_axes['y'].get_siblings(self) for artist in ax.get_children()])) if self.get_xscale() == 'log': x_stickies = x_stickies[x_stickies > 0] if self.get_yscale() == 'log': y_stickies = y_stickies[y_stickies > 0] def handle_single_axis(scale, shared_axes, name, axis, margin, stickies, set_bound): if not (scale and axis._get_autoscale_on()): return shared = shared_axes.get_siblings(self) values = [val for ax in shared for val in getattr(ax.dataLim, f'interval{name}') if np.isfinite(val)] if values: (x0, x1) = (min(values), max(values)) elif getattr(self._viewLim, f'mutated{name}')(): return else: (x0, x1) = (-np.inf, np.inf) locator = axis.get_major_locator() (x0, x1) = locator.nonsingular(x0, x1) minimum_minpos = min((getattr(ax.dataLim, f'minpos{name}') for ax in shared)) tol = 1e-05 * abs(x1 - x0) i0 = stickies.searchsorted(x0 + tol) - 1 x0bound = stickies[i0] if i0 != -1 else None i1 = stickies.searchsorted(x1 - tol) x1bound = stickies[i1] if i1 != len(stickies) else None transform = axis.get_transform() inverse_trans = transform.inverted() (x0, x1) = axis._scale.limit_range_for_scale(x0, x1, minimum_minpos) (x0t, x1t) = transform.transform([x0, x1]) delta = (x1t - x0t) * margin if not np.isfinite(delta): delta = 0 (x0, x1) = inverse_trans.transform([x0t - delta, x1t + delta]) if x0bound is not None: x0 = max(x0, x0bound) if x1bound is not None: x1 = min(x1, x1bound) if not self._tight: (x0, x1) = locator.view_limits(x0, x1) set_bound(x0, x1) handle_single_axis(scalex, self._shared_axes['x'], 'x', self.xaxis, self._xmargin, x_stickies, self.set_xbound) handle_single_axis(scaley, self._shared_axes['y'], 'y', self.yaxis, self._ymargin, y_stickies, self.set_ybound) def _update_title_position(self, renderer): if self._autotitlepos is not None and (not self._autotitlepos): _log.debug('title position was updated manually, not adjusting') return titles = (self.title, self._left_title, self._right_title) if not any((title.get_text() for title in titles)): return axs = set() axs.update(self.child_axes) axs.update(self._twinned_axes.get_siblings(self)) axs.update(self.get_figure(root=False)._align_label_groups['title'].get_siblings(self)) for ax in self.child_axes: locator = ax.get_axes_locator() ax.apply_aspect(locator(self, renderer) if locator else None) top = -np.inf for ax in axs: bb = None xticklabel_top = any((tick.label2.get_visible() for tick in [ax.xaxis.majorTicks[0], ax.xaxis.minorTicks[0]])) if xticklabel_top or ax.xaxis.get_label_position() == 'top': bb = ax.xaxis.get_tightbbox(renderer) if bb is None: bb = ax.spines.get('outline', ax).get_window_extent() top = max(top, bb.ymax) for title in titles: (x, _) = title.get_position() title.set_position((x, 1.0)) if title.get_text(): for ax in axs: ax.yaxis.get_tightbbox(renderer) if ax.yaxis.offsetText.get_text(): bb = ax.yaxis.offsetText.get_tightbbox(renderer) if bb.intersection(title.get_tightbbox(renderer), bb): top = bb.ymax if top < 0: _log.debug('top of Axes not in the figure, so title not moved') return if title.get_window_extent(renderer).ymin < top: (_, y) = self.transAxes.inverted().transform((0, top)) title.set_position((x, y)) if title.get_window_extent(renderer).ymin < top: (_, y) = self.transAxes.inverted().transform((0.0, 2 * top - title.get_window_extent(renderer).ymin)) title.set_position((x, y)) ymax = max((title.get_position()[1] for title in titles)) for title in titles: (x, _) = title.get_position() title.set_position((x, ymax)) @martist.allow_rasterization def draw(self, renderer): if renderer is None: raise RuntimeError('No renderer defined') if not self.get_visible(): return self._unstale_viewLim() renderer.open_group('axes', gid=self.get_gid()) self._stale = True locator = self.get_axes_locator() self.apply_aspect(locator(self, renderer) if locator else None) artists = self.get_children() artists.remove(self.patch) if not (self.axison and self._frameon): for spine in self.spines.values(): artists.remove(spine) self._update_title_position(renderer) if not self.axison: for _axis in self._axis_map.values(): artists.remove(_axis) if not self.get_figure(root=True).canvas.is_saving(): artists = [a for a in artists if not a.get_animated() or isinstance(a, mimage.AxesImage)] artists = sorted(artists, key=attrgetter('zorder')) rasterization_zorder = self._rasterization_zorder if rasterization_zorder is not None and artists and (artists[0].zorder < rasterization_zorder): split_index = np.searchsorted([art.zorder for art in artists], rasterization_zorder, side='right') artists_rasterized = artists[:split_index] artists = artists[split_index:] else: artists_rasterized = [] if self.axison and self._frameon: if artists_rasterized: artists_rasterized = [self.patch] + artists_rasterized else: artists = [self.patch] + artists if artists_rasterized: _draw_rasterized(self.get_figure(root=True), artists_rasterized, renderer) mimage._draw_list_compositing_images(renderer, self, artists, self.get_figure(root=True).suppressComposite) renderer.close_group('axes') self.stale = False def draw_artist(self, a): a.draw(self.get_figure(root=True).canvas.get_renderer()) def redraw_in_frame(self): with ExitStack() as stack: for artist in [*self._axis_map.values(), self.title, self._left_title, self._right_title]: stack.enter_context(artist._cm_set(visible=False)) self.draw(self.get_figure(root=True).canvas.get_renderer()) def get_frame_on(self): return self._frameon def set_frame_on(self, b): self._frameon = b self.stale = True def get_axisbelow(self): return self._axisbelow def set_axisbelow(self, b): self._axisbelow = axisbelow = validate_axisbelow(b) zorder = {True: 0.5, 'line': 1.5, False: 2.5}[axisbelow] for axis in self._axis_map.values(): axis.set_zorder(zorder) self.stale = True @_docstring.dedent_interpd def grid(self, visible=None, which='major', axis='both', **kwargs): _api.check_in_list(['x', 'y', 'both'], axis=axis) if axis in ['x', 'both']: self.xaxis.grid(visible, which=which, **kwargs) if axis in ['y', 'both']: self.yaxis.grid(visible, which=which, **kwargs) def ticklabel_format(self, *, axis='both', style=None, scilimits=None, useOffset=None, useLocale=None, useMathText=None): if isinstance(style, str): style = style.lower() axis = axis.lower() if scilimits is not None: try: (m, n) = scilimits m + n + 1 except (ValueError, TypeError) as err: raise ValueError('scilimits must be a sequence of 2 integers') from err STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None, None: None} is_sci_style = _api.check_getitem(STYLES, style=style) axis_map = {**{k: [v] for (k, v) in self._axis_map.items()}, 'both': list(self._axis_map.values())} axises = _api.check_getitem(axis_map, axis=axis) try: for axis in axises: if is_sci_style is not None: axis.major.formatter.set_scientific(is_sci_style) if scilimits is not None: axis.major.formatter.set_powerlimits(scilimits) if useOffset is not None: axis.major.formatter.set_useOffset(useOffset) if useLocale is not None: axis.major.formatter.set_useLocale(useLocale) if useMathText is not None: axis.major.formatter.set_useMathText(useMathText) except AttributeError as err: raise AttributeError('This method only works with the ScalarFormatter') from err def locator_params(self, axis='both', tight=None, **kwargs): _api.check_in_list([*self._axis_names, 'both'], axis=axis) for name in self._axis_names: if axis in [name, 'both']: loc = self._axis_map[name].get_major_locator() loc.set_params(**kwargs) self._request_autoscale_view(name, tight=tight) self.stale = True def tick_params(self, axis='both', **kwargs): _api.check_in_list(['x', 'y', 'both'], axis=axis) if axis in ['x', 'both']: xkw = dict(kwargs) xkw.pop('left', None) xkw.pop('right', None) xkw.pop('labelleft', None) xkw.pop('labelright', None) self.xaxis.set_tick_params(**xkw) if axis in ['y', 'both']: ykw = dict(kwargs) ykw.pop('top', None) ykw.pop('bottom', None) ykw.pop('labeltop', None) ykw.pop('labelbottom', None) self.yaxis.set_tick_params(**ykw) def set_axis_off(self): self.axison = False self.stale = True def set_axis_on(self): self.axison = True self.stale = True def get_xlabel(self): label = self.xaxis.get_label() return label.get_text() def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs): if labelpad is not None: self.xaxis.labelpad = labelpad protected_kw = ['x', 'horizontalalignment', 'ha'] if {*kwargs} & {*protected_kw}: if loc is not None: raise TypeError(f"Specifying 'loc' is disallowed when any of its corresponding low level keyword arguments ({protected_kw}) are also supplied") else: loc = loc if loc is not None else mpl.rcParams['xaxis.labellocation'] _api.check_in_list(('left', 'center', 'right'), loc=loc) x = {'left': 0, 'center': 0.5, 'right': 1}[loc] kwargs.update(x=x, horizontalalignment=loc) return self.xaxis.set_label_text(xlabel, fontdict, **kwargs) def invert_xaxis(self): self.xaxis.set_inverted(not self.xaxis.get_inverted()) xaxis_inverted = _axis_method_wrapper('xaxis', 'get_inverted') def get_xbound(self): (left, right) = self.get_xlim() if left < right: return (left, right) else: return (right, left) def set_xbound(self, lower=None, upper=None): if upper is None and np.iterable(lower): (lower, upper) = lower (old_lower, old_upper) = self.get_xbound() if lower is None: lower = old_lower if upper is None: upper = old_upper self.set_xlim(sorted((lower, upper), reverse=bool(self.xaxis_inverted())), auto=None) def get_xlim(self): return tuple(self.viewLim.intervalx) def _validate_converted_limits(self, limit, convert): if limit is not None: converted_limit = convert(limit) if isinstance(converted_limit, np.ndarray): converted_limit = converted_limit.squeeze() if isinstance(converted_limit, Real) and (not np.isfinite(converted_limit)): raise ValueError('Axis limits cannot be NaN or Inf') return converted_limit def set_xlim(self, left=None, right=None, *, emit=True, auto=False, xmin=None, xmax=None): if right is None and np.iterable(left): (left, right) = left if xmin is not None: if left is not None: raise TypeError("Cannot pass both 'left' and 'xmin'") left = xmin if xmax is not None: if right is not None: raise TypeError("Cannot pass both 'right' and 'xmax'") right = xmax return self.xaxis._set_lim(left, right, emit=emit, auto=auto) get_xscale = _axis_method_wrapper('xaxis', 'get_scale') set_xscale = _axis_method_wrapper('xaxis', '_set_axes_scale') get_xticks = _axis_method_wrapper('xaxis', 'get_ticklocs') set_xticks = _axis_method_wrapper('xaxis', 'set_ticks', doc_sub={'set_ticks': 'set_xticks'}) get_xmajorticklabels = _axis_method_wrapper('xaxis', 'get_majorticklabels') get_xminorticklabels = _axis_method_wrapper('xaxis', 'get_minorticklabels') get_xticklabels = _axis_method_wrapper('xaxis', 'get_ticklabels') set_xticklabels = _axis_method_wrapper('xaxis', 'set_ticklabels', doc_sub={'Axis.set_ticks': 'Axes.set_xticks'}) def get_ylabel(self): label = self.yaxis.get_label() return label.get_text() def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs): if labelpad is not None: self.yaxis.labelpad = labelpad protected_kw = ['y', 'horizontalalignment', 'ha'] if {*kwargs} & {*protected_kw}: if loc is not None: raise TypeError(f"Specifying 'loc' is disallowed when any of its corresponding low level keyword arguments ({protected_kw}) are also supplied") else: loc = loc if loc is not None else mpl.rcParams['yaxis.labellocation'] _api.check_in_list(('bottom', 'center', 'top'), loc=loc) (y, ha) = {'bottom': (0, 'left'), 'center': (0.5, 'center'), 'top': (1, 'right')}[loc] kwargs.update(y=y, horizontalalignment=ha) return self.yaxis.set_label_text(ylabel, fontdict, **kwargs) def invert_yaxis(self): self.yaxis.set_inverted(not self.yaxis.get_inverted()) yaxis_inverted = _axis_method_wrapper('yaxis', 'get_inverted') def get_ybound(self): (bottom, top) = self.get_ylim() if bottom < top: return (bottom, top) else: return (top, bottom) def set_ybound(self, lower=None, upper=None): if upper is None and np.iterable(lower): (lower, upper) = lower (old_lower, old_upper) = self.get_ybound() if lower is None: lower = old_lower if upper is None: upper = old_upper self.set_ylim(sorted((lower, upper), reverse=bool(self.yaxis_inverted())), auto=None) def get_ylim(self): return tuple(self.viewLim.intervaly) def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False, ymin=None, ymax=None): if top is None and np.iterable(bottom): (bottom, top) = bottom if ymin is not None: if bottom is not None: raise TypeError("Cannot pass both 'bottom' and 'ymin'") bottom = ymin if ymax is not None: if top is not None: raise TypeError("Cannot pass both 'top' and 'ymax'") top = ymax return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto) get_yscale = _axis_method_wrapper('yaxis', 'get_scale') set_yscale = _axis_method_wrapper('yaxis', '_set_axes_scale') get_yticks = _axis_method_wrapper('yaxis', 'get_ticklocs') set_yticks = _axis_method_wrapper('yaxis', 'set_ticks', doc_sub={'set_ticks': 'set_yticks'}) get_ymajorticklabels = _axis_method_wrapper('yaxis', 'get_majorticklabels') get_yminorticklabels = _axis_method_wrapper('yaxis', 'get_minorticklabels') get_yticklabels = _axis_method_wrapper('yaxis', 'get_ticklabels') set_yticklabels = _axis_method_wrapper('yaxis', 'set_ticklabels', doc_sub={'Axis.set_ticks': 'Axes.set_yticks'}) xaxis_date = _axis_method_wrapper('xaxis', 'axis_date') yaxis_date = _axis_method_wrapper('yaxis', 'axis_date') def format_xdata(self, x): return (self.fmt_xdata if self.fmt_xdata is not None else self.xaxis.get_major_formatter().format_data_short)(x) def format_ydata(self, y): return (self.fmt_ydata if self.fmt_ydata is not None else self.yaxis.get_major_formatter().format_data_short)(y) def format_coord(self, x, y): twins = self._twinned_axes.get_siblings(self) if len(twins) == 1: return '(x, y) = ({}, {})'.format('???' if x is None else self.format_xdata(x), '???' if y is None else self.format_ydata(y)) screen_xy = self.transData.transform((x, y)) xy_strs = [] for ax in sorted(twins, key=attrgetter('zorder')): (data_x, data_y) = ax.transData.inverted().transform(screen_xy) xy_strs.append('({}, {})'.format(ax.format_xdata(data_x), ax.format_ydata(data_y))) return '(x, y) = {}'.format(' | '.join(xy_strs)) def minorticks_on(self): self.xaxis.minorticks_on() self.yaxis.minorticks_on() def minorticks_off(self): self.xaxis.minorticks_off() self.yaxis.minorticks_off() def can_zoom(self): return True def can_pan(self): return True def get_navigate(self): return self._navigate def set_navigate(self, b): self._navigate = b def get_navigate_mode(self): return self._navigate_mode def set_navigate_mode(self, b): self._navigate_mode = b def _get_view(self): return {'xlim': self.get_xlim(), 'autoscalex_on': self.get_autoscalex_on(), 'ylim': self.get_ylim(), 'autoscaley_on': self.get_autoscaley_on()} def _set_view(self, view): self.set(**view) def _prepare_view_from_bbox(self, bbox, direction='in', mode=None, twinx=False, twiny=False): if len(bbox) == 3: (xp, yp, scl) = bbox if scl == 0: scl = 1.0 if scl > 1: direction = 'in' else: direction = 'out' scl = 1 / scl ((xmin, ymin), (xmax, ymax)) = self.transData.transform(np.transpose([self.get_xlim(), self.get_ylim()])) xwidth = xmax - xmin ywidth = ymax - ymin xcen = (xmax + xmin) * 0.5 ycen = (ymax + ymin) * 0.5 xzc = (xp * (scl - 1) + xcen) / scl yzc = (yp * (scl - 1) + ycen) / scl bbox = [xzc - xwidth / 2.0 / scl, yzc - ywidth / 2.0 / scl, xzc + xwidth / 2.0 / scl, yzc + ywidth / 2.0 / scl] elif len(bbox) != 4: _api.warn_external('Warning in _set_view_from_bbox: bounding box is not a tuple of length 3 or 4. Ignoring the view change.') return (xmin0, xmax0) = self.get_xbound() (ymin0, ymax0) = self.get_ybound() (startx, starty, stopx, stopy) = bbox ((startx, starty), (stopx, stopy)) = self.transData.inverted().transform([(startx, starty), (stopx, stopy)]) (xmin, xmax) = np.clip(sorted([startx, stopx]), xmin0, xmax0) (ymin, ymax) = np.clip(sorted([starty, stopy]), ymin0, ymax0) if twinx or mode == 'y': (xmin, xmax) = (xmin0, xmax0) if twiny or mode == 'x': (ymin, ymax) = (ymin0, ymax0) if direction == 'in': new_xbound = (xmin, xmax) new_ybound = (ymin, ymax) elif direction == 'out': x_trf = self.xaxis.get_transform() (sxmin0, sxmax0, sxmin, sxmax) = x_trf.transform([xmin0, xmax0, xmin, xmax]) factor = (sxmax0 - sxmin0) / (sxmax - sxmin) sxmin1 = sxmin0 - factor * (sxmin - sxmin0) sxmax1 = sxmax0 + factor * (sxmax0 - sxmax) new_xbound = x_trf.inverted().transform([sxmin1, sxmax1]) y_trf = self.yaxis.get_transform() (symin0, symax0, symin, symax) = y_trf.transform([ymin0, ymax0, ymin, ymax]) factor = (symax0 - symin0) / (symax - symin) symin1 = symin0 - factor * (symin - symin0) symax1 = symax0 + factor * (symax0 - symax) new_ybound = y_trf.inverted().transform([symin1, symax1]) return (new_xbound, new_ybound) def _set_view_from_bbox(self, bbox, direction='in', mode=None, twinx=False, twiny=False): (new_xbound, new_ybound) = self._prepare_view_from_bbox(bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny) if not twinx and mode != 'y': self.set_xbound(new_xbound) self.set_autoscalex_on(False) if not twiny and mode != 'x': self.set_ybound(new_ybound) self.set_autoscaley_on(False) def start_pan(self, x, y, button): self._pan_start = types.SimpleNamespace(lim=self.viewLim.frozen(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), bbox=self.bbox.frozen(), x=x, y=y) def end_pan(self): del self._pan_start def _get_pan_points(self, button, key, x, y): def format_deltas(key, dx, dy): if key == 'control': if abs(dx) > abs(dy): dy = dx else: dx = dy elif key == 'x': dy = 0 elif key == 'y': dx = 0 elif key == 'shift': if 2 * abs(dx) < abs(dy): dx = 0 elif 2 * abs(dy) < abs(dx): dy = 0 elif abs(dx) > abs(dy): dy = dy / abs(dy) * abs(dx) else: dx = dx / abs(dx) * abs(dy) return (dx, dy) p = self._pan_start dx = x - p.x dy = y - p.y if dx == dy == 0: return if button == 1: (dx, dy) = format_deltas(key, dx, dy) result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse) elif button == 3: try: dx = -dx / self.bbox.width dy = -dy / self.bbox.height (dx, dy) = format_deltas(key, dx, dy) if self.get_aspect() != 'auto': dx = dy = 0.5 * (dx + dy) alpha = np.power(10.0, (dx, dy)) start = np.array([p.x, p.y]) oldpoints = p.lim.transformed(p.trans) newpoints = start + alpha * (oldpoints - start) result = mtransforms.Bbox(newpoints).transformed(p.trans_inverse) except OverflowError: _api.warn_external('Overflow while panning') return else: return valid = np.isfinite(result.transformed(p.trans)) points = result.get_points().astype(object) points[~valid] = None return points def drag_pan(self, button, key, x, y): points = self._get_pan_points(button, key, x, y) if points is not None: self.set_xlim(points[:, 0]) self.set_ylim(points[:, 1]) def get_children(self): return [*self._children, *self.spines.values(), *self._axis_map.values(), self.title, self._left_title, self._right_title, *self.child_axes, *([self.legend_] if self.legend_ is not None else []), self.patch] def contains(self, mouseevent): return self.patch.contains(mouseevent) def contains_point(self, point): return self.patch.contains_point(point, radius=1.0) def get_default_bbox_extra_artists(self): artists = self.get_children() for axis in self._axis_map.values(): artists.remove(axis) if not (self.axison and self._frameon): for spine in self.spines.values(): artists.remove(spine) artists.remove(self.title) artists.remove(self._left_title) artists.remove(self._right_title) noclip = (_AxesBase, maxis.Axis, offsetbox.AnnotationBbox, offsetbox.OffsetBox) return [a for a in artists if a.get_visible() and a.get_in_layout() and (isinstance(a, noclip) or not a._fully_clipped_to_axes())] def get_tightbbox(self, renderer=None, *, call_axes_locator=True, bbox_extra_artists=None, for_layout_only=False): bb = [] if renderer is None: renderer = self.get_figure(root=True)._get_renderer() if not self.get_visible(): return None locator = self.get_axes_locator() self.apply_aspect(locator(self, renderer) if locator and call_axes_locator else None) for axis in self._axis_map.values(): if self.axison and axis.get_visible(): ba = martist._get_tightbbox_for_layout_only(axis, renderer) if ba: bb.append(ba) self._update_title_position(renderer) axbbox = self.get_window_extent(renderer) bb.append(axbbox) for title in [self.title, self._left_title, self._right_title]: if title.get_visible(): bt = title.get_window_extent(renderer) if for_layout_only and bt.width > 0: bt.x0 = (bt.x0 + bt.x1) / 2 - 0.5 bt.x1 = bt.x0 + 1.0 bb.append(bt) bbox_artists = bbox_extra_artists if bbox_artists is None: bbox_artists = self.get_default_bbox_extra_artists() for a in bbox_artists: bbox = a.get_tightbbox(renderer) if bbox is not None and 0 < bbox.width < np.inf and (0 < bbox.height < np.inf): bb.append(bbox) return mtransforms.Bbox.union([b for b in bb if b.width != 0 or b.height != 0]) def _make_twin_axes(self, *args, **kwargs): if 'sharex' in kwargs and 'sharey' in kwargs: if kwargs['sharex'] is not self and kwargs['sharey'] is not self: raise ValueError('Twinned Axes may share only one axis') ss = self.get_subplotspec() if ss: twin = self.get_figure(root=False).add_subplot(ss, *args, **kwargs) else: twin = self.get_figure(root=False).add_axes(self.get_position(True), *args, **kwargs, axes_locator=_TransformedBoundsLocator([0, 0, 1, 1], self.transAxes)) self.set_adjustable('datalim') twin.set_adjustable('datalim') twin.set_zorder(self.zorder) self._twinned_axes.join(self, twin) return twin def twinx(self): ax2 = self._make_twin_axes(sharex=self) ax2.yaxis.tick_right() ax2.yaxis.set_label_position('right') ax2.yaxis.set_offset_position('right') ax2.set_autoscalex_on(self.get_autoscalex_on()) self.yaxis.tick_left() ax2.xaxis.set_visible(False) ax2.patch.set_visible(False) ax2.xaxis.units = self.xaxis.units return ax2 def twiny(self): ax2 = self._make_twin_axes(sharey=self) ax2.xaxis.tick_top() ax2.xaxis.set_label_position('top') ax2.set_autoscaley_on(self.get_autoscaley_on()) self.xaxis.tick_bottom() ax2.yaxis.set_visible(False) ax2.patch.set_visible(False) ax2.yaxis.units = self.yaxis.units return ax2 def get_shared_x_axes(self): return cbook.GrouperView(self._shared_axes['x']) def get_shared_y_axes(self): return cbook.GrouperView(self._shared_axes['y']) def label_outer(self, remove_inner_ticks=False): self._label_outer_xaxis(skip_non_rectangular_axes=False, remove_inner_ticks=remove_inner_ticks) self._label_outer_yaxis(skip_non_rectangular_axes=False, remove_inner_ticks=remove_inner_ticks) def _label_outer_xaxis(self, *, skip_non_rectangular_axes, remove_inner_ticks=False): if skip_non_rectangular_axes and (not isinstance(self.patch, mpl.patches.Rectangle)): return ss = self.get_subplotspec() if not ss: return label_position = self.xaxis.get_label_position() if not ss.is_first_row(): if label_position == 'top': self.set_xlabel('') top_kw = {'top': False} if remove_inner_ticks else {} self.xaxis.set_tick_params(which='both', labeltop=False, **top_kw) if self.xaxis.offsetText.get_position()[1] == 1: self.xaxis.offsetText.set_visible(False) if not ss.is_last_row(): if label_position == 'bottom': self.set_xlabel('') bottom_kw = {'bottom': False} if remove_inner_ticks else {} self.xaxis.set_tick_params(which='both', labelbottom=False, **bottom_kw) if self.xaxis.offsetText.get_position()[1] == 0: self.xaxis.offsetText.set_visible(False) def _label_outer_yaxis(self, *, skip_non_rectangular_axes, remove_inner_ticks=False): if skip_non_rectangular_axes and (not isinstance(self.patch, mpl.patches.Rectangle)): return ss = self.get_subplotspec() if not ss: return label_position = self.yaxis.get_label_position() if not ss.is_first_col(): if label_position == 'left': self.set_ylabel('') left_kw = {'left': False} if remove_inner_ticks else {} self.yaxis.set_tick_params(which='both', labelleft=False, **left_kw) if self.yaxis.offsetText.get_position()[0] == 0: self.yaxis.offsetText.set_visible(False) if not ss.is_last_col(): if label_position == 'right': self.set_ylabel('') right_kw = {'right': False} if remove_inner_ticks else {} self.yaxis.set_tick_params(which='both', labelright=False, **right_kw) if self.yaxis.offsetText.get_position()[0] == 1: self.yaxis.offsetText.set_visible(False) def set_forward_navigation_events(self, forward): self._forward_navigation_events = forward def get_forward_navigation_events(self): return self._forward_navigation_events def _draw_rasterized(figure, artists, renderer): class _MinimalArtist: def get_rasterized(self): return True def get_agg_filter(self): return None def __init__(self, figure, artists): self.figure = figure self.artists = artists def get_figure(self, root=False): if root: return self.figure.get_figure(root=True) else: return self.figure @martist.allow_rasterization def draw(self, renderer): for a in self.artists: a.draw(renderer) return _MinimalArtist(figure, artists).draw(renderer) # File: matplotlib-main/lib/matplotlib/axes/_secondary_axes.py import numbers import numpy as np from matplotlib import _api, _docstring, transforms import matplotlib.ticker as mticker from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator from matplotlib.axis import Axis from matplotlib.transforms import Transform class SecondaryAxis(_AxesBase): def __init__(self, parent, orientation, location, functions, transform=None, **kwargs): _api.check_in_list(['x', 'y'], orientation=orientation) self._functions = functions self._parent = parent self._orientation = orientation self._ticks_set = False fig = self._parent.get_figure(root=False) if self._orientation == 'x': super().__init__(fig, [0, 1.0, 1, 0.0001], **kwargs) self._axis = self.xaxis self._locstrings = ['top', 'bottom'] self._otherstrings = ['left', 'right'] else: super().__init__(fig, [0, 1.0, 0.0001, 1], **kwargs) self._axis = self.yaxis self._locstrings = ['right', 'left'] self._otherstrings = ['top', 'bottom'] self._parentscale = None self.set_location(location, transform) self.set_functions(functions) otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis otheraxis.set_major_locator(mticker.NullLocator()) otheraxis.set_ticks_position('none') self.spines[self._otherstrings].set_visible(False) self.spines[self._locstrings].set_visible(True) if self._pos < 0.5: self._locstrings = self._locstrings[::-1] self.set_alignment(self._locstrings[0]) def set_alignment(self, align): _api.check_in_list(self._locstrings, align=align) if align == self._locstrings[1]: self._locstrings = self._locstrings[::-1] self.spines[self._locstrings[0]].set_visible(True) self.spines[self._locstrings[1]].set_visible(False) self._axis.set_ticks_position(align) self._axis.set_label_position(align) def set_location(self, location, transform=None): _api.check_isinstance((transforms.Transform, None), transform=transform) if isinstance(location, str): _api.check_in_list(self._locstrings, location=location) self._pos = 1.0 if location in ('top', 'right') else 0.0 elif isinstance(location, numbers.Real): self._pos = location else: raise ValueError(f'location must be {self._locstrings[0]!r}, {self._locstrings[1]!r}, or a float, not {location!r}') self._loc = location if self._orientation == 'x': bounds = [0, self._pos, 1.0, 1e-10] if transform is not None: transform = transforms.blended_transform_factory(self._parent.transAxes, transform) else: bounds = [self._pos, 0, 1e-10, 1] if transform is not None: transform = transforms.blended_transform_factory(transform, self._parent.transAxes) if transform is None: transform = self._parent.transAxes self.set_axes_locator(_TransformedBoundsLocator(bounds, transform)) def apply_aspect(self, position=None): self._set_lims() super().apply_aspect(position) @_docstring.copy(Axis.set_ticks) def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs): ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs) self.stale = True self._ticks_set = True return ret def set_functions(self, functions): if isinstance(functions, tuple) and len(functions) == 2 and callable(functions[0]) and callable(functions[1]): self._functions = functions elif isinstance(functions, Transform): self._functions = (functions.transform, lambda x: functions.inverted().transform(x)) elif functions is None: self._functions = (lambda x: x, lambda x: x) else: raise ValueError('functions argument of secondary Axes must be a two-tuple of callable functions with the first function being the transform and the second being the inverse') self._set_scale() def draw(self, renderer): self._set_lims() self._set_scale() super().draw(renderer) def _set_scale(self): if self._orientation == 'x': pscale = self._parent.xaxis.get_scale() set_scale = self.set_xscale else: pscale = self._parent.yaxis.get_scale() set_scale = self.set_yscale if pscale == self._parentscale: return if self._ticks_set: ticks = self._axis.get_ticklocs() set_scale('functionlog' if pscale == 'log' else 'function', functions=self._functions[::-1]) if self._ticks_set: self._axis.set_major_locator(mticker.FixedLocator(ticks)) self._parentscale = pscale def _set_lims(self): if self._orientation == 'x': lims = self._parent.get_xlim() set_lim = self.set_xlim else: lims = self._parent.get_ylim() set_lim = self.set_ylim order = lims[0] < lims[1] lims = self._functions[0](np.array(lims)) neworder = lims[0] < lims[1] if neworder != order: lims = lims[::-1] set_lim(lims) def set_aspect(self, *args, **kwargs): _api.warn_external("Secondary Axes can't set the aspect ratio") def set_color(self, color): axis = self._axis_map[self._orientation] axis.set_tick_params(colors=color) for spine in self.spines.values(): if spine.axis is axis: spine.set_color(color) axis.label.set_color(color) _secax_docstring = "\nWarnings\n--------\nThis method is experimental as of 3.1, and the API may change.\n\nParameters\n----------\nlocation : {'top', 'bottom', 'left', 'right'} or float\n The position to put the secondary axis. Strings can be 'top' or\n 'bottom' for orientation='x' and 'right' or 'left' for\n orientation='y'. A float indicates the relative position on the\n parent Axes to put the new Axes, 0.0 being the bottom (or left)\n and 1.0 being the top (or right).\n\nfunctions : 2-tuple of func, or Transform with an inverse\n\n If a 2-tuple of functions, the user specifies the transform\n function and its inverse. i.e.\n ``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an\n reciprocal transform with a factor of 2. Both functions must accept\n numpy arrays as input.\n\n The user can also directly supply a subclass of\n `.transforms.Transform` so long as it has an inverse.\n\n See :doc:`/gallery/subplots_axes_and_figures/secondary_axis`\n for examples of making these conversions.\n\ntransform : `.Transform`, optional\n If specified, *location* will be\n placed relative to this transform (in the direction of the axis)\n rather than the parent's axis. i.e. a secondary x-axis will\n use the provided y transform and the x transform of the parent.\n\n .. versionadded:: 3.9\n\nReturns\n-------\nax : axes._secondary_axes.SecondaryAxis\n\nOther Parameters\n----------------\n**kwargs : `~matplotlib.axes.Axes` properties.\n Other miscellaneous Axes parameters.\n" _docstring.interpd.update(_secax_docstring=_secax_docstring) # File: matplotlib-main/lib/matplotlib/axis.py """""" import datetime import functools import logging from numbers import Real import warnings import numpy as np import matplotlib as mpl from matplotlib import _api, cbook import matplotlib.artist as martist import matplotlib.colors as mcolors import matplotlib.lines as mlines import matplotlib.scale as mscale import matplotlib.text as mtext import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms import matplotlib.units as munits _log = logging.getLogger(__name__) GRIDLINE_INTERPOLATION_STEPS = 180 _line_inspector = martist.ArtistInspector(mlines.Line2D) _line_param_names = _line_inspector.get_setters() _line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()] _gridline_param_names = ['grid_' + name for name in _line_param_names + _line_param_aliases] class Tick(martist.Artist): def __init__(self, axes, loc, *, size=None, width=None, color=None, tickdir=None, pad=None, labelsize=None, labelcolor=None, labelfontfamily=None, zorder=None, gridOn=None, tick1On=True, tick2On=True, label1On=True, label2On=False, major=True, labelrotation=0, grid_color=None, grid_linestyle=None, grid_linewidth=None, grid_alpha=None, **kwargs): super().__init__() if gridOn is None: which = mpl.rcParams['axes.grid.which'] if major and which in ('both', 'major'): gridOn = mpl.rcParams['axes.grid'] elif not major and which in ('both', 'minor'): gridOn = mpl.rcParams['axes.grid'] else: gridOn = False self.set_figure(axes.get_figure(root=False)) self.axes = axes self._loc = loc self._major = major name = self.__name__ major_minor = 'major' if major else 'minor' if size is None: size = mpl.rcParams[f'{name}.{major_minor}.size'] self._size = size if width is None: width = mpl.rcParams[f'{name}.{major_minor}.width'] self._width = width if color is None: color = mpl.rcParams[f'{name}.color'] if pad is None: pad = mpl.rcParams[f'{name}.{major_minor}.pad'] self._base_pad = pad if labelcolor is None: labelcolor = mpl.rcParams[f'{name}.labelcolor'] if cbook._str_equal(labelcolor, 'inherit'): labelcolor = mpl.rcParams[f'{name}.color'] if labelsize is None: labelsize = mpl.rcParams[f'{name}.labelsize'] self._set_labelrotation(labelrotation) if zorder is None: if major: zorder = mlines.Line2D.zorder + 0.01 else: zorder = mlines.Line2D.zorder self._zorder = zorder grid_color = mpl._val_or_rc(grid_color, 'grid.color') grid_linestyle = mpl._val_or_rc(grid_linestyle, 'grid.linestyle') grid_linewidth = mpl._val_or_rc(grid_linewidth, 'grid.linewidth') if grid_alpha is None and (not mcolors._has_alpha_channel(grid_color)): grid_alpha = mpl.rcParams['grid.alpha'] grid_kw = {k[5:]: v for (k, v) in kwargs.items()} self.tick1line = mlines.Line2D([], [], color=color, linestyle='none', zorder=zorder, visible=tick1On, markeredgecolor=color, markersize=size, markeredgewidth=width) self.tick2line = mlines.Line2D([], [], color=color, linestyle='none', zorder=zorder, visible=tick2On, markeredgecolor=color, markersize=size, markeredgewidth=width) self.gridline = mlines.Line2D([], [], color=grid_color, alpha=grid_alpha, visible=gridOn, linestyle=grid_linestyle, linewidth=grid_linewidth, marker='', **grid_kw) self.gridline.get_path()._interpolation_steps = GRIDLINE_INTERPOLATION_STEPS self.label1 = mtext.Text(np.nan, np.nan, fontsize=labelsize, color=labelcolor, visible=label1On, fontfamily=labelfontfamily, rotation=self._labelrotation[1]) self.label2 = mtext.Text(np.nan, np.nan, fontsize=labelsize, color=labelcolor, visible=label2On, fontfamily=labelfontfamily, rotation=self._labelrotation[1]) self._apply_tickdir(tickdir) for artist in [self.tick1line, self.tick2line, self.gridline, self.label1, self.label2]: self._set_artist_props(artist) self.update_position(loc) def _set_labelrotation(self, labelrotation): if isinstance(labelrotation, str): mode = labelrotation angle = 0 elif isinstance(labelrotation, (tuple, list)): (mode, angle) = labelrotation else: mode = 'default' angle = labelrotation _api.check_in_list(['auto', 'default'], labelrotation=mode) self._labelrotation = (mode, angle) @property def _pad(self): return self._base_pad + self.get_tick_padding() def _apply_tickdir(self, tickdir): if tickdir is None: tickdir = mpl.rcParams[f'{self.__name__}.direction'] else: _api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir) self._tickdir = tickdir def get_tickdir(self): return self._tickdir def get_tick_padding(self): padding = {'in': 0.0, 'inout': 0.5, 'out': 1.0} return self._size * padding[self._tickdir] def get_children(self): children = [self.tick1line, self.tick2line, self.gridline, self.label1, self.label2] return children def set_clip_path(self, path, transform=None): super().set_clip_path(path, transform) self.gridline.set_clip_path(path, transform) self.stale = True def contains(self, mouseevent): return (False, {}) def set_pad(self, val): self._apply_params(pad=val) self.stale = True def get_pad(self): return self._base_pad def get_loc(self): return self._loc @martist.allow_rasterization def draw(self, renderer): if not self.get_visible(): self.stale = False return renderer.open_group(self.__name__, gid=self.get_gid()) for artist in [self.gridline, self.tick1line, self.tick2line, self.label1, self.label2]: artist.draw(renderer) renderer.close_group(self.__name__) self.stale = False def set_url(self, url): super().set_url(url) self.label1.set_url(url) self.label2.set_url(url) self.stale = True def _set_artist_props(self, a): a.set_figure(self.get_figure(root=False)) def get_view_interval(self): raise NotImplementedError('Derived must override') def _apply_params(self, **kwargs): for (name, target) in [('gridOn', self.gridline), ('tick1On', self.tick1line), ('tick2On', self.tick2line), ('label1On', self.label1), ('label2On', self.label2)]: if name in kwargs: target.set_visible(kwargs.pop(name)) if any((k in kwargs for k in ['size', 'width', 'pad', 'tickdir'])): self._size = kwargs.pop('size', self._size) self._width = kwargs.pop('width', self._width) self._base_pad = kwargs.pop('pad', self._base_pad) self._apply_tickdir(kwargs.pop('tickdir', self._tickdir)) for line in (self.tick1line, self.tick2line): line.set_markersize(self._size) line.set_markeredgewidth(self._width) trans = self._get_text1_transform()[0] self.label1.set_transform(trans) trans = self._get_text2_transform()[0] self.label2.set_transform(trans) tick_kw = {k: v for (k, v) in kwargs.items() if k in ['color', 'zorder']} if 'color' in kwargs: tick_kw['markeredgecolor'] = kwargs['color'] self.tick1line.set(**tick_kw) self.tick2line.set(**tick_kw) for (k, v) in tick_kw.items(): setattr(self, '_' + k, v) if 'labelrotation' in kwargs: self._set_labelrotation(kwargs.pop('labelrotation')) self.label1.set(rotation=self._labelrotation[1]) self.label2.set(rotation=self._labelrotation[1]) label_kw = {k[5:]: v for (k, v) in kwargs.items() if k in ['labelsize', 'labelcolor', 'labelfontfamily']} self.label1.set(**label_kw) self.label2.set(**label_kw) grid_kw = {k[5:]: v for (k, v) in kwargs.items() if k in _gridline_param_names} self.gridline.set(**grid_kw) def update_position(self, loc): raise NotImplementedError('Derived must override') def _get_text1_transform(self): raise NotImplementedError('Derived must override') def _get_text2_transform(self): raise NotImplementedError('Derived must override') class XTick(Tick): __name__ = 'xtick' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ax = self.axes self.tick1line.set(data=([0], [0]), transform=ax.get_xaxis_transform('tick1')) self.tick2line.set(data=([0], [1]), transform=ax.get_xaxis_transform('tick2')) self.gridline.set(data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform('grid')) (trans, va, ha) = self._get_text1_transform() self.label1.set(x=0, y=0, verticalalignment=va, horizontalalignment=ha, transform=trans) (trans, va, ha) = self._get_text2_transform() self.label2.set(x=0, y=1, verticalalignment=va, horizontalalignment=ha, transform=trans) def _get_text1_transform(self): return self.axes.get_xaxis_text1_transform(self._pad) def _get_text2_transform(self): return self.axes.get_xaxis_text2_transform(self._pad) def _apply_tickdir(self, tickdir): super()._apply_tickdir(tickdir) (mark1, mark2) = {'out': (mlines.TICKDOWN, mlines.TICKUP), 'in': (mlines.TICKUP, mlines.TICKDOWN), 'inout': ('|', '|')}[self._tickdir] self.tick1line.set_marker(mark1) self.tick2line.set_marker(mark2) def update_position(self, loc): self.tick1line.set_xdata((loc,)) self.tick2line.set_xdata((loc,)) self.gridline.set_xdata((loc,)) self.label1.set_x(loc) self.label2.set_x(loc) self._loc = loc self.stale = True def get_view_interval(self): return self.axes.viewLim.intervalx class YTick(Tick): __name__ = 'ytick' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ax = self.axes self.tick1line.set(data=([0], [0]), transform=ax.get_yaxis_transform('tick1')) self.tick2line.set(data=([1], [0]), transform=ax.get_yaxis_transform('tick2')) self.gridline.set(data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform('grid')) (trans, va, ha) = self._get_text1_transform() self.label1.set(x=0, y=0, verticalalignment=va, horizontalalignment=ha, transform=trans) (trans, va, ha) = self._get_text2_transform() self.label2.set(x=1, y=0, verticalalignment=va, horizontalalignment=ha, transform=trans) def _get_text1_transform(self): return self.axes.get_yaxis_text1_transform(self._pad) def _get_text2_transform(self): return self.axes.get_yaxis_text2_transform(self._pad) def _apply_tickdir(self, tickdir): super()._apply_tickdir(tickdir) (mark1, mark2) = {'out': (mlines.TICKLEFT, mlines.TICKRIGHT), 'in': (mlines.TICKRIGHT, mlines.TICKLEFT), 'inout': ('_', '_')}[self._tickdir] self.tick1line.set_marker(mark1) self.tick2line.set_marker(mark2) def update_position(self, loc): self.tick1line.set_ydata((loc,)) self.tick2line.set_ydata((loc,)) self.gridline.set_ydata((loc,)) self.label1.set_y(loc) self.label2.set_y(loc) self._loc = loc self.stale = True def get_view_interval(self): return self.axes.viewLim.intervaly class Ticker: def __init__(self): self._locator = None self._formatter = None self._locator_is_default = True self._formatter_is_default = True @property def locator(self): return self._locator @locator.setter def locator(self, locator): if not isinstance(locator, mticker.Locator): raise TypeError('locator must be a subclass of matplotlib.ticker.Locator') self._locator = locator @property def formatter(self): return self._formatter @formatter.setter def formatter(self, formatter): if not isinstance(formatter, mticker.Formatter): raise TypeError('formatter must be a subclass of matplotlib.ticker.Formatter') self._formatter = formatter class _LazyTickList: def __init__(self, major): self._major = major def __get__(self, instance, owner): if instance is None: return self elif self._major: instance.majorTicks = [] tick = instance._get_tick(major=True) instance.majorTicks.append(tick) return instance.majorTicks else: instance.minorTicks = [] tick = instance._get_tick(major=False) instance.minorTicks.append(tick) return instance.minorTicks class Axis(martist.Artist): OFFSETTEXTPAD = 3 _tick_class = None def __str__(self): return '{}({},{})'.format(type(self).__name__, *self.axes.transAxes.transform((0, 0))) def __init__(self, axes, *, pickradius=15, clear=True): super().__init__() self._remove_overlapping_locs = True self.set_figure(axes.get_figure(root=False)) self.isDefault_label = True self.axes = axes self.major = Ticker() self.minor = Ticker() self.callbacks = cbook.CallbackRegistry(signals=['units']) self._autolabelpos = True self.label = mtext.Text(np.nan, np.nan, fontsize=mpl.rcParams['axes.labelsize'], fontweight=mpl.rcParams['axes.labelweight'], color=mpl.rcParams['axes.labelcolor']) self._set_artist_props(self.label) self.offsetText = mtext.Text(np.nan, np.nan) self._set_artist_props(self.offsetText) self.labelpad = mpl.rcParams['axes.labelpad'] self.pickradius = pickradius self._major_tick_kw = dict() self._minor_tick_kw = dict() if clear: self.clear() else: self.converter = None self.units = None self._autoscale_on = True @property def isDefault_majloc(self): return self.major._locator_is_default @isDefault_majloc.setter def isDefault_majloc(self, value): self.major._locator_is_default = value @property def isDefault_majfmt(self): return self.major._formatter_is_default @isDefault_majfmt.setter def isDefault_majfmt(self, value): self.major._formatter_is_default = value @property def isDefault_minloc(self): return self.minor._locator_is_default @isDefault_minloc.setter def isDefault_minloc(self, value): self.minor._locator_is_default = value @property def isDefault_minfmt(self): return self.minor._formatter_is_default @isDefault_minfmt.setter def isDefault_minfmt(self, value): self.minor._formatter_is_default = value def _get_shared_axes(self): return self.axes._shared_axes[self._get_axis_name()].get_siblings(self.axes) def _get_shared_axis(self): name = self._get_axis_name() return [ax._axis_map[name] for ax in self._get_shared_axes()] def _get_axis_name(self): return next((name for (name, axis) in self.axes._axis_map.items() if axis is self)) majorTicks = _LazyTickList(major=True) minorTicks = _LazyTickList(major=False) def get_remove_overlapping_locs(self): return self._remove_overlapping_locs def set_remove_overlapping_locs(self, val): self._remove_overlapping_locs = bool(val) remove_overlapping_locs = property(get_remove_overlapping_locs, set_remove_overlapping_locs, doc='If minor ticker locations that overlap with major ticker locations should be trimmed.') def set_label_coords(self, x, y, transform=None): self._autolabelpos = False if transform is None: transform = self.axes.transAxes self.label.set_transform(transform) self.label.set_position((x, y)) self.stale = True def get_transform(self): return self._scale.get_transform() def get_scale(self): return self._scale.name def _set_scale(self, value, **kwargs): if not isinstance(value, mscale.ScaleBase): self._scale = mscale.scale_factory(value, self, **kwargs) else: self._scale = value self._scale.set_default_locators_and_formatters(self) self.isDefault_majloc = True self.isDefault_minloc = True self.isDefault_majfmt = True self.isDefault_minfmt = True def _set_axes_scale(self, value, **kwargs): name = self._get_axis_name() old_default_lims = self.get_major_locator().nonsingular(-np.inf, np.inf) for ax in self._get_shared_axes(): ax._axis_map[name]._set_scale(value, **kwargs) ax._update_transScale() ax.stale = True new_default_lims = self.get_major_locator().nonsingular(-np.inf, np.inf) if old_default_lims != new_default_lims: self.axes.autoscale_view(**{f'scale{k}': k == name for k in self.axes._axis_names}) def limit_range_for_scale(self, vmin, vmax): return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos()) def _get_autoscale_on(self): return self._autoscale_on def _set_autoscale_on(self, b): if b is not None: self._autoscale_on = b def get_children(self): return [self.label, self.offsetText, *self.get_major_ticks(), *self.get_minor_ticks()] def _reset_major_tick_kw(self): self._major_tick_kw.clear() self._major_tick_kw['gridOn'] = mpl.rcParams['axes.grid'] and mpl.rcParams['axes.grid.which'] in ('both', 'major') def _reset_minor_tick_kw(self): self._minor_tick_kw.clear() self._minor_tick_kw['gridOn'] = mpl.rcParams['axes.grid'] and mpl.rcParams['axes.grid.which'] in ('both', 'minor') def clear(self): self.label._reset_visual_defaults() self.label.set_color(mpl.rcParams['axes.labelcolor']) self.label.set_fontsize(mpl.rcParams['axes.labelsize']) self.label.set_fontweight(mpl.rcParams['axes.labelweight']) self.offsetText._reset_visual_defaults() self.labelpad = mpl.rcParams['axes.labelpad'] self._init() self._set_scale('linear') self.callbacks = cbook.CallbackRegistry(signals=['units']) self._major_tick_kw['gridOn'] = mpl.rcParams['axes.grid'] and mpl.rcParams['axes.grid.which'] in ('both', 'major') self._minor_tick_kw['gridOn'] = mpl.rcParams['axes.grid'] and mpl.rcParams['axes.grid.which'] in ('both', 'minor') self.reset_ticks() self.converter = None self.units = None self.stale = True def reset_ticks(self): try: del self.majorTicks except AttributeError: pass try: del self.minorTicks except AttributeError: pass try: self.set_clip_path(self.axes.patch) except AttributeError: pass def minorticks_on(self): scale = self.get_scale() if scale == 'log': s = self._scale self.set_minor_locator(mticker.LogLocator(s.base, s.subs)) elif scale == 'symlog': s = self._scale self.set_minor_locator(mticker.SymmetricalLogLocator(s._transform, s.subs)) elif scale == 'asinh': s = self._scale self.set_minor_locator(mticker.AsinhLocator(s.linear_width, base=s._base, subs=s._subs)) elif scale == 'logit': self.set_minor_locator(mticker.LogitLocator(minor=True)) else: self.set_minor_locator(mticker.AutoMinorLocator()) def minorticks_off(self): self.set_minor_locator(mticker.NullLocator()) def set_tick_params(self, which='major', reset=False, **kwargs): _api.check_in_list(['major', 'minor', 'both'], which=which) kwtrans = self._translate_tick_params(kwargs) if reset: if which in ['major', 'both']: self._reset_major_tick_kw() self._major_tick_kw.update(kwtrans) if which in ['minor', 'both']: self._reset_minor_tick_kw() self._minor_tick_kw.update(kwtrans) self.reset_ticks() else: if which in ['major', 'both']: self._major_tick_kw.update(kwtrans) for tick in self.majorTicks: tick._apply_params(**kwtrans) if which in ['minor', 'both']: self._minor_tick_kw.update(kwtrans) for tick in self.minorTicks: tick._apply_params(**kwtrans) if 'label1On' in kwtrans or 'label2On' in kwtrans: self.offsetText.set_visible(self._major_tick_kw.get('label1On', False) or self._major_tick_kw.get('label2On', False)) if 'labelcolor' in kwtrans: self.offsetText.set_color(kwtrans['labelcolor']) self.stale = True def get_tick_params(self, which='major'): _api.check_in_list(['major', 'minor'], which=which) if which == 'major': return self._translate_tick_params(self._major_tick_kw, reverse=True) return self._translate_tick_params(self._minor_tick_kw, reverse=True) @staticmethod def _translate_tick_params(kw, reverse=False): kw_ = {**kw} allowed_keys = ['size', 'width', 'color', 'tickdir', 'pad', 'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn', 'tick1On', 'tick2On', 'label1On', 'label2On', 'length', 'direction', 'left', 'bottom', 'right', 'top', 'labelleft', 'labelbottom', 'labelright', 'labeltop', 'labelrotation', *_gridline_param_names] keymap = {'length': 'size', 'direction': 'tickdir', 'rotation': 'labelrotation', 'left': 'tick1On', 'bottom': 'tick1On', 'right': 'tick2On', 'top': 'tick2On', 'labelleft': 'label1On', 'labelbottom': 'label1On', 'labelright': 'label2On', 'labeltop': 'label2On'} if reverse: kwtrans = {oldkey: kw_.pop(newkey) for (oldkey, newkey) in keymap.items() if newkey in kw_} else: kwtrans = {newkey: kw_.pop(oldkey) for (oldkey, newkey) in keymap.items() if oldkey in kw_} if 'colors' in kw_: c = kw_.pop('colors') kwtrans['color'] = c kwtrans['labelcolor'] = c for key in kw_: if key not in allowed_keys: raise ValueError('keyword %s is not recognized; valid keywords are %s' % (key, allowed_keys)) kwtrans.update(kw_) return kwtrans def set_clip_path(self, path, transform=None): super().set_clip_path(path, transform) for child in self.majorTicks + self.minorTicks: child.set_clip_path(path, transform) self.stale = True def get_view_interval(self): raise NotImplementedError('Derived must override') def set_view_interval(self, vmin, vmax, ignore=False): raise NotImplementedError('Derived must override') def get_data_interval(self): raise NotImplementedError('Derived must override') def set_data_interval(self, vmin, vmax, ignore=False): raise NotImplementedError('Derived must override') def get_inverted(self): (low, high) = self.get_view_interval() return high < low def set_inverted(self, inverted): (a, b) = self.get_view_interval() self._set_lim(*sorted((a, b), reverse=bool(inverted)), auto=None) def set_default_intervals(self): def _set_lim(self, v0, v1, *, emit=True, auto): name = self._get_axis_name() self.axes._process_unit_info([(name, (v0, v1))], convert=False) v0 = self.axes._validate_converted_limits(v0, self.convert_units) v1 = self.axes._validate_converted_limits(v1, self.convert_units) if v0 is None or v1 is None: (old0, old1) = self.get_view_interval() if v0 is None: v0 = old0 if v1 is None: v1 = old1 if self.get_scale() == 'log' and (v0 <= 0 or v1 <= 0): (old0, old1) = self.get_view_interval() if v0 <= 0: _api.warn_external(f'Attempt to set non-positive {name}lim on a log-scaled axis will be ignored.') v0 = old0 if v1 <= 0: _api.warn_external(f'Attempt to set non-positive {name}lim on a log-scaled axis will be ignored.') v1 = old1 if v0 == v1: _api.warn_external(f'Attempting to set identical low and high {name}lims makes transformation singular; automatically expanding.') reverse = bool(v0 > v1) (v0, v1) = self.get_major_locator().nonsingular(v0, v1) (v0, v1) = self.limit_range_for_scale(v0, v1) (v0, v1) = sorted([v0, v1], reverse=bool(reverse)) self.set_view_interval(v0, v1, ignore=True) for ax in self._get_shared_axes(): ax._stale_viewlims[name] = False self._set_autoscale_on(auto) if emit: self.axes.callbacks.process(f'{name}lim_changed', self.axes) for other in self._get_shared_axes(): if other is self.axes: continue other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto) if emit: other.callbacks.process(f'{name}lim_changed', other) if (other_fig := other.get_figure(root=False)) != self.get_figure(root=False): other_fig.canvas.draw_idle() self.stale = True return (v0, v1) def _set_artist_props(self, a): if a is None: return a.set_figure(self.get_figure(root=False)) def _update_ticks(self): major_locs = self.get_majorticklocs() major_labels = self.major.formatter.format_ticks(major_locs) major_ticks = self.get_major_ticks(len(major_locs)) for (tick, loc, label) in zip(major_ticks, major_locs, major_labels): tick.update_position(loc) tick.label1.set_text(label) tick.label2.set_text(label) minor_locs = self.get_minorticklocs() minor_labels = self.minor.formatter.format_ticks(minor_locs) minor_ticks = self.get_minor_ticks(len(minor_locs)) for (tick, loc, label) in zip(minor_ticks, minor_locs, minor_labels): tick.update_position(loc) tick.label1.set_text(label) tick.label2.set_text(label) ticks = [*major_ticks, *minor_ticks] (view_low, view_high) = self.get_view_interval() if view_low > view_high: (view_low, view_high) = (view_high, view_low) if hasattr(self, 'axes') and self.axes.name == '3d' and mpl.rcParams['axes3d.automargin']: margin = 0.019965277777777776 delta = view_high - view_low view_high = view_high - delta * margin view_low = view_low + delta * margin interval_t = self.get_transform().transform([view_low, view_high]) ticks_to_draw = [] for tick in ticks: try: loc_t = self.get_transform().transform(tick.get_loc()) except AssertionError: pass else: if mtransforms._interval_contains_close(interval_t, loc_t): ticks_to_draw.append(tick) return ticks_to_draw def _get_ticklabel_bboxes(self, ticks, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() return ([tick.label1.get_window_extent(renderer) for tick in ticks if tick.label1.get_visible()], [tick.label2.get_window_extent(renderer) for tick in ticks if tick.label2.get_visible()]) def get_tightbbox(self, renderer=None, *, for_layout_only=False): if not self.get_visible() or (for_layout_only and (not self.get_in_layout())): return if renderer is None: renderer = self.get_figure(root=True)._get_renderer() ticks_to_draw = self._update_ticks() self._update_label_position(renderer) (tlb1, tlb2) = self._get_ticklabel_bboxes(ticks_to_draw, renderer) self._update_offset_text_position(tlb1, tlb2) self.offsetText.set_text(self.major.formatter.get_offset()) bboxes = [*(a.get_window_extent(renderer) for a in [self.offsetText] if a.get_visible()), *tlb1, *tlb2] if self.label.get_visible(): bb = self.label.get_window_extent(renderer) if for_layout_only: if self.axis_name == 'x' and bb.width > 0: bb.x0 = (bb.x0 + bb.x1) / 2 - 0.5 bb.x1 = bb.x0 + 1.0 if self.axis_name == 'y' and bb.height > 0: bb.y0 = (bb.y0 + bb.y1) / 2 - 0.5 bb.y1 = bb.y0 + 1.0 bboxes.append(bb) bboxes = [b for b in bboxes if 0 < b.width < np.inf and 0 < b.height < np.inf] if bboxes: return mtransforms.Bbox.union(bboxes) else: return None def get_tick_padding(self): values = [] if len(self.majorTicks): values.append(self.majorTicks[0].get_tick_padding()) if len(self.minorTicks): values.append(self.minorTicks[0].get_tick_padding()) return max(values, default=0) @martist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group(__name__, gid=self.get_gid()) ticks_to_draw = self._update_ticks() (tlb1, tlb2) = self._get_ticklabel_bboxes(ticks_to_draw, renderer) for tick in ticks_to_draw: tick.draw(renderer) self._update_label_position(renderer) self.label.draw(renderer) self._update_offset_text_position(tlb1, tlb2) self.offsetText.set_text(self.major.formatter.get_offset()) self.offsetText.draw(renderer) renderer.close_group(__name__) self.stale = False def get_gridlines(self): ticks = self.get_major_ticks() return cbook.silent_list('Line2D gridline', [tick.gridline for tick in ticks]) def get_label(self): return self.label def get_offset_text(self): return self.offsetText def get_pickradius(self): return self._pickradius def get_majorticklabels(self): self._update_ticks() ticks = self.get_major_ticks() labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()] labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()] return labels1 + labels2 def get_minorticklabels(self): self._update_ticks() ticks = self.get_minor_ticks() labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()] labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()] return labels1 + labels2 def get_ticklabels(self, minor=False, which=None): if which is not None: if which == 'minor': return self.get_minorticklabels() elif which == 'major': return self.get_majorticklabels() elif which == 'both': return self.get_majorticklabels() + self.get_minorticklabels() else: _api.check_in_list(['major', 'minor', 'both'], which=which) if minor: return self.get_minorticklabels() return self.get_majorticklabels() def get_majorticklines(self): lines = [] ticks = self.get_major_ticks() for tick in ticks: lines.append(tick.tick1line) lines.append(tick.tick2line) return cbook.silent_list('Line2D ticklines', lines) def get_minorticklines(self): lines = [] ticks = self.get_minor_ticks() for tick in ticks: lines.append(tick.tick1line) lines.append(tick.tick2line) return cbook.silent_list('Line2D ticklines', lines) def get_ticklines(self, minor=False): if minor: return self.get_minorticklines() return self.get_majorticklines() def get_majorticklocs(self): return self.major.locator() def get_minorticklocs(self): minor_locs = np.asarray(self.minor.locator()) if self.remove_overlapping_locs: major_locs = self.major.locator() transform = self._scale.get_transform() tr_minor_locs = transform.transform(minor_locs) tr_major_locs = transform.transform(major_locs) (lo, hi) = sorted(transform.transform(self.get_view_interval())) tol = (hi - lo) * 1e-05 mask = np.isclose(tr_minor_locs[:, None], tr_major_locs[None, :], atol=tol, rtol=0).any(axis=1) minor_locs = minor_locs[~mask] return minor_locs def get_ticklocs(self, *, minor=False): return self.get_minorticklocs() if minor else self.get_majorticklocs() def get_ticks_direction(self, minor=False): if minor: return np.array([tick._tickdir for tick in self.get_minor_ticks()]) else: return np.array([tick._tickdir for tick in self.get_major_ticks()]) def _get_tick(self, major): if self._tick_class is None: raise NotImplementedError(f'The Axis subclass {self.__class__.__name__} must define _tick_class or reimplement _get_tick()') tick_kw = self._major_tick_kw if major else self._minor_tick_kw return self._tick_class(self.axes, 0, major=major, **tick_kw) def _get_tick_label_size(self, axis_name): tick_kw = self._major_tick_kw size = tick_kw.get('labelsize', mpl.rcParams[f'{axis_name}tick.labelsize']) return mtext.FontProperties(size=size).get_size_in_points() def _copy_tick_props(self, src, dest): if src is None or dest is None: return dest.label1.update_from(src.label1) dest.label2.update_from(src.label2) dest.tick1line.update_from(src.tick1line) dest.tick2line.update_from(src.tick2line) dest.gridline.update_from(src.gridline) dest.update_from(src) dest._loc = src._loc dest._size = src._size dest._width = src._width dest._base_pad = src._base_pad dest._labelrotation = src._labelrotation dest._zorder = src._zorder dest._tickdir = src._tickdir def get_label_text(self): return self.label.get_text() def get_major_locator(self): return self.major.locator def get_minor_locator(self): return self.minor.locator def get_major_formatter(self): return self.major.formatter def get_minor_formatter(self): return self.minor.formatter def get_major_ticks(self, numticks=None): if numticks is None: numticks = len(self.get_majorticklocs()) while len(self.majorTicks) < numticks: tick = self._get_tick(major=True) self.majorTicks.append(tick) self._copy_tick_props(self.majorTicks[0], tick) return self.majorTicks[:numticks] def get_minor_ticks(self, numticks=None): if numticks is None: numticks = len(self.get_minorticklocs()) while len(self.minorTicks) < numticks: tick = self._get_tick(major=False) self.minorTicks.append(tick) self._copy_tick_props(self.minorTicks[0], tick) return self.minorTicks[:numticks] def grid(self, visible=None, which='major', **kwargs): if kwargs: if visible is None: visible = True elif not visible: _api.warn_external('First parameter to grid() is false, but line properties are supplied. The grid will be enabled.') visible = True which = which.lower() _api.check_in_list(['major', 'minor', 'both'], which=which) gridkw = {f'grid_{name}': value for (name, value) in kwargs.items()} if which in ['minor', 'both']: gridkw['gridOn'] = not self._minor_tick_kw['gridOn'] if visible is None else visible self.set_tick_params(which='minor', **gridkw) if which in ['major', 'both']: gridkw['gridOn'] = not self._major_tick_kw['gridOn'] if visible is None else visible self.set_tick_params(which='major', **gridkw) self.stale = True def update_units(self, data): converter = munits.registry.get_converter(data) if converter is None: return False neednew = self.converter != converter self.converter = converter default = self.converter.default_units(data, self) if default is not None and self.units is None: self.set_units(default) elif neednew: self._update_axisinfo() self.stale = True return True def _update_axisinfo(self): if self.converter is None: return info = self.converter.axisinfo(self.units, self) if info is None: return if info.majloc is not None and self.major.locator != info.majloc and self.isDefault_majloc: self.set_major_locator(info.majloc) self.isDefault_majloc = True if info.minloc is not None and self.minor.locator != info.minloc and self.isDefault_minloc: self.set_minor_locator(info.minloc) self.isDefault_minloc = True if info.majfmt is not None and self.major.formatter != info.majfmt and self.isDefault_majfmt: self.set_major_formatter(info.majfmt) self.isDefault_majfmt = True if info.minfmt is not None and self.minor.formatter != info.minfmt and self.isDefault_minfmt: self.set_minor_formatter(info.minfmt) self.isDefault_minfmt = True if info.label is not None and self.isDefault_label: self.set_label_text(info.label) self.isDefault_label = True self.set_default_intervals() def have_units(self): return self.converter is not None or self.units is not None def convert_units(self, x): if munits._is_natively_supported(x): return x if self.converter is None: self.converter = munits.registry.get_converter(x) if self.converter is None: return x try: ret = self.converter.convert(x, self.units, self) except Exception as e: raise munits.ConversionError(f'Failed to convert value(s) to axis units: {x!r}') from e return ret def set_units(self, u): if u == self.units: return for axis in self._get_shared_axis(): axis.units = u axis._update_axisinfo() axis.callbacks.process('units') axis.stale = True def get_units(self): return self.units def set_label_text(self, label, fontdict=None, **kwargs): self.isDefault_label = False self.label.set_text(label) if fontdict is not None: self.label.update(fontdict) self.label.update(kwargs) self.stale = True return self.label def set_major_formatter(self, formatter): self._set_formatter(formatter, self.major) def set_minor_formatter(self, formatter): self._set_formatter(formatter, self.minor) def _set_formatter(self, formatter, level): if isinstance(formatter, str): formatter = mticker.StrMethodFormatter(formatter) elif callable(formatter) and (not isinstance(formatter, mticker.TickHelper)): formatter = mticker.FuncFormatter(formatter) else: _api.check_isinstance(mticker.Formatter, formatter=formatter) if isinstance(formatter, mticker.FixedFormatter) and len(formatter.seq) > 0 and (not isinstance(level.locator, mticker.FixedLocator)): _api.warn_external('FixedFormatter should only be used together with FixedLocator') if level == self.major: self.isDefault_majfmt = False else: self.isDefault_minfmt = False level.formatter = formatter formatter.set_axis(self) self.stale = True def set_major_locator(self, locator): _api.check_isinstance(mticker.Locator, locator=locator) self.isDefault_majloc = False self.major.locator = locator if self.major.formatter: self.major.formatter._set_locator(locator) locator.set_axis(self) self.stale = True def set_minor_locator(self, locator): _api.check_isinstance(mticker.Locator, locator=locator) self.isDefault_minloc = False self.minor.locator = locator if self.minor.formatter: self.minor.formatter._set_locator(locator) locator.set_axis(self) self.stale = True def set_pickradius(self, pickradius): if not isinstance(pickradius, Real) or pickradius < 0: raise ValueError('pick radius should be a distance') self._pickradius = pickradius pickradius = property(get_pickradius, set_pickradius, doc='The acceptance radius for containment tests. See also `.Axis.contains`.') @staticmethod def _format_with_dict(tickd, x, pos): return tickd.get(x, '') def set_ticklabels(self, labels, *, minor=False, fontdict=None, **kwargs): try: labels = [t.get_text() if hasattr(t, 'get_text') else t for t in labels] except TypeError: raise TypeError(f'{labels:=} must be a sequence') from None locator = self.get_minor_locator() if minor else self.get_major_locator() if not labels: formatter = mticker.NullFormatter() elif isinstance(locator, mticker.FixedLocator): if len(locator.locs) != len(labels) and len(labels) != 0: raise ValueError(f'The number of FixedLocator locations ({len(locator.locs)}), usually from a call to set_ticks, does not match the number of labels ({len(labels)}).') tickd = {loc: lab for (loc, lab) in zip(locator.locs, labels)} func = functools.partial(self._format_with_dict, tickd) formatter = mticker.FuncFormatter(func) else: _api.warn_external('set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.') formatter = mticker.FixedFormatter(labels) with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='FixedFormatter should only be used together with FixedLocator') if minor: self.set_minor_formatter(formatter) locs = self.get_minorticklocs() ticks = self.get_minor_ticks(len(locs)) else: self.set_major_formatter(formatter) locs = self.get_majorticklocs() ticks = self.get_major_ticks(len(locs)) ret = [] if fontdict is not None: kwargs.update(fontdict) for (pos, (loc, tick)) in enumerate(zip(locs, ticks)): tick.update_position(loc) tick_label = formatter(loc, pos) tick.label1.set_text(tick_label) tick.label1._internal_update(kwargs) tick.label2.set_text(tick_label) tick.label2._internal_update(kwargs) if tick.label1.get_visible(): ret.append(tick.label1) if tick.label2.get_visible(): ret.append(tick.label2) self.stale = True return ret def _set_tick_locations(self, ticks, *, minor=False): ticks = self.convert_units(ticks) locator = mticker.FixedLocator(ticks) if len(ticks): for axis in self._get_shared_axis(): axis.set_view_interval(min(ticks), max(ticks)) self.axes.stale = True if minor: self.set_minor_locator(locator) return self.get_minor_ticks(len(ticks)) else: self.set_major_locator(locator) return self.get_major_ticks(len(ticks)) def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs): if labels is None and kwargs: first_key = next(iter(kwargs)) raise ValueError(f"Incorrect use of keyword argument {first_key!r}. Keyword arguments other than 'minor' modify the text labels and can only be used if 'labels' are passed as well.") result = self._set_tick_locations(ticks, minor=minor) if labels is not None: self.set_ticklabels(labels, minor=minor, **kwargs) return result def _get_tick_boxes_siblings(self, renderer): name = self._get_axis_name() if name not in self.get_figure(root=False)._align_label_groups: return ([], []) grouper = self.get_figure(root=False)._align_label_groups[name] bboxes = [] bboxes2 = [] for ax in grouper.get_siblings(self.axes): axis = ax._axis_map[name] ticks_to_draw = axis._update_ticks() (tlb, tlb2) = axis._get_ticklabel_bboxes(ticks_to_draw, renderer) bboxes.extend(tlb) bboxes2.extend(tlb2) return (bboxes, bboxes2) def _update_label_position(self, renderer): raise NotImplementedError('Derived must override') def _update_offset_text_position(self, bboxes, bboxes2): raise NotImplementedError('Derived must override') def axis_date(self, tz=None): if isinstance(tz, str): import dateutil.tz tz = dateutil.tz.gettz(tz) self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz)) def get_tick_space(self): raise NotImplementedError() def _get_ticks_position(self): major = self.majorTicks[0] minor = self.minorTicks[0] if all((tick.tick1line.get_visible() and (not tick.tick2line.get_visible()) and tick.label1.get_visible() and (not tick.label2.get_visible()) for tick in [major, minor])): return 1 elif all((tick.tick2line.get_visible() and (not tick.tick1line.get_visible()) and tick.label2.get_visible() and (not tick.label1.get_visible()) for tick in [major, minor])): return 2 elif all((tick.tick1line.get_visible() and tick.tick2line.get_visible() and tick.label1.get_visible() and (not tick.label2.get_visible()) for tick in [major, minor])): return 'default' else: return 'unknown' def get_label_position(self): return self.label_position def set_label_position(self, position): raise NotImplementedError() def get_minpos(self): raise NotImplementedError() def _make_getset_interval(method_name, lim_name, attr_name): def getter(self): return getattr(getattr(self.axes, lim_name), attr_name) def setter(self, vmin, vmax, ignore=False): if ignore: setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax)) else: (oldmin, oldmax) = getter(self) if oldmin < oldmax: setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), ignore=True) self.stale = True getter.__name__ = f'get_{method_name}_interval' setter.__name__ = f'set_{method_name}_interval' return (getter, setter) class XAxis(Axis): __name__ = 'xaxis' axis_name = 'x' _tick_class = XTick def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._init() def _init(self): self.label.set(x=0.5, y=0, verticalalignment='top', horizontalalignment='center', transform=mtransforms.blended_transform_factory(self.axes.transAxes, mtransforms.IdentityTransform())) self.label_position = 'bottom' if mpl.rcParams['xtick.labelcolor'] == 'inherit': tick_color = mpl.rcParams['xtick.color'] else: tick_color = mpl.rcParams['xtick.labelcolor'] self.offsetText.set(x=1, y=0, verticalalignment='top', horizontalalignment='right', transform=mtransforms.blended_transform_factory(self.axes.transAxes, mtransforms.IdentityTransform()), fontsize=mpl.rcParams['xtick.labelsize'], color=tick_color) self.offset_text_position = 'bottom' def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) (x, y) = (mouseevent.x, mouseevent.y) try: trans = self.axes.transAxes.inverted() (xaxes, yaxes) = trans.transform((x, y)) except ValueError: return (False, {}) ((l, b), (r, t)) = self.axes.transAxes.transform([(0, 0), (1, 1)]) inaxis = 0 <= xaxes <= 1 and (b - self._pickradius < y < b or t < y < t + self._pickradius) return (inaxis, {}) def set_label_position(self, position): self.label.set_verticalalignment(_api.check_getitem({'top': 'baseline', 'bottom': 'top'}, position=position)) self.label_position = position self.stale = True def _update_label_position(self, renderer): if not self._autolabelpos: return (bboxes, bboxes2) = self._get_tick_boxes_siblings(renderer=renderer) (x, y) = self.label.get_position() if self.label_position == 'bottom': bbox = mtransforms.Bbox.union([*bboxes, self.axes.spines.get('bottom', self.axes).get_window_extent()]) self.label.set_position((x, bbox.y0 - self.labelpad * self.get_figure(root=True).dpi / 72)) else: bbox = mtransforms.Bbox.union([*bboxes2, self.axes.spines.get('top', self.axes).get_window_extent()]) self.label.set_position((x, bbox.y1 + self.labelpad * self.get_figure(root=True).dpi / 72)) def _update_offset_text_position(self, bboxes, bboxes2): (x, y) = self.offsetText.get_position() if not hasattr(self, '_tick_position'): self._tick_position = 'bottom' if self._tick_position == 'bottom': if not len(bboxes): bottom = self.axes.bbox.ymin else: bbox = mtransforms.Bbox.union(bboxes) bottom = bbox.y0 y = bottom - self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72 else: if not len(bboxes2): top = self.axes.bbox.ymax else: bbox = mtransforms.Bbox.union(bboxes2) top = bbox.y1 y = top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72 self.offsetText.set_position((x, y)) def set_ticks_position(self, position): if position == 'top': self.set_tick_params(which='both', top=True, labeltop=True, bottom=False, labelbottom=False) self._tick_position = 'top' self.offsetText.set_verticalalignment('bottom') elif position == 'bottom': self.set_tick_params(which='both', top=False, labeltop=False, bottom=True, labelbottom=True) self._tick_position = 'bottom' self.offsetText.set_verticalalignment('top') elif position == 'both': self.set_tick_params(which='both', top=True, bottom=True) elif position == 'none': self.set_tick_params(which='both', top=False, bottom=False) elif position == 'default': self.set_tick_params(which='both', top=True, labeltop=False, bottom=True, labelbottom=True) self._tick_position = 'bottom' self.offsetText.set_verticalalignment('top') else: _api.check_in_list(['top', 'bottom', 'both', 'default', 'none'], position=position) self.stale = True def tick_top(self): label = True if 'label1On' in self._major_tick_kw: label = self._major_tick_kw['label1On'] or self._major_tick_kw['label2On'] self.set_ticks_position('top') self.set_tick_params(which='both', labeltop=label) def tick_bottom(self): label = True if 'label1On' in self._major_tick_kw: label = self._major_tick_kw['label1On'] or self._major_tick_kw['label2On'] self.set_ticks_position('bottom') self.set_tick_params(which='both', labelbottom=label) def get_ticks_position(self): return {1: 'bottom', 2: 'top', 'default': 'default', 'unknown': 'unknown'}[self._get_ticks_position()] (get_view_interval, set_view_interval) = _make_getset_interval('view', 'viewLim', 'intervalx') (get_data_interval, set_data_interval) = _make_getset_interval('data', 'dataLim', 'intervalx') def get_minpos(self): return self.axes.dataLim.minposx def set_default_intervals(self): if not self.axes.dataLim.mutatedx() and (not self.axes.viewLim.mutatedx()): if self.converter is not None: info = self.converter.axisinfo(self.units, self) if info.default_limits is not None: (xmin, xmax) = self.convert_units(info.default_limits) self.axes.viewLim.intervalx = (xmin, xmax) self.stale = True def get_tick_space(self): ends = mtransforms.Bbox.unit().transformed(self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans) length = ends.width * 72 size = self._get_tick_label_size('x') * 3 if size > 0: return int(np.floor(length / size)) else: return 2 ** 31 - 1 class YAxis(Axis): __name__ = 'yaxis' axis_name = 'y' _tick_class = YTick def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._init() def _init(self): self.label.set(x=0, y=0.5, verticalalignment='bottom', horizontalalignment='center', rotation='vertical', rotation_mode='anchor', transform=mtransforms.blended_transform_factory(mtransforms.IdentityTransform(), self.axes.transAxes)) self.label_position = 'left' if mpl.rcParams['ytick.labelcolor'] == 'inherit': tick_color = mpl.rcParams['ytick.color'] else: tick_color = mpl.rcParams['ytick.labelcolor'] self.offsetText.set(x=0, y=0.5, verticalalignment='baseline', horizontalalignment='left', transform=mtransforms.blended_transform_factory(self.axes.transAxes, mtransforms.IdentityTransform()), fontsize=mpl.rcParams['ytick.labelsize'], color=tick_color) self.offset_text_position = 'left' def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) (x, y) = (mouseevent.x, mouseevent.y) try: trans = self.axes.transAxes.inverted() (xaxes, yaxes) = trans.transform((x, y)) except ValueError: return (False, {}) ((l, b), (r, t)) = self.axes.transAxes.transform([(0, 0), (1, 1)]) inaxis = 0 <= yaxes <= 1 and (l - self._pickradius < x < l or r < x < r + self._pickradius) return (inaxis, {}) def set_label_position(self, position): self.label.set_rotation_mode('anchor') self.label.set_verticalalignment(_api.check_getitem({'left': 'bottom', 'right': 'top'}, position=position)) self.label_position = position self.stale = True def _update_label_position(self, renderer): if not self._autolabelpos: return (bboxes, bboxes2) = self._get_tick_boxes_siblings(renderer=renderer) (x, y) = self.label.get_position() if self.label_position == 'left': bbox = mtransforms.Bbox.union([*bboxes, self.axes.spines.get('left', self.axes).get_window_extent()]) self.label.set_position((bbox.x0 - self.labelpad * self.get_figure(root=True).dpi / 72, y)) else: bbox = mtransforms.Bbox.union([*bboxes2, self.axes.spines.get('right', self.axes).get_window_extent()]) self.label.set_position((bbox.x1 + self.labelpad * self.get_figure(root=True).dpi / 72, y)) def _update_offset_text_position(self, bboxes, bboxes2): (x, _) = self.offsetText.get_position() if 'outline' in self.axes.spines: bbox = self.axes.spines['outline'].get_window_extent() else: bbox = self.axes.bbox top = bbox.ymax self.offsetText.set_position((x, top + self.OFFSETTEXTPAD * self.get_figure(root=True).dpi / 72)) def set_offset_position(self, position): (x, y) = self.offsetText.get_position() x = _api.check_getitem({'left': 0, 'right': 1}, position=position) self.offsetText.set_ha(position) self.offsetText.set_position((x, y)) self.stale = True def set_ticks_position(self, position): if position == 'right': self.set_tick_params(which='both', right=True, labelright=True, left=False, labelleft=False) self.set_offset_position(position) elif position == 'left': self.set_tick_params(which='both', right=False, labelright=False, left=True, labelleft=True) self.set_offset_position(position) elif position == 'both': self.set_tick_params(which='both', right=True, left=True) elif position == 'none': self.set_tick_params(which='both', right=False, left=False) elif position == 'default': self.set_tick_params(which='both', right=True, labelright=False, left=True, labelleft=True) else: _api.check_in_list(['left', 'right', 'both', 'default', 'none'], position=position) self.stale = True def tick_right(self): label = True if 'label1On' in self._major_tick_kw: label = self._major_tick_kw['label1On'] or self._major_tick_kw['label2On'] self.set_ticks_position('right') self.set_tick_params(which='both', labelright=label) def tick_left(self): label = True if 'label1On' in self._major_tick_kw: label = self._major_tick_kw['label1On'] or self._major_tick_kw['label2On'] self.set_ticks_position('left') self.set_tick_params(which='both', labelleft=label) def get_ticks_position(self): return {1: 'left', 2: 'right', 'default': 'default', 'unknown': 'unknown'}[self._get_ticks_position()] (get_view_interval, set_view_interval) = _make_getset_interval('view', 'viewLim', 'intervaly') (get_data_interval, set_data_interval) = _make_getset_interval('data', 'dataLim', 'intervaly') def get_minpos(self): return self.axes.dataLim.minposy def set_default_intervals(self): if not self.axes.dataLim.mutatedy() and (not self.axes.viewLim.mutatedy()): if self.converter is not None: info = self.converter.axisinfo(self.units, self) if info.default_limits is not None: (ymin, ymax) = self.convert_units(info.default_limits) self.axes.viewLim.intervaly = (ymin, ymax) self.stale = True def get_tick_space(self): ends = mtransforms.Bbox.unit().transformed(self.axes.transAxes - self.get_figure(root=False).dpi_scale_trans) length = ends.height * 72 size = self._get_tick_label_size('y') * 2 if size > 0: return int(np.floor(length / size)) else: return 2 ** 31 - 1 # File: matplotlib-main/lib/matplotlib/backend_bases.py """""" from collections import namedtuple from contextlib import ExitStack, contextmanager, nullcontext from enum import Enum, IntEnum import functools import importlib import inspect import io import itertools import logging import os import pathlib import signal import socket import sys import time import weakref from weakref import WeakKeyDictionary import numpy as np import matplotlib as mpl from matplotlib import _api, backend_tools as tools, cbook, colors, _docstring, text, _tight_bbox, transforms, widgets, is_interactive, rcParams from matplotlib._pylab_helpers import Gcf from matplotlib.backend_managers import ToolManager from matplotlib.cbook import _setattr_cm from matplotlib.layout_engine import ConstrainedLayoutEngine from matplotlib.path import Path from matplotlib.texmanager import TexManager from matplotlib.transforms import Affine2D from matplotlib._enums import JoinStyle, CapStyle _log = logging.getLogger(__name__) _default_filetypes = {'eps': 'Encapsulated Postscript', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format', 'webp': 'WebP Image Format'} _default_backends = {'eps': 'matplotlib.backends.backend_ps', 'jpg': 'matplotlib.backends.backend_agg', 'jpeg': 'matplotlib.backends.backend_agg', 'pdf': 'matplotlib.backends.backend_pdf', 'pgf': 'matplotlib.backends.backend_pgf', 'png': 'matplotlib.backends.backend_agg', 'ps': 'matplotlib.backends.backend_ps', 'raw': 'matplotlib.backends.backend_agg', 'rgba': 'matplotlib.backends.backend_agg', 'svg': 'matplotlib.backends.backend_svg', 'svgz': 'matplotlib.backends.backend_svg', 'tif': 'matplotlib.backends.backend_agg', 'tiff': 'matplotlib.backends.backend_agg', 'webp': 'matplotlib.backends.backend_agg'} def register_backend(format, backend, description=None): if description is None: description = '' _default_backends[format] = backend _default_filetypes[format] = description def get_registered_canvas_class(format): if format not in _default_backends: return None backend_class = _default_backends[format] if isinstance(backend_class, str): backend_class = importlib.import_module(backend_class).FigureCanvas _default_backends[format] = backend_class return backend_class class RendererBase: def __init__(self): super().__init__() self._texmanager = None self._text2path = text.TextToPath() self._raster_depth = 0 self._rasterizing = False def open_group(self, s, gid=None): def close_group(self, s): def draw_path(self, gc, path, transform, rgbFace=None): raise NotImplementedError def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): for (vertices, codes) in path.iter_segments(trans, simplify=False): if len(vertices): (x, y) = vertices[-2:] self.draw_path(gc, marker_path, marker_trans + transforms.Affine2D().translate(x, y), rgbFace) def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): path_ids = self._iter_collection_raw_paths(master_transform, paths, all_transforms) for (xo, yo, path_id, gc0, rgbFace) in self._iter_collection(gc, list(path_ids), offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): (path, transform) = path_id if xo != 0 or yo != 0: transform = transform.frozen() transform.translate(xo, yo) self.draw_path(gc0, path, transform, rgbFace) def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight, coordinates, offsets, offsetTrans, facecolors, antialiased, edgecolors): from matplotlib.collections import QuadMesh paths = QuadMesh._convert_mesh_to_paths(coordinates) if edgecolors is None: edgecolors = facecolors linewidths = np.array([gc.get_linewidth()], float) return self.draw_path_collection(gc, master_transform, paths, [], offsets, offsetTrans, facecolors, edgecolors, linewidths, [], [antialiased], [None], 'screen') def draw_gouraud_triangles(self, gc, triangles_array, colors_array, transform): raise NotImplementedError def _iter_collection_raw_paths(self, master_transform, paths, all_transforms): Npaths = len(paths) Ntransforms = len(all_transforms) N = max(Npaths, Ntransforms) if Npaths == 0: return transform = transforms.IdentityTransform() for i in range(N): path = paths[i % Npaths] if Ntransforms: transform = Affine2D(all_transforms[i % Ntransforms]) yield (path, transform + master_transform) def _iter_collection_uses_per_path(self, paths, all_transforms, offsets, facecolors, edgecolors): Npaths = len(paths) if Npaths == 0 or len(facecolors) == len(edgecolors) == 0: return 0 Npath_ids = max(Npaths, len(all_transforms)) N = max(Npath_ids, len(offsets)) return (N + Npath_ids - 1) // Npath_ids def _iter_collection(self, gc, path_ids, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): Npaths = len(path_ids) Noffsets = len(offsets) N = max(Npaths, Noffsets) Nfacecolors = len(facecolors) Nedgecolors = len(edgecolors) Nlinewidths = len(linewidths) Nlinestyles = len(linestyles) Nurls = len(urls) if Nfacecolors == 0 and Nedgecolors == 0 or Npaths == 0: return gc0 = self.new_gc() gc0.copy_properties(gc) def cycle_or_default(seq, default=None): return itertools.cycle(seq) if len(seq) else itertools.repeat(default) pathids = cycle_or_default(path_ids) toffsets = cycle_or_default(offset_trans.transform(offsets), (0, 0)) fcs = cycle_or_default(facecolors) ecs = cycle_or_default(edgecolors) lws = cycle_or_default(linewidths) lss = cycle_or_default(linestyles) aas = cycle_or_default(antialiaseds) urls = cycle_or_default(urls) if Nedgecolors == 0: gc0.set_linewidth(0.0) for (pathid, (xo, yo), fc, ec, lw, ls, aa, url) in itertools.islice(zip(pathids, toffsets, fcs, ecs, lws, lss, aas, urls), N): if not (np.isfinite(xo) and np.isfinite(yo)): continue if Nedgecolors: if Nlinewidths: gc0.set_linewidth(lw) if Nlinestyles: gc0.set_dashes(*ls) if len(ec) == 4 and ec[3] == 0.0: gc0.set_linewidth(0) else: gc0.set_foreground(ec) if fc is not None and len(fc) == 4 and (fc[3] == 0): fc = None gc0.set_antialiased(aa) if Nurls: gc0.set_url(url) yield (xo, yo, pathid, gc0, fc) gc0.restore() def get_image_magnification(self): return 1.0 def draw_image(self, gc, x, y, im, transform=None): raise NotImplementedError def option_image_nocomposite(self): return False def option_scale_image(self): return False def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): self._draw_text_as_path(gc, x, y, s, prop, angle, ismath='TeX') def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): self._draw_text_as_path(gc, x, y, s, prop, angle, ismath) def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath): text2path = self._text2path fontsize = self.points_to_pixels(prop.get_size_in_points()) (verts, codes) = text2path.get_text_path(prop, s, ismath=ismath) path = Path(verts, codes) if self.flipy(): (width, height) = self.get_canvas_width_height() transform = Affine2D().scale(fontsize / text2path.FONT_SCALE).rotate_deg(angle).translate(x, height - y) else: transform = Affine2D().scale(fontsize / text2path.FONT_SCALE).rotate_deg(angle).translate(x, y) color = gc.get_rgb() gc.set_linewidth(0.0) self.draw_path(gc, path, transform, rgbFace=color) def get_text_width_height_descent(self, s, prop, ismath): fontsize = prop.get_size_in_points() if ismath == 'TeX': return self.get_texmanager().get_text_width_height_descent(s, fontsize, renderer=self) dpi = self.points_to_pixels(72) if ismath: dims = self._text2path.mathtext_parser.parse(s, dpi, prop) return dims[0:3] flags = self._text2path._get_hinting_flag() font = self._text2path._get_font(prop) font.set_size(fontsize, dpi) font.set_text(s, 0.0, flags=flags) (w, h) = font.get_width_height() d = font.get_descent() w /= 64.0 h /= 64.0 d /= 64.0 return (w, h, d) def flipy(self): return True def get_canvas_width_height(self): return (1, 1) def get_texmanager(self): if self._texmanager is None: self._texmanager = TexManager() return self._texmanager def new_gc(self): return GraphicsContextBase() def points_to_pixels(self, points): return points def start_rasterizing(self): def stop_rasterizing(self): def start_filter(self): def stop_filter(self, filter_func): def _draw_disabled(self): no_ops = {meth_name: lambda *args, **kwargs: None for meth_name in dir(RendererBase) if meth_name.startswith('draw_') or meth_name in ['open_group', 'close_group']} return _setattr_cm(self, **no_ops) class GraphicsContextBase: def __init__(self): self._alpha = 1.0 self._forced_alpha = False self._antialiased = 1 self._capstyle = CapStyle('butt') self._cliprect = None self._clippath = None self._dashes = (0, None) self._joinstyle = JoinStyle('round') self._linestyle = 'solid' self._linewidth = 1 self._rgb = (0.0, 0.0, 0.0, 1.0) self._hatch = None self._hatch_color = colors.to_rgba(rcParams['hatch.color']) self._hatch_linewidth = rcParams['hatch.linewidth'] self._url = None self._gid = None self._snap = None self._sketch = None def copy_properties(self, gc): self._alpha = gc._alpha self._forced_alpha = gc._forced_alpha self._antialiased = gc._antialiased self._capstyle = gc._capstyle self._cliprect = gc._cliprect self._clippath = gc._clippath self._dashes = gc._dashes self._joinstyle = gc._joinstyle self._linestyle = gc._linestyle self._linewidth = gc._linewidth self._rgb = gc._rgb self._hatch = gc._hatch self._hatch_color = gc._hatch_color self._hatch_linewidth = gc._hatch_linewidth self._url = gc._url self._gid = gc._gid self._snap = gc._snap self._sketch = gc._sketch def restore(self): def get_alpha(self): return self._alpha def get_antialiased(self): return self._antialiased def get_capstyle(self): return self._capstyle.name def get_clip_rectangle(self): return self._cliprect def get_clip_path(self): if self._clippath is not None: (tpath, tr) = self._clippath.get_transformed_path_and_affine() if np.all(np.isfinite(tpath.vertices)): return (tpath, tr) else: _log.warning('Ill-defined clip_path detected. Returning None.') return (None, None) return (None, None) def get_dashes(self): return self._dashes def get_forced_alpha(self): return self._forced_alpha def get_joinstyle(self): return self._joinstyle.name def get_linewidth(self): return self._linewidth def get_rgb(self): return self._rgb def get_url(self): return self._url def get_gid(self): return self._gid def get_snap(self): return self._snap def set_alpha(self, alpha): if alpha is not None: self._alpha = alpha self._forced_alpha = True else: self._alpha = 1.0 self._forced_alpha = False self.set_foreground(self._rgb, isRGBA=True) def set_antialiased(self, b): self._antialiased = int(bool(b)) @_docstring.interpd def set_capstyle(self, cs): self._capstyle = CapStyle(cs) def set_clip_rectangle(self, rectangle): self._cliprect = rectangle def set_clip_path(self, path): _api.check_isinstance((transforms.TransformedPath, None), path=path) self._clippath = path def set_dashes(self, dash_offset, dash_list): if dash_list is not None: dl = np.asarray(dash_list) if np.any(dl < 0.0): raise ValueError('All values in the dash list must be non-negative') if dl.size and (not np.any(dl > 0.0)): raise ValueError('At least one value in the dash list must be positive') self._dashes = (dash_offset, dash_list) def set_foreground(self, fg, isRGBA=False): if self._forced_alpha and isRGBA: self._rgb = fg[:3] + (self._alpha,) elif self._forced_alpha: self._rgb = colors.to_rgba(fg, self._alpha) elif isRGBA: self._rgb = fg else: self._rgb = colors.to_rgba(fg) @_docstring.interpd def set_joinstyle(self, js): self._joinstyle = JoinStyle(js) def set_linewidth(self, w): self._linewidth = float(w) def set_url(self, url): self._url = url def set_gid(self, id): self._gid = id def set_snap(self, snap): self._snap = snap def set_hatch(self, hatch): self._hatch = hatch def get_hatch(self): return self._hatch def get_hatch_path(self, density=6.0): hatch = self.get_hatch() if hatch is None: return None return Path.hatch(hatch, density) def get_hatch_color(self): return self._hatch_color def set_hatch_color(self, hatch_color): self._hatch_color = hatch_color def get_hatch_linewidth(self): return self._hatch_linewidth def get_sketch_params(self): return self._sketch def set_sketch_params(self, scale=None, length=None, randomness=None): self._sketch = None if scale is None else (scale, length or 128.0, randomness or 16.0) class TimerBase: def __init__(self, interval=None, callbacks=None): self.callbacks = [] if callbacks is None else callbacks.copy() self.interval = 1000 if interval is None else interval self.single_shot = False def __del__(self): self._timer_stop() @_api.delete_parameter('3.9', 'interval', alternative='timer.interval') def start(self, interval=None): if interval is not None: self.interval = interval self._timer_start() def stop(self): self._timer_stop() def _timer_start(self): pass def _timer_stop(self): pass @property def interval(self): return self._interval @interval.setter def interval(self, interval): interval = max(int(interval), 1) self._interval = interval self._timer_set_interval() @property def single_shot(self): return self._single @single_shot.setter def single_shot(self, ss): self._single = ss self._timer_set_single_shot() def add_callback(self, func, *args, **kwargs): self.callbacks.append((func, args, kwargs)) return func def remove_callback(self, func, *args, **kwargs): if args or kwargs: _api.warn_deprecated('3.1', message='In a future version, Timer.remove_callback will not take *args, **kwargs anymore, but remove all callbacks where the callable matches; to keep a specific callback removable by itself, pass it to add_callback as a functools.partial object.') self.callbacks.remove((func, args, kwargs)) else: funcs = [c[0] for c in self.callbacks] if func in funcs: self.callbacks.pop(funcs.index(func)) def _timer_set_interval(self): def _timer_set_single_shot(self): def _on_timer(self): for (func, args, kwargs) in self.callbacks: ret = func(*args, **kwargs) if ret == 0: self.callbacks.remove((func, args, kwargs)) if len(self.callbacks) == 0: self.stop() class Event: def __init__(self, name, canvas, guiEvent=None): self.name = name self.canvas = canvas self._guiEvent = guiEvent self._guiEvent_deleted = False def _process(self): self.canvas.callbacks.process(self.name, self) self._guiEvent_deleted = True @property def guiEvent(self): if self._guiEvent_deleted: _api.warn_deprecated('3.8', message='Accessing guiEvent outside of the original GUI event handler is unsafe and deprecated since %(since)s; in the future, the attribute will be set to None after quitting the event handler. You may separately record the value of the guiEvent attribute at your own risk.') return self._guiEvent class DrawEvent(Event): def __init__(self, name, canvas, renderer): super().__init__(name, canvas) self.renderer = renderer class ResizeEvent(Event): def __init__(self, name, canvas): super().__init__(name, canvas) (self.width, self.height) = canvas.get_width_height() class CloseEvent(Event): class LocationEvent(Event): _lastevent = None lastevent = _api.deprecated('3.8')(_api.classproperty(lambda cls: cls._lastevent)) _last_axes_ref = None def __init__(self, name, canvas, x, y, guiEvent=None, *, modifiers=None): super().__init__(name, canvas, guiEvent=guiEvent) self.x = int(x) if x is not None else x self.y = int(y) if y is not None else y self.inaxes = None self.xdata = None self.ydata = None self.modifiers = frozenset(modifiers if modifiers is not None else []) if x is None or y is None: return self._set_inaxes(self.canvas.inaxes((x, y)) if self.canvas.mouse_grabber is None else self.canvas.mouse_grabber, (x, y)) def _set_inaxes(self, inaxes, xy=None): self.inaxes = inaxes if inaxes is not None: try: (self.xdata, self.ydata) = inaxes.transData.inverted().transform(xy if xy is not None else (self.x, self.y)) except ValueError: pass class MouseButton(IntEnum): LEFT = 1 MIDDLE = 2 RIGHT = 3 BACK = 8 FORWARD = 9 class MouseEvent(LocationEvent): def __init__(self, name, canvas, x, y, button=None, key=None, step=0, dblclick=False, guiEvent=None, *, modifiers=None): super().__init__(name, canvas, x, y, guiEvent=guiEvent, modifiers=modifiers) if button in MouseButton.__members__.values(): button = MouseButton(button) if name == 'scroll_event' and button is None: if step > 0: button = 'up' elif step < 0: button = 'down' self.button = button self.key = key self.step = step self.dblclick = dblclick def __str__(self): return f'{self.name}: xy=({self.x}, {self.y}) xydata=({self.xdata}, {self.ydata}) button={self.button} dblclick={self.dblclick} inaxes={self.inaxes}' class PickEvent(Event): def __init__(self, name, canvas, mouseevent, artist, guiEvent=None, **kwargs): if guiEvent is None: guiEvent = mouseevent.guiEvent super().__init__(name, canvas, guiEvent) self.mouseevent = mouseevent self.artist = artist self.__dict__.update(kwargs) class KeyEvent(LocationEvent): def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None): super().__init__(name, canvas, x, y, guiEvent=guiEvent) self.key = key def _key_handler(event): if event.name == 'key_press_event': event.canvas._key = event.key elif event.name == 'key_release_event': event.canvas._key = None def _mouse_handler(event): if event.name == 'button_press_event': event.canvas._button = event.button elif event.name == 'button_release_event': event.canvas._button = None elif event.name == 'motion_notify_event' and event.button is None: event.button = event.canvas._button if event.key is None: event.key = event.canvas._key if event.name == 'motion_notify_event': last_ref = LocationEvent._last_axes_ref last_axes = last_ref() if last_ref else None if last_axes != event.inaxes: if last_axes is not None: try: canvas = last_axes.get_figure(root=True).canvas leave_event = LocationEvent('axes_leave_event', canvas, event.x, event.y, event.guiEvent, modifiers=event.modifiers) leave_event._set_inaxes(last_axes) canvas.callbacks.process('axes_leave_event', leave_event) except Exception: pass if event.inaxes is not None: event.canvas.callbacks.process('axes_enter_event', event) LocationEvent._last_axes_ref = weakref.ref(event.inaxes) if event.inaxes else None LocationEvent._lastevent = None if event.name == 'figure_leave_event' else event def _get_renderer(figure, print_method=None): class Done(Exception): pass def _draw(renderer): raise Done(renderer) with cbook._setattr_cm(figure, draw=_draw), ExitStack() as stack: if print_method is None: fmt = figure.canvas.get_default_filetype() print_method = stack.enter_context(figure.canvas._switch_canvas_and_return_print_method(fmt)) try: print_method(io.BytesIO()) except Done as exc: (renderer,) = exc.args return renderer else: raise RuntimeError(f'{print_method} did not call Figure.draw, so no renderer is available') def _no_output_draw(figure): figure.draw_without_rendering() def _is_non_interactive_terminal_ipython(ip): return hasattr(ip, 'parent') and ip.parent is not None and (getattr(ip.parent, 'interact', None) is False) @contextmanager def _allow_interrupt(prepare_notifier, handle_sigint): old_sigint_handler = signal.getsignal(signal.SIGINT) if old_sigint_handler in (None, signal.SIG_IGN, signal.SIG_DFL): yield return handler_args = None (wsock, rsock) = socket.socketpair() wsock.setblocking(False) rsock.setblocking(False) old_wakeup_fd = signal.set_wakeup_fd(wsock.fileno()) notifier = prepare_notifier(rsock) def save_args_and_handle_sigint(*args): nonlocal handler_args handler_args = args handle_sigint() signal.signal(signal.SIGINT, save_args_and_handle_sigint) try: yield finally: wsock.close() rsock.close() signal.set_wakeup_fd(old_wakeup_fd) signal.signal(signal.SIGINT, old_sigint_handler) if handler_args is not None: old_sigint_handler(*handler_args) class FigureCanvasBase: required_interactive_framework = None manager_class = _api.classproperty(lambda cls: FigureManagerBase) events = ['resize_event', 'draw_event', 'key_press_event', 'key_release_event', 'button_press_event', 'button_release_event', 'scroll_event', 'motion_notify_event', 'pick_event', 'figure_enter_event', 'figure_leave_event', 'axes_enter_event', 'axes_leave_event', 'close_event'] fixed_dpi = None filetypes = _default_filetypes @_api.classproperty def supports_blit(cls): return hasattr(cls, 'copy_from_bbox') and hasattr(cls, 'restore_region') def __init__(self, figure=None): from matplotlib.figure import Figure self._fix_ipython_backend2gui() self._is_idle_drawing = True self._is_saving = False if figure is None: figure = Figure() figure.set_canvas(self) self.figure = figure self.manager = None self.widgetlock = widgets.LockDraw() self._button = None self._key = None self.mouse_grabber = None self.toolbar = None self._is_idle_drawing = False figure._original_dpi = figure.dpi self._device_pixel_ratio = 1 super().__init__() callbacks = property(lambda self: self.figure._canvas_callbacks) button_pick_id = property(lambda self: self.figure._button_pick_id) scroll_pick_id = property(lambda self: self.figure._scroll_pick_id) @classmethod @functools.cache def _fix_ipython_backend2gui(cls): mod_ipython = sys.modules.get('IPython') if mod_ipython is None or mod_ipython.version_info[:2] >= (8, 24): return import IPython ip = IPython.get_ipython() if not ip: return from IPython.core import pylabtools as pt if not hasattr(pt, 'backend2gui') or not hasattr(ip, 'enable_matplotlib'): return backend2gui_rif = {'qt': 'qt', 'gtk3': 'gtk3', 'gtk4': 'gtk4', 'wx': 'wx', 'macosx': 'osx'}.get(cls.required_interactive_framework) if backend2gui_rif: if _is_non_interactive_terminal_ipython(ip): ip.enable_gui(backend2gui_rif) @classmethod def new_manager(cls, figure, num): return cls.manager_class.create_with_canvas(cls, figure, num) @contextmanager def _idle_draw_cntx(self): self._is_idle_drawing = True try: yield finally: self._is_idle_drawing = False def is_saving(self): return self._is_saving def blit(self, bbox=None): def inaxes(self, xy): axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy) and a.get_visible()] if axes_list: axes = cbook._topmost_artist(axes_list) else: axes = None return axes def grab_mouse(self, ax): if self.mouse_grabber not in (None, ax): raise RuntimeError('Another Axes already grabs mouse input') self.mouse_grabber = ax def release_mouse(self, ax): if self.mouse_grabber is ax: self.mouse_grabber = None def set_cursor(self, cursor): def draw(self, *args, **kwargs): def draw_idle(self, *args, **kwargs): if not self._is_idle_drawing: with self._idle_draw_cntx(): self.draw(*args, **kwargs) @property def device_pixel_ratio(self): return self._device_pixel_ratio def _set_device_pixel_ratio(self, ratio): if self._device_pixel_ratio == ratio: return False dpi = ratio * self.figure._original_dpi self.figure._set_dpi(dpi, forward=False) self._device_pixel_ratio = ratio return True def get_width_height(self, *, physical=False): return tuple((int(size / (1 if physical else self.device_pixel_ratio)) for size in self.figure.bbox.max)) @classmethod def get_supported_filetypes(cls): return cls.filetypes @classmethod def get_supported_filetypes_grouped(cls): groupings = {} for (ext, name) in cls.filetypes.items(): groupings.setdefault(name, []).append(ext) groupings[name].sort() return groupings @contextmanager def _switch_canvas_and_return_print_method(self, fmt, backend=None): canvas = None if backend is not None: from .backends.registry import backend_registry canvas_class = backend_registry.load_backend_module(backend).FigureCanvas if not hasattr(canvas_class, f'print_{fmt}'): raise ValueError(f'The {backend!r} backend does not support {fmt} output') canvas = canvas_class(self.figure) elif hasattr(self, f'print_{fmt}'): canvas = self else: canvas_class = get_registered_canvas_class(fmt) if canvas_class is None: raise ValueError('Format {!r} is not supported (supported formats: {})'.format(fmt, ', '.join(sorted(self.get_supported_filetypes())))) canvas = canvas_class(self.figure) canvas._is_saving = self._is_saving meth = getattr(canvas, f'print_{fmt}') mod = meth.func.__module__ if hasattr(meth, 'func') else meth.__module__ if mod.startswith(('matplotlib.', 'mpl_toolkits.')): optional_kws = {'dpi', 'facecolor', 'edgecolor', 'orientation', 'bbox_inches_restore'} skip = optional_kws - {*inspect.signature(meth).parameters} print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(*args, **{k: v for (k, v) in kwargs.items() if k not in skip})) else: print_method = meth try: yield print_method finally: self.figure.canvas = self def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None, orientation='portrait', format=None, *, bbox_inches=None, pad_inches=None, bbox_extra_artists=None, backend=None, **kwargs): if format is None: if isinstance(filename, os.PathLike): filename = os.fspath(filename) if isinstance(filename, str): format = os.path.splitext(filename)[1][1:] if format is None or format == '': format = self.get_default_filetype() if isinstance(filename, str): filename = filename.rstrip('.') + '.' + format format = format.lower() if dpi is None: dpi = rcParams['savefig.dpi'] if dpi == 'figure': dpi = getattr(self.figure, '_original_dpi', self.figure.dpi) if kwargs.get('papertype') == 'auto': _api.warn_deprecated('3.8', name="papertype='auto'", addendum="Pass an explicit paper type, 'figure', or omit the *papertype* argument entirely.") with cbook._setattr_cm(self, manager=None), self._switch_canvas_and_return_print_method(format, backend) as print_method, cbook._setattr_cm(self.figure, dpi=dpi), cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1), cbook._setattr_cm(self.figure.canvas, _is_saving=True), ExitStack() as stack: for prop in ['facecolor', 'edgecolor']: color = locals()[prop] if color is None: color = rcParams[f'savefig.{prop}'] if not cbook._str_equal(color, 'auto'): stack.enter_context(self.figure._cm_set(**{prop: color})) if bbox_inches is None: bbox_inches = rcParams['savefig.bbox'] layout_engine = self.figure.get_layout_engine() if layout_engine is not None or bbox_inches == 'tight': renderer = _get_renderer(self.figure, functools.partial(print_method, orientation=orientation)) with getattr(renderer, '_draw_disabled', nullcontext)(): self.figure.draw(renderer) if bbox_inches: if bbox_inches == 'tight': bbox_inches = self.figure.get_tightbbox(renderer, bbox_extra_artists=bbox_extra_artists) if isinstance(layout_engine, ConstrainedLayoutEngine) and pad_inches == 'layout': h_pad = layout_engine.get()['h_pad'] w_pad = layout_engine.get()['w_pad'] else: if pad_inches in [None, 'layout']: pad_inches = rcParams['savefig.pad_inches'] h_pad = w_pad = pad_inches bbox_inches = bbox_inches.padded(w_pad, h_pad) restore_bbox = _tight_bbox.adjust_bbox(self.figure, bbox_inches, self.figure.canvas.fixed_dpi) _bbox_inches_restore = (bbox_inches, restore_bbox) else: _bbox_inches_restore = None stack.enter_context(self.figure._cm_set(layout_engine='none')) try: with cbook._setattr_cm(self.figure, dpi=dpi): result = print_method(filename, facecolor=facecolor, edgecolor=edgecolor, orientation=orientation, bbox_inches_restore=_bbox_inches_restore, **kwargs) finally: if bbox_inches and restore_bbox: restore_bbox() return result @classmethod def get_default_filetype(cls): return rcParams['savefig.format'] def get_default_filename(self): default_basename = self.manager.get_window_title() if self.manager is not None else '' default_basename = default_basename or 'image' removed_chars = '<>:"/\\|?*\\0 ' default_basename = default_basename.translate({ord(c): '_' for c in removed_chars}) default_filetype = self.get_default_filetype() return f'{default_basename}.{default_filetype}' @_api.deprecated('3.8') def switch_backends(self, FigureCanvasClass): newCanvas = FigureCanvasClass(self.figure) newCanvas._is_saving = self._is_saving return newCanvas def mpl_connect(self, s, func): return self.callbacks.connect(s, func) def mpl_disconnect(self, cid): self.callbacks.disconnect(cid) _timer_cls = TimerBase def new_timer(self, interval=None, callbacks=None): return self._timer_cls(interval=interval, callbacks=callbacks) def flush_events(self): def start_event_loop(self, timeout=0): if timeout <= 0: timeout = np.inf timestep = 0.01 counter = 0 self._looping = True while self._looping and counter * timestep < timeout: self.flush_events() time.sleep(timestep) counter += 1 def stop_event_loop(self): self._looping = False def key_press_handler(event, canvas=None, toolbar=None): if event.key is None: return if canvas is None: canvas = event.canvas if toolbar is None: toolbar = canvas.toolbar if event.key in rcParams['keymap.fullscreen']: try: canvas.manager.full_screen_toggle() except AttributeError: pass if event.key in rcParams['keymap.quit']: Gcf.destroy_fig(canvas.figure) if event.key in rcParams['keymap.quit_all']: Gcf.destroy_all() if toolbar is not None: if event.key in rcParams['keymap.home']: toolbar.home() elif event.key in rcParams['keymap.back']: toolbar.back() elif event.key in rcParams['keymap.forward']: toolbar.forward() elif event.key in rcParams['keymap.pan']: toolbar.pan() toolbar._update_cursor(event) elif event.key in rcParams['keymap.zoom']: toolbar.zoom() toolbar._update_cursor(event) elif event.key in rcParams['keymap.save']: toolbar.save_figure() if event.inaxes is None: return def _get_uniform_gridstate(ticks): return True if all((tick.gridline.get_visible() for tick in ticks)) else False if not any((tick.gridline.get_visible() for tick in ticks)) else None ax = event.inaxes if event.key in rcParams['keymap.grid'] and None not in [_get_uniform_gridstate(ax.xaxis.minorTicks), _get_uniform_gridstate(ax.yaxis.minorTicks)]: x_state = _get_uniform_gridstate(ax.xaxis.majorTicks) y_state = _get_uniform_gridstate(ax.yaxis.majorTicks) cycle = [(False, False), (True, False), (True, True), (False, True)] try: (x_state, y_state) = cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)] except ValueError: pass else: ax.grid(x_state, which='major' if x_state else 'both', axis='x') ax.grid(y_state, which='major' if y_state else 'both', axis='y') canvas.draw_idle() if event.key in rcParams['keymap.grid_minor'] and None not in [_get_uniform_gridstate(ax.xaxis.majorTicks), _get_uniform_gridstate(ax.yaxis.majorTicks)]: x_state = _get_uniform_gridstate(ax.xaxis.minorTicks) y_state = _get_uniform_gridstate(ax.yaxis.minorTicks) cycle = [(False, False), (True, False), (True, True), (False, True)] try: (x_state, y_state) = cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)] except ValueError: pass else: ax.grid(x_state, which='both', axis='x') ax.grid(y_state, which='both', axis='y') canvas.draw_idle() elif event.key in rcParams['keymap.yscale']: scale = ax.get_yscale() if scale == 'log': ax.set_yscale('linear') ax.get_figure(root=True).canvas.draw_idle() elif scale == 'linear': try: ax.set_yscale('log') except ValueError as exc: _log.warning(str(exc)) ax.set_yscale('linear') ax.get_figure(root=True).canvas.draw_idle() elif event.key in rcParams['keymap.xscale']: scalex = ax.get_xscale() if scalex == 'log': ax.set_xscale('linear') ax.get_figure(root=True).canvas.draw_idle() elif scalex == 'linear': try: ax.set_xscale('log') except ValueError as exc: _log.warning(str(exc)) ax.set_xscale('linear') ax.get_figure(root=True).canvas.draw_idle() def button_press_handler(event, canvas=None, toolbar=None): if canvas is None: canvas = event.canvas if toolbar is None: toolbar = canvas.toolbar if toolbar is not None: button_name = str(MouseButton(event.button)) if button_name in rcParams['keymap.back']: toolbar.back() elif button_name in rcParams['keymap.forward']: toolbar.forward() class NonGuiException(Exception): pass class FigureManagerBase: _toolbar2_class = None _toolmanager_toolbar_class = None def __init__(self, canvas, num): self.canvas = canvas canvas.manager = self self.num = num self.set_window_title(f'Figure {num:d}') self.key_press_handler_id = None self.button_press_handler_id = None if rcParams['toolbar'] != 'toolmanager': self.key_press_handler_id = self.canvas.mpl_connect('key_press_event', key_press_handler) self.button_press_handler_id = self.canvas.mpl_connect('button_press_event', button_press_handler) self.toolmanager = ToolManager(canvas.figure) if mpl.rcParams['toolbar'] == 'toolmanager' else None if mpl.rcParams['toolbar'] == 'toolbar2' and self._toolbar2_class: self.toolbar = self._toolbar2_class(self.canvas) elif mpl.rcParams['toolbar'] == 'toolmanager' and self._toolmanager_toolbar_class: self.toolbar = self._toolmanager_toolbar_class(self.toolmanager) else: self.toolbar = None if self.toolmanager: tools.add_tools_to_manager(self.toolmanager) if self.toolbar: tools.add_tools_to_container(self.toolbar) @self.canvas.figure.add_axobserver def notify_axes_change(fig): if self.toolmanager is None and self.toolbar is not None: self.toolbar.update() @classmethod def create_with_canvas(cls, canvas_class, figure, num): return cls(canvas_class(figure), num) @classmethod def start_main_loop(cls): @classmethod def pyplot_show(cls, *, block=None): managers = Gcf.get_all_fig_managers() if not managers: return for manager in managers: try: manager.show() except NonGuiException as exc: _api.warn_external(str(exc)) if block is None: pyplot_show = getattr(sys.modules.get('matplotlib.pyplot'), 'show', None) ipython_pylab = hasattr(pyplot_show, '_needmain') block = not ipython_pylab and (not is_interactive()) if block: cls.start_main_loop() def show(self): if sys.platform == 'linux' and (not os.environ.get('DISPLAY')): return raise NonGuiException(f'{type(self.canvas).__name__} is non-interactive, and thus cannot be shown') def destroy(self): pass def full_screen_toggle(self): pass def resize(self, w, h): def get_window_title(self): return 'image' def set_window_title(self, title): cursors = tools.cursors class _Mode(str, Enum): NONE = '' PAN = 'pan/zoom' ZOOM = 'zoom rect' def __str__(self): return self.value @property def _navigate_mode(self): return self.name if self is not _Mode.NONE else None class NavigationToolbar2: toolitems = (('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view', 'back', 'back'), ('Forward', 'Forward to next view', 'forward', 'forward'), (None, None, None, None), ('Pan', 'Left button pans, Right button zooms\nx/y fixes axis, CTRL fixes aspect', 'move', 'pan'), ('Zoom', 'Zoom to rectangle\nx/y fixes axis', 'zoom_to_rect', 'zoom'), ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'), (None, None, None, None), ('Save', 'Save the figure', 'filesave', 'save_figure')) def __init__(self, canvas): self.canvas = canvas canvas.toolbar = self self._nav_stack = cbook._Stack() self._last_cursor = tools.Cursors.POINTER self._id_press = self.canvas.mpl_connect('button_press_event', self._zoom_pan_handler) self._id_release = self.canvas.mpl_connect('button_release_event', self._zoom_pan_handler) self._id_drag = self.canvas.mpl_connect('motion_notify_event', self.mouse_move) self._pan_info = None self._zoom_info = None self.mode = _Mode.NONE self.set_history_buttons() def set_message(self, s): def draw_rubberband(self, event, x0, y0, x1, y1): def remove_rubberband(self): def home(self, *args): self._nav_stack.home() self.set_history_buttons() self._update_view() def back(self, *args): self._nav_stack.back() self.set_history_buttons() self._update_view() def forward(self, *args): self._nav_stack.forward() self.set_history_buttons() self._update_view() def _update_cursor(self, event): if self.mode and event.inaxes and event.inaxes.get_navigate(): if self.mode == _Mode.ZOOM and self._last_cursor != tools.Cursors.SELECT_REGION: self.canvas.set_cursor(tools.Cursors.SELECT_REGION) self._last_cursor = tools.Cursors.SELECT_REGION elif self.mode == _Mode.PAN and self._last_cursor != tools.Cursors.MOVE: self.canvas.set_cursor(tools.Cursors.MOVE) self._last_cursor = tools.Cursors.MOVE elif self._last_cursor != tools.Cursors.POINTER: self.canvas.set_cursor(tools.Cursors.POINTER) self._last_cursor = tools.Cursors.POINTER @contextmanager def _wait_cursor_for_draw_cm(self): (self._draw_time, last_draw_time) = (time.time(), getattr(self, '_draw_time', -np.inf)) if self._draw_time - last_draw_time > 1: try: self.canvas.set_cursor(tools.Cursors.WAIT) yield finally: self.canvas.set_cursor(self._last_cursor) else: yield @staticmethod def _mouse_event_to_message(event): if event.inaxes and event.inaxes.get_navigate(): try: s = event.inaxes.format_coord(event.xdata, event.ydata) except (ValueError, OverflowError): pass else: s = s.rstrip() artists = [a for a in event.inaxes._mouseover_set if a.contains(event)[0] and a.get_visible()] if artists: a = cbook._topmost_artist(artists) if a is not event.inaxes.patch: data = a.get_cursor_data(event) if data is not None: data_str = a.format_cursor_data(data).rstrip() if data_str: s = s + '\n' + data_str return s return '' def mouse_move(self, event): self._update_cursor(event) self.set_message(self._mouse_event_to_message(event)) def _zoom_pan_handler(self, event): if self.mode == _Mode.PAN: if event.name == 'button_press_event': self.press_pan(event) elif event.name == 'button_release_event': self.release_pan(event) if self.mode == _Mode.ZOOM: if event.name == 'button_press_event': self.press_zoom(event) elif event.name == 'button_release_event': self.release_zoom(event) def _start_event_axes_interaction(self, event, *, method): def _ax_filter(ax): return ax.in_axes(event) and ax.get_navigate() and getattr(ax, f'can_{method}')() def _capture_events(ax): f = ax.get_forward_navigation_events() if f == 'auto': f = not ax.patch.get_visible() return not f axes = list(filter(_ax_filter, self.canvas.figure.get_axes())) if len(axes) == 0: return [] if self._nav_stack() is None: self.push_current() grps = dict() for ax in reversed(axes): grps.setdefault(ax.get_zorder(), []).append(ax) axes_to_trigger = [] for zorder in sorted(grps, reverse=True): for ax in grps[zorder]: axes_to_trigger.append(ax) axes_to_trigger.extend(ax._twinned_axes.get_siblings(ax)) if _capture_events(ax): break else: continue break axes_to_trigger = list(dict.fromkeys(axes_to_trigger)) return axes_to_trigger def pan(self, *args): if not self.canvas.widgetlock.available(self): self.set_message('pan unavailable') return if self.mode == _Mode.PAN: self.mode = _Mode.NONE self.canvas.widgetlock.release(self) else: self.mode = _Mode.PAN self.canvas.widgetlock(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self.mode._navigate_mode) _PanInfo = namedtuple('_PanInfo', 'button axes cid') def press_pan(self, event): if event.button not in [MouseButton.LEFT, MouseButton.RIGHT] or event.x is None or event.y is None: return axes = self._start_event_axes_interaction(event, method='pan') if not axes: return for ax in axes: ax.start_pan(event.x, event.y, event.button) self.canvas.mpl_disconnect(self._id_drag) id_drag = self.canvas.mpl_connect('motion_notify_event', self.drag_pan) self._pan_info = self._PanInfo(button=event.button, axes=axes, cid=id_drag) def drag_pan(self, event): for ax in self._pan_info.axes: ax.drag_pan(self._pan_info.button, event.key, event.x, event.y) self.canvas.draw_idle() def release_pan(self, event): if self._pan_info is None: return self.canvas.mpl_disconnect(self._pan_info.cid) self._id_drag = self.canvas.mpl_connect('motion_notify_event', self.mouse_move) for ax in self._pan_info.axes: ax.end_pan() self.canvas.draw_idle() self._pan_info = None self.push_current() def zoom(self, *args): if not self.canvas.widgetlock.available(self): self.set_message('zoom unavailable') return '' if self.mode == _Mode.ZOOM: self.mode = _Mode.NONE self.canvas.widgetlock.release(self) else: self.mode = _Mode.ZOOM self.canvas.widgetlock(self) for a in self.canvas.figure.get_axes(): a.set_navigate_mode(self.mode._navigate_mode) _ZoomInfo = namedtuple('_ZoomInfo', 'direction start_xy axes cid cbar') def press_zoom(self, event): if event.button not in [MouseButton.LEFT, MouseButton.RIGHT] or event.x is None or event.y is None: return axes = self._start_event_axes_interaction(event, method='zoom') if not axes: return id_zoom = self.canvas.mpl_connect('motion_notify_event', self.drag_zoom) parent_ax = axes[0] if hasattr(parent_ax, '_colorbar'): cbar = parent_ax._colorbar.orientation else: cbar = None self._zoom_info = self._ZoomInfo(direction='in' if event.button == 1 else 'out', start_xy=(event.x, event.y), axes=axes, cid=id_zoom, cbar=cbar) def drag_zoom(self, event): start_xy = self._zoom_info.start_xy ax = self._zoom_info.axes[0] ((x1, y1), (x2, y2)) = np.clip([start_xy, [event.x, event.y]], ax.bbox.min, ax.bbox.max) key = event.key if self._zoom_info.cbar == 'horizontal': key = 'x' elif self._zoom_info.cbar == 'vertical': key = 'y' if key == 'x': (y1, y2) = ax.bbox.intervaly elif key == 'y': (x1, x2) = ax.bbox.intervalx self.draw_rubberband(event, x1, y1, x2, y2) def release_zoom(self, event): if self._zoom_info is None: return self.canvas.mpl_disconnect(self._zoom_info.cid) self.remove_rubberband() (start_x, start_y) = self._zoom_info.start_xy key = event.key if self._zoom_info.cbar == 'horizontal': key = 'x' elif self._zoom_info.cbar == 'vertical': key = 'y' if abs(event.x - start_x) < 5 and key != 'y' or (abs(event.y - start_y) < 5 and key != 'x'): self.canvas.draw_idle() self._zoom_info = None return for (i, ax) in enumerate(self._zoom_info.axes): twinx = any((ax.get_shared_x_axes().joined(ax, prev) for prev in self._zoom_info.axes[:i])) twiny = any((ax.get_shared_y_axes().joined(ax, prev) for prev in self._zoom_info.axes[:i])) ax._set_view_from_bbox((start_x, start_y, event.x, event.y), self._zoom_info.direction, key, twinx, twiny) self.canvas.draw_idle() self._zoom_info = None self.push_current() def push_current(self): self._nav_stack.push(WeakKeyDictionary({ax: (ax._get_view(), (ax.get_position(True).frozen(), ax.get_position().frozen())) for ax in self.canvas.figure.axes})) self.set_history_buttons() def _update_view(self): nav_info = self._nav_stack() if nav_info is None: return items = list(nav_info.items()) for (ax, (view, (pos_orig, pos_active))) in items: ax._set_view(view) ax._set_position(pos_orig, 'original') ax._set_position(pos_active, 'active') self.canvas.draw_idle() def configure_subplots(self, *args): if hasattr(self, 'subplot_tool'): self.subplot_tool.figure.canvas.manager.show() return from matplotlib.figure import Figure with mpl.rc_context({'toolbar': 'none'}): manager = type(self.canvas).new_manager(Figure(figsize=(6, 3)), -1) manager.set_window_title('Subplot configuration tool') tool_fig = manager.canvas.figure tool_fig.subplots_adjust(top=0.9) self.subplot_tool = widgets.SubplotTool(self.canvas.figure, tool_fig) cid = self.canvas.mpl_connect('close_event', lambda e: manager.destroy()) def on_tool_fig_close(e): self.canvas.mpl_disconnect(cid) del self.subplot_tool tool_fig.canvas.mpl_connect('close_event', on_tool_fig_close) manager.show() return self.subplot_tool def save_figure(self, *args): raise NotImplementedError def update(self): self._nav_stack.clear() self.set_history_buttons() def set_history_buttons(self): class ToolContainerBase: _icon_extension = '.png' '' def __init__(self, toolmanager): self.toolmanager = toolmanager toolmanager.toolmanager_connect('tool_message_event', lambda event: self.set_message(event.message)) toolmanager.toolmanager_connect('tool_removed_event', lambda event: self.remove_toolitem(event.tool.name)) def _tool_toggled_cbk(self, event): self.toggle_toolitem(event.tool.name, event.tool.toggled) def add_tool(self, tool, group, position=-1): tool = self.toolmanager.get_tool(tool) image = self._get_image_filename(tool) toggle = getattr(tool, 'toggled', None) is not None self.add_toolitem(tool.name, group, position, image, tool.description, toggle) if toggle: self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name, self._tool_toggled_cbk) if tool.toggled: self.toggle_toolitem(tool.name, True) def _get_image_filename(self, tool): if not tool.image: return None if os.path.isabs(tool.image): filename = tool.image else: if 'image' in getattr(tool, '__dict__', {}): raise ValueError("If 'tool.image' is an instance variable, it must be an absolute path") for cls in type(tool).__mro__: if 'image' in vars(cls): try: src = inspect.getfile(cls) break except (OSError, TypeError): raise ValueError("Failed to locate source file where 'tool.image' is defined") from None else: raise ValueError("Failed to find parent class defining 'tool.image'") filename = str(pathlib.Path(src).parent / tool.image) for filename in [filename, filename + self._icon_extension]: if os.path.isfile(filename): return os.path.abspath(filename) for fname in [tool.image, tool.image + self._icon_extension, cbook._get_data_path('images', tool.image), cbook._get_data_path('images', tool.image + self._icon_extension)]: if os.path.isfile(fname): _api.warn_deprecated('3.9', message=f"Loading icon {tool.image!r} from the current directory or from Matplotlib's image directory. This behavior is deprecated since %(since)s and will be removed %(removal)s; Tool.image should be set to a path relative to the Tool's source file, or to an absolute path.") return os.path.abspath(fname) def trigger_tool(self, name): self.toolmanager.trigger_tool(name, sender=self) def add_toolitem(self, name, group, position, image, description, toggle): raise NotImplementedError def toggle_toolitem(self, name, toggled): raise NotImplementedError def remove_toolitem(self, name): raise NotImplementedError def set_message(self, s): raise NotImplementedError class _Backend: backend_version = 'unknown' FigureCanvas = None FigureManager = FigureManagerBase mainloop = None @classmethod def new_figure_manager(cls, num, *args, **kwargs): from matplotlib.figure import Figure fig_cls = kwargs.pop('FigureClass', Figure) fig = fig_cls(*args, **kwargs) return cls.new_figure_manager_given_figure(num, fig) @classmethod def new_figure_manager_given_figure(cls, num, figure): return cls.FigureCanvas.new_manager(figure, num) @classmethod def draw_if_interactive(cls): manager_class = cls.FigureCanvas.manager_class backend_is_interactive = manager_class.start_main_loop != FigureManagerBase.start_main_loop or manager_class.pyplot_show != FigureManagerBase.pyplot_show if backend_is_interactive and is_interactive(): manager = Gcf.get_active() if manager: manager.canvas.draw_idle() @classmethod def show(cls, *, block=None): managers = Gcf.get_all_fig_managers() if not managers: return for manager in managers: try: manager.show() except NonGuiException as exc: _api.warn_external(str(exc)) if cls.mainloop is None: return if block is None: pyplot_show = getattr(sys.modules.get('matplotlib.pyplot'), 'show', None) ipython_pylab = hasattr(pyplot_show, '_needmain') block = not ipython_pylab and (not is_interactive()) if block: cls.mainloop() @staticmethod def export(cls): for name in ['backend_version', 'FigureCanvas', 'FigureManager', 'new_figure_manager', 'new_figure_manager_given_figure', 'draw_if_interactive', 'show']: setattr(sys.modules[cls.__module__], name, getattr(cls, name)) class Show(ShowBase): def mainloop(self): return cls.mainloop() setattr(sys.modules[cls.__module__], 'Show', Show) return cls class ShowBase(_Backend): def __call__(self, block=None): return self.show(block=block) # File: matplotlib-main/lib/matplotlib/backend_managers.py from matplotlib import _api, backend_tools, cbook, widgets class ToolEvent: def __init__(self, name, sender, tool, data=None): self.name = name self.sender = sender self.tool = tool self.data = data class ToolTriggerEvent(ToolEvent): def __init__(self, name, sender, tool, canvasevent=None, data=None): super().__init__(name, sender, tool, data) self.canvasevent = canvasevent class ToolManagerMessageEvent: def __init__(self, name, sender, message): self.name = name self.sender = sender self.message = message class ToolManager: def __init__(self, figure=None): self._key_press_handler_id = None self._tools = {} self._keys = {} self._toggled = {} self._callbacks = cbook.CallbackRegistry() self.keypresslock = widgets.LockDraw() self.messagelock = widgets.LockDraw() self._figure = None self.set_figure(figure) @property def canvas(self): if not self._figure: return None return self._figure.canvas @property def figure(self): return self._figure @figure.setter def figure(self, figure): self.set_figure(figure) def set_figure(self, figure, update_tools=True): if self._key_press_handler_id: self.canvas.mpl_disconnect(self._key_press_handler_id) self._figure = figure if figure: self._key_press_handler_id = self.canvas.mpl_connect('key_press_event', self._key_press) if update_tools: for tool in self._tools.values(): tool.figure = figure def toolmanager_connect(self, s, func): return self._callbacks.connect(s, func) def toolmanager_disconnect(self, cid): return self._callbacks.disconnect(cid) def message_event(self, message, sender=None): if sender is None: sender = self s = 'tool_message_event' event = ToolManagerMessageEvent(s, sender, message) self._callbacks.process(s, event) @property def active_toggle(self): return self._toggled def get_tool_keymap(self, name): keys = [k for (k, i) in self._keys.items() if i == name] return keys def _remove_keys(self, name): for k in self.get_tool_keymap(name): del self._keys[k] def update_keymap(self, name, key): if name not in self._tools: raise KeyError(f'{name!r} not in Tools') self._remove_keys(name) if isinstance(key, str): key = [key] for k in key: if k in self._keys: _api.warn_external(f'Key {k} changed from {self._keys[k]} to {name}') self._keys[k] = name def remove_tool(self, name): tool = self.get_tool(name) if getattr(tool, 'toggled', False): self.trigger_tool(tool, 'toolmanager') self._remove_keys(name) event = ToolEvent('tool_removed_event', self, tool) self._callbacks.process(event.name, event) del self._tools[name] def add_tool(self, name, tool, *args, **kwargs): tool_cls = backend_tools._find_tool_class(type(self.canvas), tool) if not tool_cls: raise ValueError('Impossible to find class for %s' % str(tool)) if name in self._tools: _api.warn_external('A "Tool class" with the same name already exists, not added') return self._tools[name] tool_obj = tool_cls(self, name, *args, **kwargs) self._tools[name] = tool_obj if tool_obj.default_keymap is not None: self.update_keymap(name, tool_obj.default_keymap) if isinstance(tool_obj, backend_tools.ToolToggleBase): if tool_obj.radio_group is None: self._toggled.setdefault(None, set()) else: self._toggled.setdefault(tool_obj.radio_group, None) if tool_obj.toggled: self._handle_toggle(tool_obj, None, None) tool_obj.set_figure(self.figure) event = ToolEvent('tool_added_event', self, tool_obj) self._callbacks.process(event.name, event) return tool_obj def _handle_toggle(self, tool, canvasevent, data): radio_group = tool.radio_group if radio_group is None: if tool.name in self._toggled[None]: self._toggled[None].remove(tool.name) else: self._toggled[None].add(tool.name) return if self._toggled[radio_group] == tool.name: toggled = None elif self._toggled[radio_group] is None: toggled = tool.name else: self.trigger_tool(self._toggled[radio_group], self, canvasevent, data) toggled = tool.name self._toggled[radio_group] = toggled def trigger_tool(self, name, sender=None, canvasevent=None, data=None): tool = self.get_tool(name) if tool is None: return if sender is None: sender = self if isinstance(tool, backend_tools.ToolToggleBase): self._handle_toggle(tool, canvasevent, data) tool.trigger(sender, canvasevent, data) s = 'tool_trigger_%s' % name event = ToolTriggerEvent(s, sender, tool, canvasevent, data) self._callbacks.process(s, event) def _key_press(self, event): if event.key is None or self.keypresslock.locked(): return name = self._keys.get(event.key, None) if name is None: return self.trigger_tool(name, canvasevent=event) @property def tools(self): return self._tools def get_tool(self, name, warn=True): if isinstance(name, backend_tools.ToolBase) and name.name in self._tools: return name if name not in self._tools: if warn: _api.warn_external(f'ToolManager does not control tool {name!r}') return None return self._tools[name] # File: matplotlib-main/lib/matplotlib/backend_tools.py """""" import enum import functools import re import time from types import SimpleNamespace import uuid from weakref import WeakKeyDictionary import numpy as np import matplotlib as mpl from matplotlib._pylab_helpers import Gcf from matplotlib import _api, cbook class Cursors(enum.IntEnum): POINTER = enum.auto() HAND = enum.auto() SELECT_REGION = enum.auto() MOVE = enum.auto() WAIT = enum.auto() RESIZE_HORIZONTAL = enum.auto() RESIZE_VERTICAL = enum.auto() cursors = Cursors _tool_registry = set() def _register_tool_class(canvas_cls, tool_cls=None): if tool_cls is None: return functools.partial(_register_tool_class, canvas_cls) _tool_registry.add((canvas_cls, tool_cls)) return tool_cls def _find_tool_class(canvas_cls, tool_cls): for canvas_parent in canvas_cls.__mro__: for tool_child in _api.recursive_subclasses(tool_cls): if (canvas_parent, tool_child) in _tool_registry: return tool_child return tool_cls _views_positions = 'viewpos' class ToolBase: default_keymap = None '' description = None '' image = None '' def __init__(self, toolmanager, name): self._name = name self._toolmanager = toolmanager self._figure = None name = property(lambda self: self._name, doc='The tool id (str, must be unique among tools of a tool manager).') toolmanager = property(lambda self: self._toolmanager, doc='The `.ToolManager` that controls this tool.') canvas = property(lambda self: self._figure.canvas if self._figure is not None else None, doc='The canvas of the figure affected by this tool, or None.') def set_figure(self, figure): self._figure = figure figure = property(lambda self: self._figure, lambda self, figure: self.set_figure(figure), doc='The Figure affected by this tool, or None.') def _make_classic_style_pseudo_toolbar(self): return SimpleNamespace(canvas=self.canvas) def trigger(self, sender, event, data=None): pass class ToolToggleBase(ToolBase): radio_group = None '' cursor = None '' default_toggled = False '' def __init__(self, *args, **kwargs): self._toggled = kwargs.pop('toggled', self.default_toggled) super().__init__(*args, **kwargs) def trigger(self, sender, event, data=None): if self._toggled: self.disable(event) else: self.enable(event) self._toggled = not self._toggled def enable(self, event=None): pass def disable(self, event=None): pass @property def toggled(self): return self._toggled def set_figure(self, figure): toggled = self.toggled if toggled: if self.figure: self.trigger(self, None) else: self._toggled = False super().set_figure(figure) if toggled: if figure: self.trigger(self, None) else: self._toggled = True class ToolSetCursor(ToolBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._id_drag = None self._current_tool = None self._default_cursor = cursors.POINTER self._last_cursor = self._default_cursor self.toolmanager.toolmanager_connect('tool_added_event', self._add_tool_cbk) for tool in self.toolmanager.tools.values(): self._add_tool_cbk(mpl.backend_managers.ToolEvent('tool_added_event', self.toolmanager, tool)) def set_figure(self, figure): if self._id_drag: self.canvas.mpl_disconnect(self._id_drag) super().set_figure(figure) if figure: self._id_drag = self.canvas.mpl_connect('motion_notify_event', self._set_cursor_cbk) def _add_tool_cbk(self, event): if getattr(event.tool, 'cursor', None) is not None: self.toolmanager.toolmanager_connect(f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk) def _tool_trigger_cbk(self, event): self._current_tool = event.tool if event.tool.toggled else None self._set_cursor_cbk(event.canvasevent) def _set_cursor_cbk(self, event): if not event or not self.canvas: return if self._current_tool and getattr(event, 'inaxes', None) and event.inaxes.get_navigate(): if self._last_cursor != self._current_tool.cursor: self.canvas.set_cursor(self._current_tool.cursor) self._last_cursor = self._current_tool.cursor elif self._last_cursor != self._default_cursor: self.canvas.set_cursor(self._default_cursor) self._last_cursor = self._default_cursor class ToolCursorPosition(ToolBase): def __init__(self, *args, **kwargs): self._id_drag = None super().__init__(*args, **kwargs) def set_figure(self, figure): if self._id_drag: self.canvas.mpl_disconnect(self._id_drag) super().set_figure(figure) if figure: self._id_drag = self.canvas.mpl_connect('motion_notify_event', self.send_message) def send_message(self, event): if self.toolmanager.messagelock.locked(): return from matplotlib.backend_bases import NavigationToolbar2 message = NavigationToolbar2._mouse_event_to_message(event) self.toolmanager.message_event(message, self) class RubberbandBase(ToolBase): def trigger(self, sender, event, data=None): if not self.figure.canvas.widgetlock.available(sender): return if data is not None: self.draw_rubberband(*data) else: self.remove_rubberband() def draw_rubberband(self, *data): raise NotImplementedError def remove_rubberband(self): pass class ToolQuit(ToolBase): description = 'Quit the figure' default_keymap = property(lambda self: mpl.rcParams['keymap.quit']) def trigger(self, sender, event, data=None): Gcf.destroy_fig(self.figure) class ToolQuitAll(ToolBase): description = 'Quit all figures' default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all']) def trigger(self, sender, event, data=None): Gcf.destroy_all() class ToolGrid(ToolBase): description = 'Toggle major grids' default_keymap = property(lambda self: mpl.rcParams['keymap.grid']) def trigger(self, sender, event, data=None): sentinel = str(uuid.uuid4()) with cbook._setattr_cm(event, key=sentinel), mpl.rc_context({'keymap.grid': sentinel}): mpl.backend_bases.key_press_handler(event, self.figure.canvas) class ToolMinorGrid(ToolBase): description = 'Toggle major and minor grids' default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor']) def trigger(self, sender, event, data=None): sentinel = str(uuid.uuid4()) with cbook._setattr_cm(event, key=sentinel), mpl.rc_context({'keymap.grid_minor': sentinel}): mpl.backend_bases.key_press_handler(event, self.figure.canvas) class ToolFullScreen(ToolBase): description = 'Toggle fullscreen mode' default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen']) def trigger(self, sender, event, data=None): self.figure.canvas.manager.full_screen_toggle() class AxisScaleBase(ToolToggleBase): def trigger(self, sender, event, data=None): if event.inaxes is None: return super().trigger(sender, event, data) def enable(self, event=None): self.set_scale(event.inaxes, 'log') self.figure.canvas.draw_idle() def disable(self, event=None): self.set_scale(event.inaxes, 'linear') self.figure.canvas.draw_idle() class ToolYScale(AxisScaleBase): description = 'Toggle scale Y axis' default_keymap = property(lambda self: mpl.rcParams['keymap.yscale']) def set_scale(self, ax, scale): ax.set_yscale(scale) class ToolXScale(AxisScaleBase): description = 'Toggle scale X axis' default_keymap = property(lambda self: mpl.rcParams['keymap.xscale']) def set_scale(self, ax, scale): ax.set_xscale(scale) class ToolViewsPositions(ToolBase): def __init__(self, *args, **kwargs): self.views = WeakKeyDictionary() self.positions = WeakKeyDictionary() self.home_views = WeakKeyDictionary() super().__init__(*args, **kwargs) def add_figure(self, figure): if figure not in self.views: self.views[figure] = cbook._Stack() self.positions[figure] = cbook._Stack() self.home_views[figure] = WeakKeyDictionary() self.push_current(figure) figure.add_axobserver(lambda fig: self.update_home_views(fig)) def clear(self, figure): if figure in self.views: self.views[figure].clear() self.positions[figure].clear() self.home_views[figure].clear() self.update_home_views() def update_view(self): views = self.views[self.figure]() if views is None: return pos = self.positions[self.figure]() if pos is None: return home_views = self.home_views[self.figure] all_axes = self.figure.get_axes() for a in all_axes: if a in views: cur_view = views[a] else: cur_view = home_views[a] a._set_view(cur_view) if set(all_axes).issubset(pos): for a in all_axes: a._set_position(pos[a][0], 'original') a._set_position(pos[a][1], 'active') self.figure.canvas.draw_idle() def push_current(self, figure=None): if not figure: figure = self.figure views = WeakKeyDictionary() pos = WeakKeyDictionary() for a in figure.get_axes(): views[a] = a._get_view() pos[a] = self._axes_pos(a) self.views[figure].push(views) self.positions[figure].push(pos) def _axes_pos(self, ax): return (ax.get_position(True).frozen(), ax.get_position().frozen()) def update_home_views(self, figure=None): if not figure: figure = self.figure for a in figure.get_axes(): if a not in self.home_views[figure]: self.home_views[figure][a] = a._get_view() def home(self): self.views[self.figure].home() self.positions[self.figure].home() def back(self): self.views[self.figure].back() self.positions[self.figure].back() def forward(self): self.views[self.figure].forward() self.positions[self.figure].forward() class ViewsPositionsBase(ToolBase): _on_trigger = None def trigger(self, sender, event, data=None): self.toolmanager.get_tool(_views_positions).add_figure(self.figure) getattr(self.toolmanager.get_tool(_views_positions), self._on_trigger)() self.toolmanager.get_tool(_views_positions).update_view() class ToolHome(ViewsPositionsBase): description = 'Reset original view' image = 'mpl-data/images/home' default_keymap = property(lambda self: mpl.rcParams['keymap.home']) _on_trigger = 'home' class ToolBack(ViewsPositionsBase): description = 'Back to previous view' image = 'mpl-data/images/back' default_keymap = property(lambda self: mpl.rcParams['keymap.back']) _on_trigger = 'back' class ToolForward(ViewsPositionsBase): description = 'Forward to next view' image = 'mpl-data/images/forward' default_keymap = property(lambda self: mpl.rcParams['keymap.forward']) _on_trigger = 'forward' class ConfigureSubplotsBase(ToolBase): description = 'Configure subplots' image = 'mpl-data/images/subplots' class SaveFigureBase(ToolBase): description = 'Save the figure' image = 'mpl-data/images/filesave' default_keymap = property(lambda self: mpl.rcParams['keymap.save']) class ZoomPanBase(ToolToggleBase): def __init__(self, *args): super().__init__(*args) self._button_pressed = None self._xypress = None self._idPress = None self._idRelease = None self._idScroll = None self.base_scale = 2.0 self.scrollthresh = 0.5 self.lastscroll = time.time() - self.scrollthresh def enable(self, event=None): self.figure.canvas.widgetlock(self) self._idPress = self.figure.canvas.mpl_connect('button_press_event', self._press) self._idRelease = self.figure.canvas.mpl_connect('button_release_event', self._release) self._idScroll = self.figure.canvas.mpl_connect('scroll_event', self.scroll_zoom) def disable(self, event=None): self._cancel_action() self.figure.canvas.widgetlock.release(self) self.figure.canvas.mpl_disconnect(self._idPress) self.figure.canvas.mpl_disconnect(self._idRelease) self.figure.canvas.mpl_disconnect(self._idScroll) def trigger(self, sender, event, data=None): self.toolmanager.get_tool(_views_positions).add_figure(self.figure) super().trigger(sender, event, data) new_navigate_mode = self.name.upper() if self.toggled else None for ax in self.figure.axes: ax.set_navigate_mode(new_navigate_mode) def scroll_zoom(self, event): if event.inaxes is None: return if event.button == 'up': scl = self.base_scale elif event.button == 'down': scl = 1 / self.base_scale else: scl = 1 ax = event.inaxes ax._set_view_from_bbox([event.x, event.y, scl]) if time.time() - self.lastscroll < self.scrollthresh: self.toolmanager.get_tool(_views_positions).back() self.figure.canvas.draw_idle() self.lastscroll = time.time() self.toolmanager.get_tool(_views_positions).push_current() class ToolZoom(ZoomPanBase): description = 'Zoom to rectangle' image = 'mpl-data/images/zoom_to_rect' default_keymap = property(lambda self: mpl.rcParams['keymap.zoom']) cursor = cursors.SELECT_REGION radio_group = 'default' def __init__(self, *args): super().__init__(*args) self._ids_zoom = [] def _cancel_action(self): for zoom_id in self._ids_zoom: self.figure.canvas.mpl_disconnect(zoom_id) self.toolmanager.trigger_tool('rubberband', self) self.figure.canvas.draw_idle() self._xypress = None self._button_pressed = None self._ids_zoom = [] return def _press(self, event): if self._ids_zoom: self._cancel_action() if event.button == 1: self._button_pressed = 1 elif event.button == 3: self._button_pressed = 3 else: self._cancel_action() return (x, y) = (event.x, event.y) self._xypress = [] for (i, a) in enumerate(self.figure.get_axes()): if x is not None and y is not None and a.in_axes(event) and a.get_navigate() and a.can_zoom(): self._xypress.append((x, y, a, i, a._get_view())) id1 = self.figure.canvas.mpl_connect('motion_notify_event', self._mouse_move) id2 = self.figure.canvas.mpl_connect('key_press_event', self._switch_on_zoom_mode) id3 = self.figure.canvas.mpl_connect('key_release_event', self._switch_off_zoom_mode) self._ids_zoom = (id1, id2, id3) self._zoom_mode = event.key def _switch_on_zoom_mode(self, event): self._zoom_mode = event.key self._mouse_move(event) def _switch_off_zoom_mode(self, event): self._zoom_mode = None self._mouse_move(event) def _mouse_move(self, event): if self._xypress: (x, y) = (event.x, event.y) (lastx, lasty, a, ind, view) = self._xypress[0] ((x1, y1), (x2, y2)) = np.clip([[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max) if self._zoom_mode == 'x': (y1, y2) = a.bbox.intervaly elif self._zoom_mode == 'y': (x1, x2) = a.bbox.intervalx self.toolmanager.trigger_tool('rubberband', self, data=(x1, y1, x2, y2)) def _release(self, event): for zoom_id in self._ids_zoom: self.figure.canvas.mpl_disconnect(zoom_id) self._ids_zoom = [] if not self._xypress: self._cancel_action() return done_ax = [] for cur_xypress in self._xypress: (x, y) = (event.x, event.y) (lastx, lasty, a, _ind, view) = cur_xypress if abs(x - lastx) < 5 or abs(y - lasty) < 5: self._cancel_action() return twinx = any((a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)) twiny = any((a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)) done_ax.append(a) if self._button_pressed == 1: direction = 'in' elif self._button_pressed == 3: direction = 'out' else: continue a._set_view_from_bbox((lastx, lasty, x, y), direction, self._zoom_mode, twinx, twiny) self._zoom_mode = None self.toolmanager.get_tool(_views_positions).push_current() self._cancel_action() class ToolPan(ZoomPanBase): default_keymap = property(lambda self: mpl.rcParams['keymap.pan']) description = 'Pan axes with left mouse, zoom with right' image = 'mpl-data/images/move' cursor = cursors.MOVE radio_group = 'default' def __init__(self, *args): super().__init__(*args) self._id_drag = None def _cancel_action(self): self._button_pressed = None self._xypress = [] self.figure.canvas.mpl_disconnect(self._id_drag) self.toolmanager.messagelock.release(self) self.figure.canvas.draw_idle() def _press(self, event): if event.button == 1: self._button_pressed = 1 elif event.button == 3: self._button_pressed = 3 else: self._cancel_action() return (x, y) = (event.x, event.y) self._xypress = [] for (i, a) in enumerate(self.figure.get_axes()): if x is not None and y is not None and a.in_axes(event) and a.get_navigate() and a.can_pan(): a.start_pan(x, y, event.button) self._xypress.append((a, i)) self.toolmanager.messagelock(self) self._id_drag = self.figure.canvas.mpl_connect('motion_notify_event', self._mouse_move) def _release(self, event): if self._button_pressed is None: self._cancel_action() return self.figure.canvas.mpl_disconnect(self._id_drag) self.toolmanager.messagelock.release(self) for (a, _ind) in self._xypress: a.end_pan() if not self._xypress: self._cancel_action() return self.toolmanager.get_tool(_views_positions).push_current() self._cancel_action() def _mouse_move(self, event): for (a, _ind) in self._xypress: a.drag_pan(self._button_pressed, event.key, event.x, event.y) self.toolmanager.canvas.draw_idle() class ToolHelpBase(ToolBase): description = 'Print tool list, shortcuts and description' default_keymap = property(lambda self: mpl.rcParams['keymap.help']) image = 'mpl-data/images/help' @staticmethod def format_shortcut(key_sequence): return key_sequence if len(key_sequence) == 1 else re.sub('\\+[A-Z]', '+Shift\\g<0>', key_sequence).title() def _format_tool_keymap(self, name): keymaps = self.toolmanager.get_tool_keymap(name) return ', '.join((self.format_shortcut(keymap) for keymap in keymaps)) def _get_help_entries(self): return [(name, self._format_tool_keymap(name), tool.description) for (name, tool) in sorted(self.toolmanager.tools.items()) if tool.description] def _get_help_text(self): entries = self._get_help_entries() entries = ['{}: {}\n\t{}'.format(*entry) for entry in entries] return '\n'.join(entries) def _get_help_html(self): fmt = '{}{}{}' rows = [fmt.format('Action', 'Shortcuts', 'Description')] rows += [fmt.format(*row) for row in self._get_help_entries()] return '' + rows[0] + ''.join(rows[1:]) + '
' class ToolCopyToClipboardBase(ToolBase): description = 'Copy the canvas figure to clipboard' default_keymap = property(lambda self: mpl.rcParams['keymap.copy']) def trigger(self, *args, **kwargs): message = 'Copy tool is not available' self.toolmanager.message_event(message, self) default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward, 'zoom': ToolZoom, 'pan': ToolPan, 'subplots': ConfigureSubplotsBase, 'save': SaveFigureBase, 'grid': ToolGrid, 'grid_minor': ToolMinorGrid, 'fullscreen': ToolFullScreen, 'quit': ToolQuit, 'quit_all': ToolQuitAll, 'xscale': ToolXScale, 'yscale': ToolYScale, 'position': ToolCursorPosition, _views_positions: ToolViewsPositions, 'cursor': ToolSetCursor, 'rubberband': RubberbandBase, 'help': ToolHelpBase, 'copy': ToolCopyToClipboardBase} default_toolbar_tools = [['navigation', ['home', 'back', 'forward']], ['zoompan', ['pan', 'zoom', 'subplots']], ['io', ['save', 'help']]] def add_tools_to_manager(toolmanager, tools=default_tools): for (name, tool) in tools.items(): toolmanager.add_tool(name, tool) def add_tools_to_container(container, tools=default_toolbar_tools): for (group, grouptools) in tools: for (position, tool) in enumerate(grouptools): container.add_tool(tool, group, position) # File: matplotlib-main/lib/matplotlib/backends/_backend_gtk.py """""" import logging import sys import matplotlib as mpl from matplotlib import _api, backend_tools, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase from matplotlib.backend_tools import Cursors import gi from gi.repository import Gdk, Gio, GLib, Gtk try: gi.require_foreign('cairo') except ImportError as e: raise ImportError('Gtk-based backends require cairo') from e _log = logging.getLogger(__name__) _application = None def _shutdown_application(app): for win in app.get_windows(): win.close() app._created_by_matplotlib = True global _application _application = None def _create_application(): global _application if _application is None: app = Gio.Application.get_default() if app is None or getattr(app, '_created_by_matplotlib', False): if not mpl._c_internal_utils.display_is_valid(): raise RuntimeError('Invalid DISPLAY variable') _application = Gtk.Application.new('org.matplotlib.Matplotlib3', Gio.ApplicationFlags.NON_UNIQUE) _application.connect('activate', lambda *args, **kwargs: None) _application.connect('shutdown', _shutdown_application) _application.register() cbook._setup_new_guiapp() else: _application = app return _application def mpl_to_gtk_cursor_name(mpl_cursor): return _api.check_getitem({Cursors.MOVE: 'move', Cursors.HAND: 'pointer', Cursors.POINTER: 'default', Cursors.SELECT_REGION: 'crosshair', Cursors.WAIT: 'wait', Cursors.RESIZE_HORIZONTAL: 'ew-resize', Cursors.RESIZE_VERTICAL: 'ns-resize'}, cursor=mpl_cursor) class TimerGTK(TimerBase): def __init__(self, *args, **kwargs): self._timer = None super().__init__(*args, **kwargs) def _timer_start(self): self._timer_stop() self._timer = GLib.timeout_add(self._interval, self._on_timer) def _timer_stop(self): if self._timer is not None: GLib.source_remove(self._timer) self._timer = None def _timer_set_interval(self): if self._timer is not None: self._timer_stop() self._timer_start() def _on_timer(self): super()._on_timer() if self.callbacks and (not self._single): return True else: self._timer = None return False class _FigureCanvasGTK(FigureCanvasBase): _timer_cls = TimerGTK class _FigureManagerGTK(FigureManagerBase): def __init__(self, canvas, num): self._gtk_ver = gtk_ver = Gtk.get_major_version() app = _create_application() self.window = Gtk.Window() app.add_window(self.window) super().__init__(canvas, num) if gtk_ver == 3: self.window.set_wmclass('matplotlib', 'Matplotlib') icon_ext = 'png' if sys.platform == 'win32' else 'svg' self.window.set_icon_from_file(str(cbook._get_data_path(f'images/matplotlib.{icon_ext}'))) self.vbox = Gtk.Box() self.vbox.set_property('orientation', Gtk.Orientation.VERTICAL) if gtk_ver == 3: self.window.add(self.vbox) self.vbox.show() self.canvas.show() self.vbox.pack_start(self.canvas, True, True, 0) elif gtk_ver == 4: self.window.set_child(self.vbox) self.vbox.prepend(self.canvas) (w, h) = self.canvas.get_width_height() if self.toolbar is not None: if gtk_ver == 3: self.toolbar.show() self.vbox.pack_end(self.toolbar, False, False, 0) elif gtk_ver == 4: sw = Gtk.ScrolledWindow(vscrollbar_policy=Gtk.PolicyType.NEVER) sw.set_child(self.toolbar) self.vbox.append(sw) (min_size, nat_size) = self.toolbar.get_preferred_size() h += nat_size.height self.window.set_default_size(w, h) self._destroying = False self.window.connect('destroy', lambda *args: Gcf.destroy(self)) self.window.connect({3: 'delete_event', 4: 'close-request'}[gtk_ver], lambda *args: Gcf.destroy(self)) if mpl.is_interactive(): self.window.show() self.canvas.draw_idle() self.canvas.grab_focus() def destroy(self, *args): if self._destroying: return self._destroying = True self.window.destroy() self.canvas.destroy() @classmethod def start_main_loop(cls): global _application if _application is None: return try: _application.run() except KeyboardInterrupt: context = GLib.MainContext.default() while context.pending(): context.iteration(True) raise finally: _application = None def show(self): self.window.show() self.canvas.draw() if mpl.rcParams['figure.raise_window']: meth_name = {3: 'get_window', 4: 'get_surface'}[self._gtk_ver] if getattr(self.window, meth_name)(): self.window.present() else: _api.warn_external('Cannot raise window yet to be setup') def full_screen_toggle(self): is_fullscreen = {3: lambda w: w.get_window().get_state() & Gdk.WindowState.FULLSCREEN, 4: lambda w: w.is_fullscreen()}[self._gtk_ver] if is_fullscreen(self.window): self.window.unfullscreen() else: self.window.fullscreen() def get_window_title(self): return self.window.get_title() def set_window_title(self, title): self.window.set_title(title) def resize(self, width, height): width = int(width / self.canvas.device_pixel_ratio) height = int(height / self.canvas.device_pixel_ratio) if self.toolbar: (min_size, nat_size) = self.toolbar.get_preferred_size() height += nat_size.height canvas_size = self.canvas.get_allocation() if self._gtk_ver >= 4 or canvas_size.width == canvas_size.height == 1: self.window.set_default_size(width, height) else: self.window.resize(width, height) class _NavigationToolbar2GTK(NavigationToolbar2): def set_message(self, s): escaped = GLib.markup_escape_text(s) self.message.set_markup(f'{escaped}') def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas._draw_rubberband(rect) def remove_rubberband(self): self.canvas._draw_rubberband(None) def _update_buttons_checked(self): for (name, active) in [('Pan', 'PAN'), ('Zoom', 'ZOOM')]: button = self._gtk_ids.get(name) if button: with button.handler_block(button._signal_handler): button.set_active(self.mode.name == active) def pan(self, *args): super().pan(*args) self._update_buttons_checked() def zoom(self, *args): super().zoom(*args) self._update_buttons_checked() def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 if 'Back' in self._gtk_ids: self._gtk_ids['Back'].set_sensitive(can_backward) if 'Forward' in self._gtk_ids: self._gtk_ids['Forward'].set_sensitive(can_forward) class RubberbandGTK(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): _NavigationToolbar2GTK.draw_rubberband(self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): _NavigationToolbar2GTK.remove_rubberband(self._make_classic_style_pseudo_toolbar()) class ConfigureSubplotsGTK(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): _NavigationToolbar2GTK.configure_subplots(self, None) class _BackendGTK(_Backend): backend_version = '{}.{}.{}'.format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()) mainloop = _FigureManagerGTK.start_main_loop # File: matplotlib-main/lib/matplotlib/backends/_backend_pdf_ps.py """""" from io import BytesIO import functools from fontTools import subset import matplotlib as mpl from .. import font_manager, ft2font from .._afm import AFM from ..backend_bases import RendererBase @functools.lru_cache(50) def _cached_get_afm_from_fname(fname): with open(fname, 'rb') as fh: return AFM(fh) def get_glyphs_subset(fontfile, characters): options = subset.Options(glyph_names=True, recommended_glyphs=True) options.drop_tables += ['FFTM', 'PfEd', 'BDF', 'meta'] if fontfile.endswith('.ttc'): options.font_number = 0 with subset.load_font(fontfile, options) as font: subsetter = subset.Subsetter(options=options) subsetter.populate(text=characters) subsetter.subset(font) fh = BytesIO() font.save(fh, reorderTables=False) return fh class CharacterTracker: def __init__(self): self.used = {} def track(self, font, s): char_to_font = font._get_fontmap(s) for (_c, _f) in char_to_font.items(): self.used.setdefault(_f.fname, set()).add(ord(_c)) def track_glyph(self, font, glyph): self.used.setdefault(font.fname, set()).add(glyph) class RendererPDFPSBase(RendererBase): def __init__(self, width, height): super().__init__() self.width = width self.height = height def flipy(self): return False def option_scale_image(self): return True def option_image_nocomposite(self): return not mpl.rcParams['image.composite_image'] def get_canvas_width_height(self): return (self.width * 72.0, self.height * 72.0) def get_text_width_height_descent(self, s, prop, ismath): if ismath == 'TeX': return super().get_text_width_height_descent(s, prop, ismath) elif ismath: parse = self._text2path.mathtext_parser.parse(s, 72, prop) return (parse.width, parse.height, parse.depth) elif mpl.rcParams[self._use_afm_rc_name]: font = self._get_font_afm(prop) (l, b, w, h, d) = font.get_str_bbox_and_descent(s) scale = prop.get_size_in_points() / 1000 w *= scale h *= scale d *= scale return (w, h, d) else: font = self._get_font_ttf(prop) font.set_text(s, 0.0, flags=ft2font.LOAD_NO_HINTING) (w, h) = font.get_width_height() d = font.get_descent() scale = 1 / 64 w *= scale h *= scale d *= scale return (w, h, d) def _get_font_afm(self, prop): fname = font_manager.findfont(prop, fontext='afm', directory=self._afm_font_dir) return _cached_get_afm_from_fname(fname) def _get_font_ttf(self, prop): fnames = font_manager.fontManager._find_fonts_by_props(prop) font = font_manager.get_font(fnames) font.clear() font.set_size(prop.get_size_in_points(), 72) return font # File: matplotlib-main/lib/matplotlib/backends/_backend_tk.py import uuid import weakref from contextlib import contextmanager import logging import math import os.path import pathlib import sys import tkinter as tk import tkinter.filedialog import tkinter.font import tkinter.messagebox from tkinter.simpledialog import SimpleDialog import numpy as np from PIL import Image, ImageTk import matplotlib as mpl from matplotlib import _api, backend_tools, cbook, _c_internal_utils from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, ToolContainerBase, cursors, _Mode, CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent from matplotlib._pylab_helpers import Gcf from . import _tkagg from ._tkagg import TK_PHOTO_COMPOSITE_OVERLAY, TK_PHOTO_COMPOSITE_SET _log = logging.getLogger(__name__) cursord = {cursors.MOVE: 'fleur', cursors.HAND: 'hand2', cursors.POINTER: 'arrow', cursors.SELECT_REGION: 'crosshair', cursors.WAIT: 'watch', cursors.RESIZE_HORIZONTAL: 'sb_h_double_arrow', cursors.RESIZE_VERTICAL: 'sb_v_double_arrow'} @contextmanager def _restore_foreground_window_at_end(): foreground = _c_internal_utils.Win32_GetForegroundWindow() try: yield finally: if foreground and mpl.rcParams['tk.window_focus']: _c_internal_utils.Win32_SetForegroundWindow(foreground) _blit_args = {} _blit_tcl_name = 'mpl_blit_' + uuid.uuid4().hex def _blit(argsid): (photoimage, data, offsets, bbox, comp_rule) = _blit_args.pop(argsid) if not photoimage.tk.call('info', 'commands', photoimage): return _tkagg.blit(photoimage.tk.interpaddr(), str(photoimage), data, comp_rule, offsets, bbox) def blit(photoimage, aggimage, offsets, bbox=None): data = np.asarray(aggimage) (height, width) = data.shape[:2] if bbox is not None: ((x1, y1), (x2, y2)) = bbox.__array__() x1 = max(math.floor(x1), 0) x2 = min(math.ceil(x2), width) y1 = max(math.floor(y1), 0) y2 = min(math.ceil(y2), height) if x1 > x2 or y1 > y2: return bboxptr = (x1, x2, y1, y2) comp_rule = TK_PHOTO_COMPOSITE_OVERLAY else: bboxptr = (0, width, 0, height) comp_rule = TK_PHOTO_COMPOSITE_SET args = (photoimage, data, offsets, bboxptr, comp_rule) argsid = str(id(args)) _blit_args[argsid] = args try: photoimage.tk.call(_blit_tcl_name, argsid) except tk.TclError as e: if 'invalid command name' not in str(e): raise photoimage.tk.createcommand(_blit_tcl_name, _blit) photoimage.tk.call(_blit_tcl_name, argsid) class TimerTk(TimerBase): def __init__(self, parent, *args, **kwargs): self._timer = None super().__init__(*args, **kwargs) self.parent = parent def _timer_start(self): self._timer_stop() self._timer = self.parent.after(self._interval, self._on_timer) def _timer_stop(self): if self._timer is not None: self.parent.after_cancel(self._timer) self._timer = None def _on_timer(self): super()._on_timer() if not self._single and self._timer: if self._interval > 0: self._timer = self.parent.after(self._interval, self._on_timer) else: self._timer = self.parent.after_idle(lambda : self.parent.after(self._interval, self._on_timer)) else: self._timer = None class FigureCanvasTk(FigureCanvasBase): required_interactive_framework = 'tk' manager_class = _api.classproperty(lambda cls: FigureManagerTk) def __init__(self, figure=None, master=None): super().__init__(figure) self._idle_draw_id = None self._event_loop_id = None (w, h) = self.get_width_height(physical=True) self._tkcanvas = tk.Canvas(master=master, background='white', width=w, height=h, borderwidth=0, highlightthickness=0) self._tkphoto = tk.PhotoImage(master=self._tkcanvas, width=w, height=h) self._tkcanvas_image_region = self._tkcanvas.create_image(w // 2, h // 2, image=self._tkphoto) self._tkcanvas.bind('', self.resize) if sys.platform == 'win32': self._tkcanvas.bind('', self._update_device_pixel_ratio) self._tkcanvas.bind('', self.key_press) self._tkcanvas.bind('', self.motion_notify_event) self._tkcanvas.bind('', self.enter_notify_event) self._tkcanvas.bind('', self.leave_notify_event) self._tkcanvas.bind('', self.key_release) for name in ['', '', '']: self._tkcanvas.bind(name, self.button_press_event) for name in ['', '', '']: self._tkcanvas.bind(name, self.button_dblclick_event) for name in ['', '', '']: self._tkcanvas.bind(name, self.button_release_event) for name in ('', ''): self._tkcanvas.bind(name, self.scroll_event) root = self._tkcanvas.winfo_toplevel() weakself = weakref.ref(self) weakroot = weakref.ref(root) def scroll_event_windows(event): self = weakself() if self is None: root = weakroot() if root is not None: root.unbind('', scroll_event_windows_id) return return self.scroll_event_windows(event) scroll_event_windows_id = root.bind('', scroll_event_windows, '+') def filter_destroy(event): self = weakself() if self is None: root = weakroot() if root is not None: root.unbind('', filter_destroy_id) return if event.widget is self._tkcanvas: CloseEvent('close_event', self)._process() filter_destroy_id = root.bind('', filter_destroy, '+') self._tkcanvas.focus_set() self._rubberband_rect_black = None self._rubberband_rect_white = None def _update_device_pixel_ratio(self, event=None): ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2) if self._set_device_pixel_ratio(ratio): (w, h) = self.get_width_height(physical=True) self._tkcanvas.configure(width=w, height=h) def resize(self, event): (width, height) = (event.width, event.height) dpival = self.figure.dpi winch = width / dpival hinch = height / dpival self.figure.set_size_inches(winch, hinch, forward=False) self._tkcanvas.delete(self._tkcanvas_image_region) self._tkphoto.configure(width=int(width), height=int(height)) self._tkcanvas_image_region = self._tkcanvas.create_image(int(width / 2), int(height / 2), image=self._tkphoto) ResizeEvent('resize_event', self)._process() self.draw_idle() def draw_idle(self): if self._idle_draw_id: return def idle_draw(*args): try: self.draw() finally: self._idle_draw_id = None self._idle_draw_id = self._tkcanvas.after_idle(idle_draw) def get_tk_widget(self): return self._tkcanvas def _event_mpl_coords(self, event): return (self._tkcanvas.canvasx(event.x), self.figure.bbox.height - self._tkcanvas.canvasy(event.y)) def motion_notify_event(self, event): MouseEvent('motion_notify_event', self, *self._event_mpl_coords(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def enter_notify_event(self, event): LocationEvent('figure_enter_event', self, *self._event_mpl_coords(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def leave_notify_event(self, event): LocationEvent('figure_leave_event', self, *self._event_mpl_coords(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def button_press_event(self, event, dblclick=False): self._tkcanvas.focus_set() num = getattr(event, 'num', None) if sys.platform == 'darwin': num = {2: 3, 3: 2}.get(num, num) MouseEvent('button_press_event', self, *self._event_mpl_coords(event), num, dblclick=dblclick, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def button_dblclick_event(self, event): self.button_press_event(event, dblclick=True) def button_release_event(self, event): num = getattr(event, 'num', None) if sys.platform == 'darwin': num = {2: 3, 3: 2}.get(num, num) MouseEvent('button_release_event', self, *self._event_mpl_coords(event), num, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def scroll_event(self, event): num = getattr(event, 'num', None) step = 1 if num == 4 else -1 if num == 5 else 0 MouseEvent('scroll_event', self, *self._event_mpl_coords(event), step=step, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def scroll_event_windows(self, event): w = event.widget.winfo_containing(event.x_root, event.y_root) if w != self._tkcanvas: return x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx()) y = self.figure.bbox.height - self._tkcanvas.canvasy(event.y_root - w.winfo_rooty()) step = event.delta / 120 MouseEvent('scroll_event', self, x, y, step=step, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() @staticmethod def _mpl_modifiers(event, *, exclude=None): modifiers = [('ctrl', 1 << 2, 'control'), ('alt', 1 << 17, 'alt'), ('shift', 1 << 0, 'shift')] if sys.platform == 'win32' else [('ctrl', 1 << 2, 'control'), ('alt', 1 << 4, 'alt'), ('shift', 1 << 0, 'shift'), ('cmd', 1 << 3, 'cmd')] if sys.platform == 'darwin' else [('ctrl', 1 << 2, 'control'), ('alt', 1 << 3, 'alt'), ('shift', 1 << 0, 'shift'), ('super', 1 << 6, 'super')] return [name for (name, mask, key) in modifiers if event.state & mask and exclude != key] def _get_key(self, event): unikey = event.char key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym) if key is not None: mods = self._mpl_modifiers(event, exclude=key) if 'shift' in mods and unikey: mods.remove('shift') return '+'.join([*mods, key]) def key_press(self, event): KeyEvent('key_press_event', self, self._get_key(event), *self._event_mpl_coords(event), guiEvent=event)._process() def key_release(self, event): KeyEvent('key_release_event', self, self._get_key(event), *self._event_mpl_coords(event), guiEvent=event)._process() def new_timer(self, *args, **kwargs): return TimerTk(self._tkcanvas, *args, **kwargs) def flush_events(self): self._tkcanvas.update() def start_event_loop(self, timeout=0): if timeout > 0: milliseconds = int(1000 * timeout) if milliseconds > 0: self._event_loop_id = self._tkcanvas.after(milliseconds, self.stop_event_loop) else: self._event_loop_id = self._tkcanvas.after_idle(self.stop_event_loop) self._tkcanvas.mainloop() def stop_event_loop(self): if self._event_loop_id: self._tkcanvas.after_cancel(self._event_loop_id) self._event_loop_id = None self._tkcanvas.quit() def set_cursor(self, cursor): try: self._tkcanvas.configure(cursor=cursord[cursor]) except tkinter.TclError: pass class FigureManagerTk(FigureManagerBase): _owns_mainloop = False def __init__(self, canvas, num, window): self.window = window super().__init__(canvas, num) self.window.withdraw() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) window_frame = int(window.wm_frame(), 16) self._window_dpi = tk.IntVar(master=window, value=96, name=f'window_dpi{window_frame}') self._window_dpi_cbname = '' if _tkagg.enable_dpi_awareness(window_frame, window.tk.interpaddr()): self._window_dpi_cbname = self._window_dpi.trace_add('write', self._update_window_dpi) self._shown = False @classmethod def create_with_canvas(cls, canvas_class, figure, num): with _restore_foreground_window_at_end(): if cbook._get_running_interactive_framework() is None: cbook._setup_new_guiapp() _c_internal_utils.Win32_SetProcessDpiAwareness_max() window = tk.Tk(className='matplotlib') window.withdraw() icon_fname = str(cbook._get_data_path('images/matplotlib.png')) icon_img = ImageTk.PhotoImage(file=icon_fname, master=window) icon_fname_large = str(cbook._get_data_path('images/matplotlib_large.png')) icon_img_large = ImageTk.PhotoImage(file=icon_fname_large, master=window) window.iconphoto(False, icon_img_large, icon_img) canvas = canvas_class(figure, master=window) manager = cls(canvas, num, window) if mpl.is_interactive(): manager.show() canvas.draw_idle() return manager @classmethod def start_main_loop(cls): managers = Gcf.get_all_fig_managers() if managers: first_manager = managers[0] manager_class = type(first_manager) if manager_class._owns_mainloop: return manager_class._owns_mainloop = True try: first_manager.window.mainloop() finally: manager_class._owns_mainloop = False def _update_window_dpi(self, *args): newdpi = self._window_dpi.get() self.window.call('tk', 'scaling', newdpi / 72) if self.toolbar and hasattr(self.toolbar, '_rescale'): self.toolbar._rescale() self.canvas._update_device_pixel_ratio() def resize(self, width, height): max_size = 1400000 if (width > max_size or height > max_size) and sys.platform == 'linux': raise ValueError(f'You have requested to resize the Tk window to ({width}, {height}), one of which is bigger than {max_size}. At larger sizes xorg will either exit with an error on newer versions (~1.20) or cause corruption on older version (~1.19). We do not expect a window over a million pixel wide or tall to be intended behavior.') self.canvas._tkcanvas.configure(width=width, height=height) def show(self): with _restore_foreground_window_at_end(): if not self._shown: def destroy(*args): Gcf.destroy(self) self.window.protocol('WM_DELETE_WINDOW', destroy) self.window.deiconify() self.canvas._tkcanvas.focus_set() else: self.canvas.draw_idle() if mpl.rcParams['figure.raise_window']: self.canvas.manager.window.attributes('-topmost', 1) self.canvas.manager.window.attributes('-topmost', 0) self._shown = True def destroy(self, *args): if self.canvas._idle_draw_id: self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id) if self.canvas._event_loop_id: self.canvas._tkcanvas.after_cancel(self.canvas._event_loop_id) if self._window_dpi_cbname: self._window_dpi.trace_remove('write', self._window_dpi_cbname) def delayed_destroy(): self.window.destroy() if self._owns_mainloop and (not Gcf.get_num_fig_managers()): self.window.quit() if cbook._get_running_interactive_framework() == 'tk': self.window.after_idle(self.window.after, 0, delayed_destroy) else: self.window.update() delayed_destroy() def get_window_title(self): return self.window.wm_title() def set_window_title(self, title): self.window.wm_title(title) def full_screen_toggle(self): is_fullscreen = bool(self.window.attributes('-fullscreen')) self.window.attributes('-fullscreen', not is_fullscreen) class NavigationToolbar2Tk(NavigationToolbar2, tk.Frame): def __init__(self, canvas, window=None, *, pack_toolbar=True): if window is None: window = canvas.get_tk_widget().master tk.Frame.__init__(self, master=window, borderwidth=2, width=int(canvas.figure.bbox.width), height=50) self._buttons = {} for (text, tooltip_text, image_file, callback) in self.toolitems: if text is None: self._Spacer() else: self._buttons[text] = button = self._Button(text, str(cbook._get_data_path(f'images/{image_file}.png')), toggle=callback in ['zoom', 'pan'], command=getattr(self, callback)) if tooltip_text is not None: add_tooltip(button, tooltip_text) self._label_font = tkinter.font.Font(root=window, size=10) label = tk.Label(master=self, font=self._label_font, text='\xa0\n\xa0') label.pack(side=tk.RIGHT) self.message = tk.StringVar(master=self) self._message_label = tk.Label(master=self, font=self._label_font, textvariable=self.message, justify=tk.RIGHT) self._message_label.pack(side=tk.RIGHT) NavigationToolbar2.__init__(self, canvas) if pack_toolbar: self.pack(side=tk.BOTTOM, fill=tk.X) def _rescale(self): for widget in self.winfo_children(): if isinstance(widget, (tk.Button, tk.Checkbutton)): if hasattr(widget, '_image_file'): NavigationToolbar2Tk._set_image_for_button(self, widget) else: pass elif isinstance(widget, tk.Frame): widget.configure(height='18p') widget.pack_configure(padx='3p') elif isinstance(widget, tk.Label): pass else: _log.warning('Unknown child class %s', widget.winfo_class) self._label_font.configure(size=10) def _update_buttons_checked(self): for (text, mode) in [('Zoom', _Mode.ZOOM), ('Pan', _Mode.PAN)]: if text in self._buttons: if self.mode == mode: self._buttons[text].select() else: self._buttons[text].deselect() def pan(self, *args): super().pan(*args) self._update_buttons_checked() def zoom(self, *args): super().zoom(*args) self._update_buttons_checked() def set_message(self, s): self.message.set(s) def draw_rubberband(self, event, x0, y0, x1, y1): if self.canvas._rubberband_rect_white: self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white) if self.canvas._rubberband_rect_black: self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black) height = self.canvas.figure.bbox.height y0 = height - y0 y1 = height - y1 self.canvas._rubberband_rect_black = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1) self.canvas._rubberband_rect_white = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1, outline='white', dash=(3, 3)) def remove_rubberband(self): if self.canvas._rubberband_rect_white: self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white) self.canvas._rubberband_rect_white = None if self.canvas._rubberband_rect_black: self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black) self.canvas._rubberband_rect_black = None def _set_image_for_button(self, button): if button._image_file is None: return path_regular = cbook._get_data_path('images', button._image_file) path_large = path_regular.with_name(path_regular.name.replace('.png', '_large.png')) size = button.winfo_pixels('18p') def _get_color(color_name): return button.winfo_rgb(button.cget(color_name)) def _is_dark(color): if isinstance(color, str): color = _get_color(color) return max(color) < 65535 / 2 def _recolor_icon(image, color): image_data = np.asarray(image).copy() black_mask = (image_data[..., :3] == 0).all(axis=-1) image_data[black_mask, :3] = color return Image.fromarray(image_data, mode='RGBA') with Image.open(path_large if size > 24 and path_large.exists() else path_regular) as im: im = im.convert('RGBA') image = ImageTk.PhotoImage(im.resize((size, size)), master=self) button._ntimage = image foreground = 255 / 65535 * np.array(button.winfo_rgb(button.cget('foreground'))) im_alt = _recolor_icon(im, foreground) image_alt = ImageTk.PhotoImage(im_alt.resize((size, size)), master=self) button._ntimage_alt = image_alt if _is_dark('background'): image_kwargs = {'image': image_alt} else: image_kwargs = {'image': image} if isinstance(button, tk.Checkbutton) and button.cget('selectcolor') != '': if self._windowingsystem != 'x11': selectcolor = 'selectcolor' else: (r1, g1, b1) = _get_color('selectcolor') (r2, g2, b2) = _get_color('activebackground') selectcolor = ((r1 + r2) / 2, (g1 + g2) / 2, (b1 + b2) / 2) if _is_dark(selectcolor): image_kwargs['selectimage'] = image_alt else: image_kwargs['selectimage'] = image button.configure(**image_kwargs, height='18p', width='18p') def _Button(self, text, image_file, toggle, command): if not toggle: b = tk.Button(master=self, text=text, command=command, relief='flat', overrelief='groove', borderwidth=1) else: var = tk.IntVar(master=self) b = tk.Checkbutton(master=self, text=text, command=command, indicatoron=False, variable=var, offrelief='flat', overrelief='groove', borderwidth=1) b.var = var b._image_file = image_file if image_file is not None: NavigationToolbar2Tk._set_image_for_button(self, b) else: b.configure(font=self._label_font) b.pack(side=tk.LEFT) return b def _Spacer(self): s = tk.Frame(master=self, height='18p', relief=tk.RIDGE, bg='DarkGray') s.pack(side=tk.LEFT, padx='3p') return s def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() tk_filetypes = [(name, ' '.join((f'*.{ext}' for ext in exts))) for (name, exts) in sorted(filetypes.items())] default_extension = self.canvas.get_default_filetype() default_filetype = self.canvas.get_supported_filetypes()[default_extension] filetype_variable = tk.StringVar(self.canvas.get_tk_widget(), default_filetype) defaultextension = '' initialdir = os.path.expanduser(mpl.rcParams['savefig.directory']) initialfile = pathlib.Path(self.canvas.get_default_filename()).stem fname = tkinter.filedialog.asksaveasfilename(master=self.canvas.get_tk_widget().master, title='Save the figure', filetypes=tk_filetypes, defaultextension=defaultextension, initialdir=initialdir, initialfile=initialfile, typevariable=filetype_variable) if fname in ['', ()]: return if initialdir != '': mpl.rcParams['savefig.directory'] = os.path.dirname(str(fname)) if pathlib.Path(fname).suffix[1:] != '': extension = None else: extension = filetypes[filetype_variable.get()][0] try: self.canvas.figure.savefig(fname, format=extension) except Exception as e: tkinter.messagebox.showerror('Error saving file', str(e)) def set_history_buttons(self): state_map = {True: tk.NORMAL, False: tk.DISABLED} can_back = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 if 'Back' in self._buttons: self._buttons['Back']['state'] = state_map[can_back] if 'Forward' in self._buttons: self._buttons['Forward']['state'] = state_map[can_forward] def add_tooltip(widget, text): tipwindow = None def showtip(event): nonlocal tipwindow if tipwindow or not text: return (x, y, _, _) = widget.bbox('insert') x = x + widget.winfo_rootx() + widget.winfo_width() y = y + widget.winfo_rooty() tipwindow = tk.Toplevel(widget) tipwindow.overrideredirect(1) tipwindow.geometry(f'+{x}+{y}') try: tipwindow.tk.call('::tk::unsupported::MacWindowStyle', 'style', tipwindow._w, 'help', 'noActivates') except tk.TclError: pass label = tk.Label(tipwindow, text=text, justify=tk.LEFT, relief=tk.SOLID, borderwidth=1) label.pack(ipadx=1) def hidetip(event): nonlocal tipwindow if tipwindow: tipwindow.destroy() tipwindow = None widget.bind('', showtip) widget.bind('', hidetip) @backend_tools._register_tool_class(FigureCanvasTk) class RubberbandTk(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): NavigationToolbar2Tk.draw_rubberband(self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): NavigationToolbar2Tk.remove_rubberband(self._make_classic_style_pseudo_toolbar()) class ToolbarTk(ToolContainerBase, tk.Frame): def __init__(self, toolmanager, window=None): ToolContainerBase.__init__(self, toolmanager) if window is None: window = self.toolmanager.canvas.get_tk_widget().master (xmin, xmax) = self.toolmanager.canvas.figure.bbox.intervalx (height, width) = (50, xmax - xmin) tk.Frame.__init__(self, master=window, width=int(width), height=int(height), borderwidth=2) self._label_font = tkinter.font.Font(size=10) label = tk.Label(master=self, font=self._label_font, text='\xa0\n\xa0') label.pack(side=tk.RIGHT) self._message = tk.StringVar(master=self) self._message_label = tk.Label(master=self, font=self._label_font, textvariable=self._message) self._message_label.pack(side=tk.RIGHT) self._toolitems = {} self.pack(side=tk.TOP, fill=tk.X) self._groups = {} def _rescale(self): return NavigationToolbar2Tk._rescale(self) def add_toolitem(self, name, group, position, image_file, description, toggle): frame = self._get_groupframe(group) buttons = frame.pack_slaves() if position >= len(buttons) or position < 0: before = None else: before = buttons[position] button = NavigationToolbar2Tk._Button(frame, name, image_file, toggle, lambda : self._button_click(name)) button.pack_configure(before=before) if description is not None: add_tooltip(button, description) self._toolitems.setdefault(name, []) self._toolitems[name].append(button) def _get_groupframe(self, group): if group not in self._groups: if self._groups: self._add_separator() frame = tk.Frame(master=self, borderwidth=0) frame.pack(side=tk.LEFT, fill=tk.Y) frame._label_font = self._label_font self._groups[group] = frame return self._groups[group] def _add_separator(self): return NavigationToolbar2Tk._Spacer(self) def _button_click(self, name): self.trigger_tool(name) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for toolitem in self._toolitems[name]: if toggled: toolitem.select() else: toolitem.deselect() def remove_toolitem(self, name): for toolitem in self._toolitems.pop(name, []): toolitem.pack_forget() def set_message(self, s): self._message.set(s) @backend_tools._register_tool_class(FigureCanvasTk) class SaveFigureTk(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2Tk.save_figure(self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(FigureCanvasTk) class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): NavigationToolbar2Tk.configure_subplots(self) @backend_tools._register_tool_class(FigureCanvasTk) class HelpTk(backend_tools.ToolHelpBase): def trigger(self, *args): dialog = SimpleDialog(self.figure.canvas._tkcanvas, self._get_help_text(), ['OK']) dialog.done = lambda num: dialog.frame.master.withdraw() Toolbar = ToolbarTk FigureManagerTk._toolbar2_class = NavigationToolbar2Tk FigureManagerTk._toolmanager_toolbar_class = ToolbarTk @_Backend.export class _BackendTk(_Backend): backend_version = tk.TkVersion FigureCanvas = FigureCanvasTk FigureManager = FigureManagerTk mainloop = FigureManagerTk.start_main_loop # File: matplotlib-main/lib/matplotlib/backends/backend_agg.py """""" from contextlib import nullcontext from math import radians, cos, sin import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, RendererBase from matplotlib.font_manager import fontManager as _fontManager, get_font from matplotlib.ft2font import LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING, LOAD_DEFAULT, LOAD_NO_AUTOHINT from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.transforms import Bbox, BboxBase from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg def get_hinting_flag(): mapping = {'default': LOAD_DEFAULT, 'no_autohint': LOAD_NO_AUTOHINT, 'force_autohint': LOAD_FORCE_AUTOHINT, 'no_hinting': LOAD_NO_HINTING, True: LOAD_FORCE_AUTOHINT, False: LOAD_NO_HINTING, 'either': LOAD_DEFAULT, 'native': LOAD_NO_AUTOHINT, 'auto': LOAD_FORCE_AUTOHINT, 'none': LOAD_NO_HINTING} return mapping[mpl.rcParams['text.hinting']] class RendererAgg(RendererBase): def __init__(self, width, height, dpi): super().__init__() self.dpi = dpi self.width = width self.height = height self._renderer = _RendererAgg(int(width), int(height), dpi) self._filter_renderers = [] self._update_methods() self.mathtext_parser = MathTextParser('agg') self.bbox = Bbox.from_bounds(0, 0, self.width, self.height) def __getstate__(self): return {'width': self.width, 'height': self.height, 'dpi': self.dpi} def __setstate__(self, state): self.__init__(state['width'], state['height'], state['dpi']) def _update_methods(self): self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles self.draw_image = self._renderer.draw_image self.draw_markers = self._renderer.draw_markers self.draw_path_collection = self._renderer.draw_path_collection self.draw_quad_mesh = self._renderer.draw_quad_mesh self.copy_from_bbox = self._renderer.copy_from_bbox def draw_path(self, gc, path, transform, rgbFace=None): nmax = mpl.rcParams['agg.path.chunksize'] npts = path.vertices.shape[0] if npts > nmax > 100 and path.should_simplify and (rgbFace is None) and (gc.get_hatch() is None): nch = np.ceil(npts / nmax) chsize = int(np.ceil(npts / nch)) i0 = np.arange(0, npts, chsize) i1 = np.zeros_like(i0) i1[:-1] = i0[1:] - 1 i1[-1] = npts for (ii0, ii1) in zip(i0, i1): v = path.vertices[ii0:ii1, :] c = path.codes if c is not None: c = c[ii0:ii1] c[0] = Path.MOVETO p = Path(v, c) p.simplify_threshold = path.simplify_threshold try: self._renderer.draw_path(gc, p, transform, rgbFace) except OverflowError: msg = f"Exceeded cell block limit in Agg.\n\nPlease reduce the value of rcParams['agg.path.chunksize'] (currently {nmax}) or increase the path simplification threshold(rcParams['path.simplify_threshold'] = {mpl.rcParams['path.simplify_threshold']:.2f} by default and path.simplify_threshold = {path.simplify_threshold:.2f} on the input)." raise OverflowError(msg) from None else: try: self._renderer.draw_path(gc, path, transform, rgbFace) except OverflowError: cant_chunk = '' if rgbFace is not None: cant_chunk += '- cannot split filled path\n' if gc.get_hatch() is not None: cant_chunk += '- cannot split hatched path\n' if not path.should_simplify: cant_chunk += '- path.should_simplify is False\n' if len(cant_chunk): msg = f'Exceeded cell block limit in Agg, however for the following reasons:\n\n{cant_chunk}\nwe cannot automatically split up this path to draw.\n\nPlease manually simplify your path.' else: inc_threshold = f"or increase the path simplification threshold(rcParams['path.simplify_threshold'] = {mpl.rcParams['path.simplify_threshold']} by default and path.simplify_threshold = {path.simplify_threshold} on the input)." if nmax > 100: msg = f"Exceeded cell block limit in Agg. Please reduce the value of rcParams['agg.path.chunksize'] (currently {nmax}) {inc_threshold}" else: msg = f"Exceeded cell block limit in Agg. Please set the value of rcParams['agg.path.chunksize'], (currently {nmax}) to be greater than 100 " + inc_threshold raise OverflowError(msg) from None def draw_mathtext(self, gc, x, y, s, prop, angle): (ox, oy, width, height, descent, font_image) = self.mathtext_parser.parse(s, self.dpi, prop, antialiased=gc.get_antialiased()) xd = descent * sin(radians(angle)) yd = descent * cos(radians(angle)) x = round(x + ox + xd) y = round(y - oy + yd) self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) font = self._prepare_font(prop) font.set_text(s, 0, flags=get_hinting_flag()) font.draw_glyphs_to_bitmap(antialiased=gc.get_antialiased()) d = font.get_descent() / 64.0 (xo, yo) = font.get_bitmap_offset() xo /= 64.0 yo /= 64.0 xd = d * sin(radians(angle)) yd = d * cos(radians(angle)) x = round(x + xo + xd) y = round(y + yo + yd) self._renderer.draw_text_image(font, x, y + 1, angle, gc) def get_text_width_height_descent(self, s, prop, ismath): _api.check_in_list(['TeX', True, False], ismath=ismath) if ismath == 'TeX': return super().get_text_width_height_descent(s, prop, ismath) if ismath: (ox, oy, width, height, descent, font_image) = self.mathtext_parser.parse(s, self.dpi, prop) return (width, height, descent) font = self._prepare_font(prop) font.set_text(s, 0.0, flags=get_hinting_flag()) (w, h) = font.get_width_height() d = font.get_descent() w /= 64.0 h /= 64.0 d /= 64.0 return (w, h, d) def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): size = prop.get_size_in_points() texmanager = self.get_texmanager() Z = texmanager.get_grey(s, size, self.dpi) Z = np.array(Z * 255.0, np.uint8) (w, h, d) = self.get_text_width_height_descent(s, prop, ismath='TeX') xd = d * sin(radians(angle)) yd = d * cos(radians(angle)) x = round(x + xd) y = round(y + yd) self._renderer.draw_text_image(Z, x, y, angle, gc) def get_canvas_width_height(self): return (self.width, self.height) def _prepare_font(self, font_prop): font = get_font(_fontManager._find_fonts_by_props(font_prop)) font.clear() size = font_prop.get_size_in_points() font.set_size(size, self.dpi) return font def points_to_pixels(self, points): return points * self.dpi / 72 def buffer_rgba(self): return memoryview(self._renderer) def tostring_argb(self): return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes() @_api.deprecated('3.8', alternative='buffer_rgba') def tostring_rgb(self): return np.asarray(self._renderer).take([0, 1, 2], axis=2).tobytes() def clear(self): self._renderer.clear() def option_image_nocomposite(self): return True def option_scale_image(self): return False def restore_region(self, region, bbox=None, xy=None): if bbox is not None or xy is not None: if bbox is None: (x1, y1, x2, y2) = region.get_extents() elif isinstance(bbox, BboxBase): (x1, y1, x2, y2) = bbox.extents else: (x1, y1, x2, y2) = bbox if xy is None: (ox, oy) = (x1, y1) else: (ox, oy) = xy self._renderer.restore_region(region, int(x1), int(y1), int(x2), int(y2), int(ox), int(oy)) else: self._renderer.restore_region(region) def start_filter(self): self._filter_renderers.append(self._renderer) self._renderer = _RendererAgg(int(self.width), int(self.height), self.dpi) self._update_methods() def stop_filter(self, post_processing): orig_img = np.asarray(self.buffer_rgba()) (slice_y, slice_x) = cbook._get_nonzero_slices(orig_img[..., 3]) cropped_img = orig_img[slice_y, slice_x] self._renderer = self._filter_renderers.pop() self._update_methods() if cropped_img.size: (img, ox, oy) = post_processing(cropped_img / 255, self.dpi) gc = self.new_gc() if img.dtype.kind == 'f': img = np.asarray(img * 255.0, np.uint8) self._renderer.draw_image(gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy, img[::-1]) class FigureCanvasAgg(FigureCanvasBase): _lastKey = None def copy_from_bbox(self, bbox): renderer = self.get_renderer() return renderer.copy_from_bbox(bbox) def restore_region(self, region, bbox=None, xy=None): renderer = self.get_renderer() return renderer.restore_region(region, bbox, xy) def draw(self): self.renderer = self.get_renderer() self.renderer.clear() with self.toolbar._wait_cursor_for_draw_cm() if self.toolbar else nullcontext(): self.figure.draw(self.renderer) super().draw() def get_renderer(self): (w, h) = self.figure.bbox.size key = (w, h, self.figure.dpi) reuse_renderer = self._lastKey == key if not reuse_renderer: self.renderer = RendererAgg(w, h, self.figure.dpi) self._lastKey = key return self.renderer @_api.deprecated('3.8', alternative='buffer_rgba') def tostring_rgb(self): return self.renderer.tostring_rgb() def tostring_argb(self): return self.renderer.tostring_argb() def buffer_rgba(self): return self.renderer.buffer_rgba() def print_raw(self, filename_or_obj, *, metadata=None): if metadata is not None: raise ValueError('metadata not supported for raw/rgba') FigureCanvasAgg.draw(self) renderer = self.get_renderer() with cbook.open_file_cm(filename_or_obj, 'wb') as fh: fh.write(renderer.buffer_rgba()) print_rgba = print_raw def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None): FigureCanvasAgg.draw(self) mpl.image.imsave(filename_or_obj, self.buffer_rgba(), format=fmt, origin='upper', dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs) def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None): self._print_pil(filename_or_obj, 'png', pil_kwargs, metadata) def print_to_buffer(self): FigureCanvasAgg.draw(self) renderer = self.get_renderer() return (bytes(renderer.buffer_rgba()), (int(renderer.width), int(renderer.height))) def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None): with mpl.rc_context({'savefig.facecolor': 'white'}): self._print_pil(filename_or_obj, 'jpeg', pil_kwargs, metadata) print_jpeg = print_jpg def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None): self._print_pil(filename_or_obj, 'tiff', pil_kwargs, metadata) print_tiff = print_tif def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None): self._print_pil(filename_or_obj, 'webp', pil_kwargs, metadata) (print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__) = map('\n Write the figure to a {} file.\n\n Parameters\n ----------\n filename_or_obj : str or path-like or file-like\n The file to write to.\n pil_kwargs : dict, optional\n Additional keyword arguments that are passed to\n `PIL.Image.Image.save` when saving the figure.\n '.format, ['JPEG', 'TIFF', 'WebP']) @_Backend.export class _BackendAgg(_Backend): backend_version = 'v2.2' FigureCanvas = FigureCanvasAgg FigureManager = FigureManagerBase # File: matplotlib-main/lib/matplotlib/backends/backend_cairo.py """""" import functools import gzip import math import numpy as np try: import cairo if cairo.version_info < (1, 14, 0): raise ImportError(f'Cairo backend requires cairo>=1.14.0, but only {cairo.version_info} is available') except ImportError: try: import cairocffi as cairo except ImportError as err: raise ImportError('cairo backend requires that pycairo>=1.14.0 or cairocffi is installed') from err from .. import _api, cbook, font_manager from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase from matplotlib.font_manager import ttfFontProperty from matplotlib.path import Path from matplotlib.transforms import Affine2D def _set_rgba(ctx, color, alpha, forced_alpha): if len(color) == 3 or forced_alpha: ctx.set_source_rgba(*color[:3], alpha) else: ctx.set_source_rgba(*color) def _append_path(ctx, path, transform, clip=None): for (points, code) in path.iter_segments(transform, remove_nans=True, clip=clip): if code == Path.MOVETO: ctx.move_to(*points) elif code == Path.CLOSEPOLY: ctx.close_path() elif code == Path.LINETO: ctx.line_to(*points) elif code == Path.CURVE3: cur = np.asarray(ctx.get_current_point()) a = points[:2] b = points[-2:] ctx.curve_to(*cur / 3 + a * 2 / 3, *a * 2 / 3 + b / 3, *b) elif code == Path.CURVE4: ctx.curve_to(*points) def _cairo_font_args_from_font_prop(prop): def attr(field): try: return getattr(prop, f'get_{field}')() except AttributeError: return getattr(prop, field) name = attr('name') slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}") weight = attr('weight') weight = cairo.FONT_WEIGHT_NORMAL if font_manager.weight_dict.get(weight, weight) < 550 else cairo.FONT_WEIGHT_BOLD return (name, slant, weight) class RendererCairo(RendererBase): def __init__(self, dpi): self.dpi = dpi self.gc = GraphicsContextCairo(renderer=self) self.width = None self.height = None self.text_ctx = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) super().__init__() def set_context(self, ctx): surface = ctx.get_target() if hasattr(surface, 'get_width') and hasattr(surface, 'get_height'): size = (surface.get_width(), surface.get_height()) elif hasattr(surface, 'get_extents'): ext = surface.get_extents() size = (ext.width, ext.height) else: ctx.save() ctx.reset_clip() (rect, *rest) = ctx.copy_clip_rectangle_list() if rest: raise TypeError('Cannot infer surface size') (_, _, *size) = rect ctx.restore() self.gc.ctx = ctx (self.width, self.height) = size @staticmethod def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides): if fill_c is not None: ctx.save() _set_rgba(ctx, fill_c, alpha, alpha_overrides) ctx.fill_preserve() ctx.restore() ctx.stroke() def draw_path(self, gc, path, transform, rgbFace=None): ctx = gc.ctx clip = ctx.clip_extents() if rgbFace is None and gc.get_hatch() is None else None transform = transform + Affine2D().scale(1, -1).translate(0, self.height) ctx.new_path() _append_path(ctx, path, transform, clip) if rgbFace is not None: ctx.save() _set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) ctx.fill_preserve() ctx.restore() hatch_path = gc.get_hatch_path() if hatch_path: dpi = int(self.dpi) hatch_surface = ctx.get_target().create_similar(cairo.Content.COLOR_ALPHA, dpi, dpi) hatch_ctx = cairo.Context(hatch_surface) _append_path(hatch_ctx, hatch_path, Affine2D().scale(dpi, -dpi).translate(0, dpi), None) hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth())) hatch_ctx.set_source_rgba(*gc.get_hatch_color()) hatch_ctx.fill_preserve() hatch_ctx.stroke() hatch_pattern = cairo.SurfacePattern(hatch_surface) hatch_pattern.set_extend(cairo.Extend.REPEAT) ctx.save() ctx.set_source(hatch_pattern) ctx.fill_preserve() ctx.restore() ctx.stroke() def draw_markers(self, gc, marker_path, marker_trans, path, transform, rgbFace=None): ctx = gc.ctx ctx.new_path() _append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1)) marker_path = ctx.copy_path_flat() (x1, y1, x2, y2) = ctx.fill_extents() if x1 == 0 and y1 == 0 and (x2 == 0) and (y2 == 0): filled = False rgbFace = None else: filled = True transform = transform + Affine2D().scale(1, -1).translate(0, self.height) ctx.new_path() for (i, (vertices, codes)) in enumerate(path.iter_segments(transform, simplify=False)): if len(vertices): (x, y) = vertices[-2:] ctx.save() ctx.translate(x, y) ctx.append_path(marker_path) ctx.restore() if filled or i % 1000 == 0: self._fill_and_stroke(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) if not filled: self._fill_and_stroke(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) def draw_image(self, gc, x, y, im): im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1]) surface = cairo.ImageSurface.create_for_data(im.ravel().data, cairo.FORMAT_ARGB32, im.shape[1], im.shape[0], im.shape[1] * 4) ctx = gc.ctx y = self.height - y - im.shape[0] ctx.save() ctx.set_source_surface(surface, float(x), float(y)) ctx.paint() ctx.restore() def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): if ismath: self._draw_mathtext(gc, x, y, s, prop, angle) else: ctx = gc.ctx ctx.new_path() ctx.move_to(x, y) ctx.save() ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points())) opts = cairo.FontOptions() opts.set_antialias(gc.get_antialiased()) ctx.set_font_options(opts) if angle: ctx.rotate(np.deg2rad(-angle)) ctx.show_text(s) ctx.restore() def _draw_mathtext(self, gc, x, y, s, prop, angle): ctx = gc.ctx (width, height, descent, glyphs, rects) = self._text2path.mathtext_parser.parse(s, self.dpi, prop) ctx.save() ctx.translate(x, y) if angle: ctx.rotate(np.deg2rad(-angle)) for (font, fontsize, idx, ox, oy) in glyphs: ctx.new_path() ctx.move_to(ox, -oy) ctx.select_font_face(*_cairo_font_args_from_font_prop(ttfFontProperty(font))) ctx.set_font_size(self.points_to_pixels(fontsize)) ctx.show_text(chr(idx)) for (ox, oy, w, h) in rects: ctx.new_path() ctx.rectangle(ox, -oy, w, -h) ctx.set_source_rgb(0, 0, 0) ctx.fill_preserve() ctx.restore() def get_canvas_width_height(self): return (self.width, self.height) def get_text_width_height_descent(self, s, prop, ismath): if ismath == 'TeX': return super().get_text_width_height_descent(s, prop, ismath) if ismath: (width, height, descent, *_) = self._text2path.mathtext_parser.parse(s, self.dpi, prop) return (width, height, descent) ctx = self.text_ctx ctx.save() ctx.select_font_face(*_cairo_font_args_from_font_prop(prop)) ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points())) (y_bearing, w, h) = ctx.text_extents(s)[1:4] ctx.restore() return (w, h, h + y_bearing) def new_gc(self): self.gc.ctx.save() self.gc._alpha = 1 self.gc._forced_alpha = False self.gc._hatch = None return self.gc def points_to_pixels(self, points): return points / 72 * self.dpi class GraphicsContextCairo(GraphicsContextBase): _joind = {'bevel': cairo.LINE_JOIN_BEVEL, 'miter': cairo.LINE_JOIN_MITER, 'round': cairo.LINE_JOIN_ROUND} _capd = {'butt': cairo.LINE_CAP_BUTT, 'projecting': cairo.LINE_CAP_SQUARE, 'round': cairo.LINE_CAP_ROUND} def __init__(self, renderer): super().__init__() self.renderer = renderer def restore(self): self.ctx.restore() def set_alpha(self, alpha): super().set_alpha(alpha) _set_rgba(self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha()) def set_antialiased(self, b): self.ctx.set_antialias(cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE) def get_antialiased(self): return self.ctx.get_antialias() def set_capstyle(self, cs): self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs)) self._capstyle = cs def set_clip_rectangle(self, rectangle): if not rectangle: return (x, y, w, h) = np.round(rectangle.bounds) ctx = self.ctx ctx.new_path() ctx.rectangle(x, self.renderer.height - h - y, w, h) ctx.clip() def set_clip_path(self, path): if not path: return (tpath, affine) = path.get_transformed_path_and_affine() ctx = self.ctx ctx.new_path() affine = affine + Affine2D().scale(1, -1).translate(0, self.renderer.height) _append_path(ctx, tpath, affine) ctx.clip() def set_dashes(self, offset, dashes): self._dashes = (offset, dashes) if dashes is None: self.ctx.set_dash([], 0) else: self.ctx.set_dash(list(self.renderer.points_to_pixels(np.asarray(dashes))), offset) def set_foreground(self, fg, isRGBA=None): super().set_foreground(fg, isRGBA) if len(self._rgb) == 3: self.ctx.set_source_rgb(*self._rgb) else: self.ctx.set_source_rgba(*self._rgb) def get_rgb(self): return self.ctx.get_source().get_rgba()[:3] def set_joinstyle(self, js): self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js)) self._joinstyle = js def set_linewidth(self, w): self._linewidth = float(w) self.ctx.set_line_width(self.renderer.points_to_pixels(w)) class _CairoRegion: def __init__(self, slices, data): self._slices = slices self._data = data class FigureCanvasCairo(FigureCanvasBase): @property def _renderer(self): if not hasattr(self, '_cached_renderer'): self._cached_renderer = RendererCairo(self.figure.dpi) return self._cached_renderer def get_renderer(self): return self._renderer def copy_from_bbox(self, bbox): surface = self._renderer.gc.ctx.get_target() if not isinstance(surface, cairo.ImageSurface): raise RuntimeError('copy_from_bbox only works when rendering to an ImageSurface') sw = surface.get_width() sh = surface.get_height() x0 = math.ceil(bbox.x0) x1 = math.floor(bbox.x1) y0 = math.ceil(sh - bbox.y1) y1 = math.floor(sh - bbox.y0) if not (0 <= x0 and x1 <= sw and (bbox.x0 <= bbox.x1) and (0 <= y0) and (y1 <= sh) and (bbox.y0 <= bbox.y1)): raise ValueError('Invalid bbox') sls = (slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0))) data = np.frombuffer(surface.get_data(), np.uint32).reshape((sh, sw))[sls].copy() return _CairoRegion(sls, data) def restore_region(self, region): surface = self._renderer.gc.ctx.get_target() if not isinstance(surface, cairo.ImageSurface): raise RuntimeError('restore_region only works when rendering to an ImageSurface') surface.flush() sw = surface.get_width() sh = surface.get_height() (sly, slx) = region._slices np.frombuffer(surface.get_data(), np.uint32).reshape((sh, sw))[sly, slx] = region._data surface.mark_dirty_rectangle(slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start) def print_png(self, fobj): self._get_printed_image_surface().write_to_png(fobj) def print_rgba(self, fobj): (width, height) = self.get_width_height() buf = self._get_printed_image_surface().get_data() fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888(np.asarray(buf).reshape((width, height, 4)))) print_raw = print_rgba def _get_printed_image_surface(self): self._renderer.dpi = self.figure.dpi (width, height) = self.get_width_height() surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) self._renderer.set_context(cairo.Context(surface)) self.figure.draw(self._renderer) return surface def _save(self, fmt, fobj, *, orientation='portrait'): dpi = 72 self.figure.dpi = dpi (w_in, h_in) = self.figure.get_size_inches() (width_in_points, height_in_points) = (w_in * dpi, h_in * dpi) if orientation == 'landscape': (width_in_points, height_in_points) = (height_in_points, width_in_points) if fmt == 'ps': if not hasattr(cairo, 'PSSurface'): raise RuntimeError('cairo has not been compiled with PS support enabled') surface = cairo.PSSurface(fobj, width_in_points, height_in_points) elif fmt == 'pdf': if not hasattr(cairo, 'PDFSurface'): raise RuntimeError('cairo has not been compiled with PDF support enabled') surface = cairo.PDFSurface(fobj, width_in_points, height_in_points) elif fmt in ('svg', 'svgz'): if not hasattr(cairo, 'SVGSurface'): raise RuntimeError('cairo has not been compiled with SVG support enabled') if fmt == 'svgz': if isinstance(fobj, str): fobj = gzip.GzipFile(fobj, 'wb') else: fobj = gzip.GzipFile(None, 'wb', fileobj=fobj) surface = cairo.SVGSurface(fobj, width_in_points, height_in_points) else: raise ValueError(f'Unknown format: {fmt!r}') self._renderer.dpi = self.figure.dpi self._renderer.set_context(cairo.Context(surface)) ctx = self._renderer.gc.ctx if orientation == 'landscape': ctx.rotate(np.pi / 2) ctx.translate(0, -height_in_points) self.figure.draw(self._renderer) ctx.show_page() surface.finish() if fmt == 'svgz': fobj.close() print_pdf = functools.partialmethod(_save, 'pdf') print_ps = functools.partialmethod(_save, 'ps') print_svg = functools.partialmethod(_save, 'svg') print_svgz = functools.partialmethod(_save, 'svgz') @_Backend.export class _BackendCairo(_Backend): backend_version = cairo.version FigureCanvas = FigureCanvasCairo FigureManager = FigureManagerBase # File: matplotlib-main/lib/matplotlib/backends/backend_gtk3.py import functools import logging import os from pathlib import Path import matplotlib as mpl from matplotlib import _api, backend_tools, cbook from matplotlib.backend_bases import ToolContainerBase, CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent try: import gi except ImportError as err: raise ImportError('The GTK3 backends require PyGObject') from err try: gi.require_version('Gtk', '3.0') except ValueError as e: raise ImportError(e) from e from gi.repository import Gio, GLib, GObject, Gtk, Gdk from . import _backend_gtk from ._backend_gtk import _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK, TimerGTK as TimerGTK3 _log = logging.getLogger(__name__) @functools.cache def _mpl_to_gtk_cursor(mpl_cursor): return Gdk.Cursor.new_from_name(Gdk.Display.get_default(), _backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor)) class FigureCanvasGTK3(_FigureCanvasGTK, Gtk.DrawingArea): required_interactive_framework = 'gtk3' manager_class = _api.classproperty(lambda cls: FigureManagerGTK3) event_mask = Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.EXPOSURE_MASK | Gdk.EventMask.KEY_PRESS_MASK | Gdk.EventMask.KEY_RELEASE_MASK | Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK | Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.SCROLL_MASK def __init__(self, figure=None): super().__init__(figure=figure) self._idle_draw_id = 0 self._rubberband_rect = None self.connect('scroll_event', self.scroll_event) self.connect('button_press_event', self.button_press_event) self.connect('button_release_event', self.button_release_event) self.connect('configure_event', self.configure_event) self.connect('screen-changed', self._update_device_pixel_ratio) self.connect('notify::scale-factor', self._update_device_pixel_ratio) self.connect('draw', self.on_draw_event) self.connect('draw', self._post_draw) self.connect('key_press_event', self.key_press_event) self.connect('key_release_event', self.key_release_event) self.connect('motion_notify_event', self.motion_notify_event) self.connect('enter_notify_event', self.enter_notify_event) self.connect('leave_notify_event', self.leave_notify_event) self.connect('size_allocate', self.size_allocate) self.set_events(self.__class__.event_mask) self.set_can_focus(True) css = Gtk.CssProvider() css.load_from_data(b'.matplotlib-canvas { background-color: white; }') style_ctx = self.get_style_context() style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) style_ctx.add_class('matplotlib-canvas') def destroy(self): CloseEvent('close_event', self)._process() def set_cursor(self, cursor): window = self.get_property('window') if window is not None: window.set_cursor(_mpl_to_gtk_cursor(cursor)) context = GLib.MainContext.default() context.iteration(True) def _mpl_coords(self, event=None): if event is None: window = self.get_window() (t, x, y, state) = window.get_device_position(window.get_display().get_device_manager().get_client_pointer()) else: (x, y) = (event.x, event.y) x = x * self.device_pixel_ratio y = self.figure.bbox.height - y * self.device_pixel_ratio return (x, y) def scroll_event(self, widget, event): step = 1 if event.direction == Gdk.ScrollDirection.UP else -1 MouseEvent('scroll_event', self, *self._mpl_coords(event), step=step, modifiers=self._mpl_modifiers(event.state), guiEvent=event)._process() return False def button_press_event(self, widget, event): MouseEvent('button_press_event', self, *self._mpl_coords(event), event.button, modifiers=self._mpl_modifiers(event.state), guiEvent=event)._process() return False def button_release_event(self, widget, event): MouseEvent('button_release_event', self, *self._mpl_coords(event), event.button, modifiers=self._mpl_modifiers(event.state), guiEvent=event)._process() return False def key_press_event(self, widget, event): KeyEvent('key_press_event', self, self._get_key(event), *self._mpl_coords(), guiEvent=event)._process() return True def key_release_event(self, widget, event): KeyEvent('key_release_event', self, self._get_key(event), *self._mpl_coords(), guiEvent=event)._process() return True def motion_notify_event(self, widget, event): MouseEvent('motion_notify_event', self, *self._mpl_coords(event), modifiers=self._mpl_modifiers(event.state), guiEvent=event)._process() return False def enter_notify_event(self, widget, event): gtk_mods = Gdk.Keymap.get_for_display(self.get_display()).get_modifier_state() LocationEvent('figure_enter_event', self, *self._mpl_coords(event), modifiers=self._mpl_modifiers(gtk_mods), guiEvent=event)._process() def leave_notify_event(self, widget, event): gtk_mods = Gdk.Keymap.get_for_display(self.get_display()).get_modifier_state() LocationEvent('figure_leave_event', self, *self._mpl_coords(event), modifiers=self._mpl_modifiers(gtk_mods), guiEvent=event)._process() def size_allocate(self, widget, allocation): dpival = self.figure.dpi winch = allocation.width * self.device_pixel_ratio / dpival hinch = allocation.height * self.device_pixel_ratio / dpival self.figure.set_size_inches(winch, hinch, forward=False) ResizeEvent('resize_event', self)._process() self.draw_idle() @staticmethod def _mpl_modifiers(event_state, *, exclude=None): modifiers = [('ctrl', Gdk.ModifierType.CONTROL_MASK, 'control'), ('alt', Gdk.ModifierType.MOD1_MASK, 'alt'), ('shift', Gdk.ModifierType.SHIFT_MASK, 'shift'), ('super', Gdk.ModifierType.MOD4_MASK, 'super')] return [name for (name, mask, key) in modifiers if exclude != key and event_state & mask] def _get_key(self, event): unikey = chr(Gdk.keyval_to_unicode(event.keyval)) key = cbook._unikey_or_keysym_to_mplkey(unikey, Gdk.keyval_name(event.keyval)) mods = self._mpl_modifiers(event.state, exclude=key) if 'shift' in mods and unikey.isprintable(): mods.remove('shift') return '+'.join([*mods, key]) def _update_device_pixel_ratio(self, *args, **kwargs): if self._set_device_pixel_ratio(self.get_scale_factor()): self.queue_resize() self.queue_draw() def configure_event(self, widget, event): if widget.get_property('window') is None: return w = event.width * self.device_pixel_ratio h = event.height * self.device_pixel_ratio if w < 3 or h < 3: return dpi = self.figure.dpi self.figure.set_size_inches(w / dpi, h / dpi, forward=False) return False def _draw_rubberband(self, rect): self._rubberband_rect = rect self.queue_draw() def _post_draw(self, widget, ctx): if self._rubberband_rect is None: return (x0, y0, w, h) = (dim / self.device_pixel_ratio for dim in self._rubberband_rect) x1 = x0 + w y1 = y0 + h ctx.move_to(x0, y0) ctx.line_to(x0, y1) ctx.move_to(x0, y0) ctx.line_to(x1, y0) ctx.move_to(x0, y1) ctx.line_to(x1, y1) ctx.move_to(x1, y0) ctx.line_to(x1, y1) ctx.set_antialias(1) ctx.set_line_width(1) ctx.set_dash((3, 3), 0) ctx.set_source_rgb(0, 0, 0) ctx.stroke_preserve() ctx.set_dash((3, 3), 3) ctx.set_source_rgb(1, 1, 1) ctx.stroke() def on_draw_event(self, widget, ctx): pass def draw(self): if self.is_drawable(): self.queue_draw() def draw_idle(self): if self._idle_draw_id != 0: return def idle_draw(*args): try: self.draw() finally: self._idle_draw_id = 0 return False self._idle_draw_id = GLib.idle_add(idle_draw) def flush_events(self): context = GLib.MainContext.default() while context.pending(): context.iteration(True) class NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar): def __init__(self, canvas): GObject.GObject.__init__(self) self.set_style(Gtk.ToolbarStyle.ICONS) self._gtk_ids = {} for (text, tooltip_text, image_file, callback) in self.toolitems: if text is None: self.insert(Gtk.SeparatorToolItem(), -1) continue image = Gtk.Image.new_from_gicon(Gio.Icon.new_for_string(str(cbook._get_data_path('images', f'{image_file}-symbolic.svg'))), Gtk.IconSize.LARGE_TOOLBAR) self._gtk_ids[text] = button = Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else Gtk.ToolButton() button.set_label(text) button.set_icon_widget(image) button._signal_handler = button.connect('clicked', getattr(self, callback)) button.set_tooltip_text(tooltip_text) self.insert(button, -1) toolitem = Gtk.ToolItem() self.insert(toolitem, -1) label = Gtk.Label() label.set_markup('\xa0\n\xa0') toolitem.set_expand(True) toolitem.add(label) toolitem = Gtk.ToolItem() self.insert(toolitem, -1) self.message = Gtk.Label() self.message.set_justify(Gtk.Justification.RIGHT) toolitem.add(self.message) self.show_all() _NavigationToolbar2GTK.__init__(self, canvas) def save_figure(self, *args): dialog = Gtk.FileChooserDialog(title='Save the figure', parent=self.canvas.get_toplevel(), action=Gtk.FileChooserAction.SAVE, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK)) for (name, fmts) in self.canvas.get_supported_filetypes_grouped().items(): ff = Gtk.FileFilter() ff.set_name(name) for fmt in fmts: ff.add_pattern(f'*.{fmt}') dialog.add_filter(ff) if self.canvas.get_default_filetype() in fmts: dialog.set_filter(ff) @functools.partial(dialog.connect, 'notify::filter') def on_notify_filter(*args): name = dialog.get_filter().get_name() fmt = self.canvas.get_supported_filetypes_grouped()[name][0] dialog.set_current_name(str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}'))) dialog.set_current_folder(mpl.rcParams['savefig.directory']) dialog.set_current_name(self.canvas.get_default_filename()) dialog.set_do_overwrite_confirmation(True) response = dialog.run() fname = dialog.get_filename() ff = dialog.get_filter() fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0] dialog.destroy() if response != Gtk.ResponseType.OK: return if mpl.rcParams['savefig.directory']: mpl.rcParams['savefig.directory'] = os.path.dirname(fname) try: self.canvas.figure.savefig(fname, format=fmt) except Exception as e: dialog = Gtk.MessageDialog(parent=self.canvas.get_toplevel(), message_format=str(e), type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK) dialog.run() dialog.destroy() class ToolbarGTK3(ToolContainerBase, Gtk.Box): _icon_extension = '-symbolic.svg' def __init__(self, toolmanager): ToolContainerBase.__init__(self, toolmanager) Gtk.Box.__init__(self) self.set_property('orientation', Gtk.Orientation.HORIZONTAL) self._message = Gtk.Label() self._message.set_justify(Gtk.Justification.RIGHT) self.pack_end(self._message, False, False, 0) self.show_all() self._groups = {} self._toolitems = {} def add_toolitem(self, name, group, position, image_file, description, toggle): if toggle: button = Gtk.ToggleToolButton() else: button = Gtk.ToolButton() button.set_label(name) if image_file is not None: image = Gtk.Image.new_from_gicon(Gio.Icon.new_for_string(image_file), Gtk.IconSize.LARGE_TOOLBAR) button.set_icon_widget(image) if position is None: position = -1 self._add_button(button, group, position) signal = button.connect('clicked', self._call_tool, name) button.set_tooltip_text(description) button.show_all() self._toolitems.setdefault(name, []) self._toolitems[name].append((button, signal)) def _add_button(self, button, group, position): if group not in self._groups: if self._groups: self._add_separator() toolbar = Gtk.Toolbar() toolbar.set_style(Gtk.ToolbarStyle.ICONS) self.pack_start(toolbar, False, False, 0) toolbar.show_all() self._groups[group] = toolbar self._groups[group].insert(button, position) def _call_tool(self, btn, name): self.trigger_tool(name) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for (toolitem, signal) in self._toolitems[name]: toolitem.handler_block(signal) toolitem.set_active(toggled) toolitem.handler_unblock(signal) def remove_toolitem(self, name): for (toolitem, _signal) in self._toolitems.pop(name, []): for group in self._groups: if toolitem in self._groups[group]: self._groups[group].remove(toolitem) def _add_separator(self): sep = Gtk.Separator() sep.set_property('orientation', Gtk.Orientation.VERTICAL) self.pack_start(sep, False, True, 0) sep.show_all() def set_message(self, s): self._message.set_label(s) @backend_tools._register_tool_class(FigureCanvasGTK3) class SaveFigureGTK3(backend_tools.SaveFigureBase): def trigger(self, *args, **kwargs): NavigationToolbar2GTK3.save_figure(self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(FigureCanvasGTK3) class HelpGTK3(backend_tools.ToolHelpBase): def _normalize_shortcut(self, key): special = {'backspace': 'BackSpace', 'pagedown': 'Page_Down', 'pageup': 'Page_Up', 'scroll_lock': 'Scroll_Lock'} parts = key.split('+') mods = ['<' + mod + '>' for mod in parts[:-1]] key = parts[-1] if key in special: key = special[key] elif len(key) > 1: key = key.capitalize() elif key.isupper(): mods += [''] return ''.join(mods) + key def _is_valid_shortcut(self, key): return 'cmd+' not in key and (not key.startswith('MouseButton.')) def _show_shortcuts_window(self): section = Gtk.ShortcutsSection() for (name, tool) in sorted(self.toolmanager.tools.items()): if not tool.description: continue group = Gtk.ShortcutsGroup() section.add(group) group.forall(lambda widget, data: widget.set_visible(False), None) shortcut = Gtk.ShortcutsShortcut(accelerator=' '.join((self._normalize_shortcut(key) for key in self.toolmanager.get_tool_keymap(name) if self._is_valid_shortcut(key))), title=tool.name, subtitle=tool.description) group.add(shortcut) window = Gtk.ShortcutsWindow(title='Help', modal=True, transient_for=self._figure.canvas.get_toplevel()) section.show() window.add(section) window.show_all() def _show_shortcuts_dialog(self): dialog = Gtk.MessageDialog(self._figure.canvas.get_toplevel(), 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(), title='Help') dialog.run() dialog.destroy() def trigger(self, *args): if Gtk.check_version(3, 20, 0) is None: self._show_shortcuts_window() else: self._show_shortcuts_dialog() @backend_tools._register_tool_class(FigureCanvasGTK3) class ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) window = self.canvas.get_window() (x, y, width, height) = window.get_geometry() pb = Gdk.pixbuf_get_from_window(window, x, y, width, height) clipboard.set_image(pb) Toolbar = ToolbarGTK3 backend_tools._register_tool_class(FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK) backend_tools._register_tool_class(FigureCanvasGTK3, _backend_gtk.RubberbandGTK) class FigureManagerGTK3(_FigureManagerGTK): _toolbar2_class = NavigationToolbar2GTK3 _toolmanager_toolbar_class = ToolbarGTK3 @_BackendGTK.export class _BackendGTK3(_BackendGTK): FigureCanvas = FigureCanvasGTK3 FigureManager = FigureManagerGTK3 # File: matplotlib-main/lib/matplotlib/backends/backend_gtk3agg.py import numpy as np from .. import cbook, transforms from . import backend_agg, backend_gtk3 from .backend_gtk3 import GLib, Gtk, _BackendGTK3 import cairo class FigureCanvasGTK3Agg(backend_agg.FigureCanvasAgg, backend_gtk3.FigureCanvasGTK3): def __init__(self, figure): super().__init__(figure=figure) self._bbox_queue = [] def on_draw_event(self, widget, ctx): if self._idle_draw_id: GLib.source_remove(self._idle_draw_id) self._idle_draw_id = 0 self.draw() scale = self.device_pixel_ratio allocation = self.get_allocation() w = allocation.width * scale h = allocation.height * scale if not len(self._bbox_queue): Gtk.render_background(self.get_style_context(), ctx, allocation.x, allocation.y, allocation.width, allocation.height) bbox_queue = [transforms.Bbox([[0, 0], [w, h]])] else: bbox_queue = self._bbox_queue for bbox in bbox_queue: x = int(bbox.x0) y = h - int(bbox.y1) width = int(bbox.x1) - int(bbox.x0) height = int(bbox.y1) - int(bbox.y0) buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(np.asarray(self.copy_from_bbox(bbox))) image = cairo.ImageSurface.create_for_data(buf.ravel().data, cairo.FORMAT_ARGB32, width, height) image.set_device_scale(scale, scale) ctx.set_source_surface(image, x / scale, y / scale) ctx.paint() if len(self._bbox_queue): self._bbox_queue = [] return False def blit(self, bbox=None): if bbox is None: bbox = self.figure.bbox scale = self.device_pixel_ratio allocation = self.get_allocation() x = int(bbox.x0 / scale) y = allocation.height - int(bbox.y1 / scale) width = (int(bbox.x1) - int(bbox.x0)) // scale height = (int(bbox.y1) - int(bbox.y0)) // scale self._bbox_queue.append(bbox) self.queue_draw_area(x, y, width, height) @_BackendGTK3.export class _BackendGTK3Cairo(_BackendGTK3): FigureCanvas = FigureCanvasGTK3Agg # File: matplotlib-main/lib/matplotlib/backends/backend_gtk3cairo.py from contextlib import nullcontext from .backend_cairo import FigureCanvasCairo from .backend_gtk3 import GLib, Gtk, FigureCanvasGTK3, _BackendGTK3 class FigureCanvasGTK3Cairo(FigureCanvasCairo, FigureCanvasGTK3): def on_draw_event(self, widget, ctx): if self._idle_draw_id: GLib.source_remove(self._idle_draw_id) self._idle_draw_id = 0 self.draw() with self.toolbar._wait_cursor_for_draw_cm() if self.toolbar else nullcontext(): allocation = self.get_allocation() Gtk.render_background(self.get_style_context(), ctx, 0, 0, allocation.width, allocation.height) scale = self.device_pixel_ratio ctx.scale(1 / scale, 1 / scale) self._renderer.set_context(ctx) self._renderer.width = allocation.width * scale self._renderer.height = allocation.height * scale self._renderer.dpi = self.figure.dpi self.figure.draw(self._renderer) @_BackendGTK3.export class _BackendGTK3Cairo(_BackendGTK3): FigureCanvas = FigureCanvasGTK3Cairo # File: matplotlib-main/lib/matplotlib/backends/backend_gtk4.py import functools import io import os import matplotlib as mpl from matplotlib import _api, backend_tools, cbook from matplotlib.backend_bases import ToolContainerBase, KeyEvent, LocationEvent, MouseEvent, ResizeEvent, CloseEvent try: import gi except ImportError as err: raise ImportError('The GTK4 backends require PyGObject') from err try: gi.require_version('Gtk', '4.0') except ValueError as e: raise ImportError(e) from e from gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf from . import _backend_gtk from ._backend_gtk import _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK, TimerGTK as TimerGTK4 class FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea): required_interactive_framework = 'gtk4' supports_blit = False manager_class = _api.classproperty(lambda cls: FigureManagerGTK4) def __init__(self, figure=None): super().__init__(figure=figure) self.set_hexpand(True) self.set_vexpand(True) self._idle_draw_id = 0 self._rubberband_rect = None self.set_draw_func(self._draw_func) self.connect('resize', self.resize_event) self.connect('notify::scale-factor', self._update_device_pixel_ratio) click = Gtk.GestureClick() click.set_button(0) click.connect('pressed', self.button_press_event) click.connect('released', self.button_release_event) self.add_controller(click) key = Gtk.EventControllerKey() key.connect('key-pressed', self.key_press_event) key.connect('key-released', self.key_release_event) self.add_controller(key) motion = Gtk.EventControllerMotion() motion.connect('motion', self.motion_notify_event) motion.connect('enter', self.enter_notify_event) motion.connect('leave', self.leave_notify_event) self.add_controller(motion) scroll = Gtk.EventControllerScroll.new(Gtk.EventControllerScrollFlags.VERTICAL) scroll.connect('scroll', self.scroll_event) self.add_controller(scroll) self.set_focusable(True) css = Gtk.CssProvider() style = '.matplotlib-canvas { background-color: white; }' if Gtk.check_version(4, 9, 3) is None: css.load_from_data(style, -1) else: css.load_from_data(style.encode('utf-8')) style_ctx = self.get_style_context() style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) style_ctx.add_class('matplotlib-canvas') def destroy(self): CloseEvent('close_event', self)._process() def set_cursor(self, cursor): self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor)) def _mpl_coords(self, xy=None): if xy is None: surface = self.get_native().get_surface() (is_over, x, y, mask) = surface.get_device_position(self.get_display().get_default_seat().get_pointer()) else: (x, y) = xy x = x * self.device_pixel_ratio y = self.figure.bbox.height - y * self.device_pixel_ratio return (x, y) def scroll_event(self, controller, dx, dy): MouseEvent('scroll_event', self, *self._mpl_coords(), step=dy, modifiers=self._mpl_modifiers(controller))._process() return True def button_press_event(self, controller, n_press, x, y): MouseEvent('button_press_event', self, *self._mpl_coords((x, y)), controller.get_current_button(), modifiers=self._mpl_modifiers(controller))._process() self.grab_focus() def button_release_event(self, controller, n_press, x, y): MouseEvent('button_release_event', self, *self._mpl_coords((x, y)), controller.get_current_button(), modifiers=self._mpl_modifiers(controller))._process() def key_press_event(self, controller, keyval, keycode, state): KeyEvent('key_press_event', self, self._get_key(keyval, keycode, state), *self._mpl_coords())._process() return True def key_release_event(self, controller, keyval, keycode, state): KeyEvent('key_release_event', self, self._get_key(keyval, keycode, state), *self._mpl_coords())._process() return True def motion_notify_event(self, controller, x, y): MouseEvent('motion_notify_event', self, *self._mpl_coords((x, y)), modifiers=self._mpl_modifiers(controller))._process() def enter_notify_event(self, controller, x, y): LocationEvent('figure_enter_event', self, *self._mpl_coords((x, y)), modifiers=self._mpl_modifiers())._process() def leave_notify_event(self, controller): LocationEvent('figure_leave_event', self, *self._mpl_coords(), modifiers=self._mpl_modifiers())._process() def resize_event(self, area, width, height): self._update_device_pixel_ratio() dpi = self.figure.dpi winch = width * self.device_pixel_ratio / dpi hinch = height * self.device_pixel_ratio / dpi self.figure.set_size_inches(winch, hinch, forward=False) ResizeEvent('resize_event', self)._process() self.draw_idle() def _mpl_modifiers(self, controller=None): if controller is None: surface = self.get_native().get_surface() (is_over, x, y, event_state) = surface.get_device_position(self.get_display().get_default_seat().get_pointer()) else: event_state = controller.get_current_event_state() mod_table = [('ctrl', Gdk.ModifierType.CONTROL_MASK), ('alt', Gdk.ModifierType.ALT_MASK), ('shift', Gdk.ModifierType.SHIFT_MASK), ('super', Gdk.ModifierType.SUPER_MASK)] return [name for (name, mask) in mod_table if event_state & mask] def _get_key(self, keyval, keycode, state): unikey = chr(Gdk.keyval_to_unicode(keyval)) key = cbook._unikey_or_keysym_to_mplkey(unikey, Gdk.keyval_name(keyval)) modifiers = [('ctrl', Gdk.ModifierType.CONTROL_MASK, 'control'), ('alt', Gdk.ModifierType.ALT_MASK, 'alt'), ('shift', Gdk.ModifierType.SHIFT_MASK, 'shift'), ('super', Gdk.ModifierType.SUPER_MASK, 'super')] mods = [mod for (mod, mask, mod_key) in modifiers if mod_key != key and state & mask and (not (mod == 'shift' and unikey.isprintable()))] return '+'.join([*mods, key]) def _update_device_pixel_ratio(self, *args, **kwargs): if self._set_device_pixel_ratio(self.get_scale_factor()): self.draw() def _draw_rubberband(self, rect): self._rubberband_rect = rect self.queue_draw() def _draw_func(self, drawing_area, ctx, width, height): self.on_draw_event(self, ctx) self._post_draw(self, ctx) def _post_draw(self, widget, ctx): if self._rubberband_rect is None: return lw = 1 dash = 3 (x0, y0, w, h) = (dim / self.device_pixel_ratio for dim in self._rubberband_rect) x1 = x0 + w y1 = y0 + h ctx.move_to(x0, y0) ctx.line_to(x0, y1) ctx.move_to(x0, y0) ctx.line_to(x1, y0) ctx.move_to(x0, y1) ctx.line_to(x1, y1) ctx.move_to(x1, y0) ctx.line_to(x1, y1) ctx.set_antialias(1) ctx.set_line_width(lw) ctx.set_dash((dash, dash), 0) ctx.set_source_rgb(0, 0, 0) ctx.stroke_preserve() ctx.set_dash((dash, dash), dash) ctx.set_source_rgb(1, 1, 1) ctx.stroke() def on_draw_event(self, widget, ctx): pass def draw(self): if self.is_drawable(): self.queue_draw() def draw_idle(self): if self._idle_draw_id != 0: return def idle_draw(*args): try: self.draw() finally: self._idle_draw_id = 0 return False self._idle_draw_id = GLib.idle_add(idle_draw) def flush_events(self): context = GLib.MainContext.default() while context.pending(): context.iteration(True) class NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box): def __init__(self, canvas): Gtk.Box.__init__(self) self.add_css_class('toolbar') self._gtk_ids = {} for (text, tooltip_text, image_file, callback) in self.toolitems: if text is None: self.append(Gtk.Separator()) continue image = Gtk.Image.new_from_gicon(Gio.Icon.new_for_string(str(cbook._get_data_path('images', f'{image_file}-symbolic.svg')))) self._gtk_ids[text] = button = Gtk.ToggleButton() if callback in ['zoom', 'pan'] else Gtk.Button() button.set_child(image) button.add_css_class('flat') button.add_css_class('image-button') button._signal_handler = button.connect('clicked', getattr(self, callback)) button.set_tooltip_text(tooltip_text) self.append(button) label = Gtk.Label() label.set_markup('\xa0\n\xa0') label.set_hexpand(True) self.append(label) self.message = Gtk.Label() self.message.set_justify(Gtk.Justification.RIGHT) self.append(self.message) _NavigationToolbar2GTK.__init__(self, canvas) def save_figure(self, *args): dialog = Gtk.FileChooserNative(title='Save the figure', transient_for=self.canvas.get_root(), action=Gtk.FileChooserAction.SAVE, modal=True) self._save_dialog = dialog ff = Gtk.FileFilter() ff.set_name('All files') ff.add_pattern('*') dialog.add_filter(ff) dialog.set_filter(ff) formats = [] default_format = None for (i, (name, fmts)) in enumerate(self.canvas.get_supported_filetypes_grouped().items()): ff = Gtk.FileFilter() ff.set_name(name) for fmt in fmts: ff.add_pattern(f'*.{fmt}') dialog.add_filter(ff) formats.append(name) if self.canvas.get_default_filetype() in fmts: default_format = i formats = [formats[default_format], *formats[:default_format], *formats[default_format + 1:]] dialog.add_choice('format', 'File format', formats, formats) dialog.set_choice('format', formats[0]) dialog.set_current_folder(Gio.File.new_for_path(os.path.expanduser(mpl.rcParams['savefig.directory']))) dialog.set_current_name(self.canvas.get_default_filename()) @functools.partial(dialog.connect, 'response') def on_response(dialog, response): file = dialog.get_file() fmt = dialog.get_choice('format') fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0] dialog.destroy() self._save_dialog = None if response != Gtk.ResponseType.ACCEPT: return if mpl.rcParams['savefig.directory']: parent = file.get_parent() mpl.rcParams['savefig.directory'] = parent.get_path() try: self.canvas.figure.savefig(file.get_path(), format=fmt) except Exception as e: msg = Gtk.MessageDialog(transient_for=self.canvas.get_root(), message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, modal=True, text=str(e)) msg.show() dialog.show() class ToolbarGTK4(ToolContainerBase, Gtk.Box): _icon_extension = '-symbolic.svg' def __init__(self, toolmanager): ToolContainerBase.__init__(self, toolmanager) Gtk.Box.__init__(self) self.set_property('orientation', Gtk.Orientation.HORIZONTAL) self._tool_box = Gtk.Box() self.append(self._tool_box) self._groups = {} self._toolitems = {} label = Gtk.Label() label.set_markup('\xa0\n\xa0') label.set_hexpand(True) self.append(label) self._message = Gtk.Label() self._message.set_justify(Gtk.Justification.RIGHT) self.append(self._message) def add_toolitem(self, name, group, position, image_file, description, toggle): if toggle: button = Gtk.ToggleButton() else: button = Gtk.Button() button.set_label(name) button.add_css_class('flat') if image_file is not None: image = Gtk.Image.new_from_gicon(Gio.Icon.new_for_string(image_file)) button.set_child(image) button.add_css_class('image-button') if position is None: position = -1 self._add_button(button, group, position) signal = button.connect('clicked', self._call_tool, name) button.set_tooltip_text(description) self._toolitems.setdefault(name, []) self._toolitems[name].append((button, signal)) def _find_child_at_position(self, group, position): children = [None] child = self._groups[group].get_first_child() while child is not None: children.append(child) child = child.get_next_sibling() return children[position] def _add_button(self, button, group, position): if group not in self._groups: if self._groups: self._add_separator() group_box = Gtk.Box() self._tool_box.append(group_box) self._groups[group] = group_box self._groups[group].insert_child_after(button, self._find_child_at_position(group, position)) def _call_tool(self, btn, name): self.trigger_tool(name) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for (toolitem, signal) in self._toolitems[name]: toolitem.handler_block(signal) toolitem.set_active(toggled) toolitem.handler_unblock(signal) def remove_toolitem(self, name): for (toolitem, _signal) in self._toolitems.pop(name, []): for group in self._groups: if toolitem in self._groups[group]: self._groups[group].remove(toolitem) def _add_separator(self): sep = Gtk.Separator() sep.set_property('orientation', Gtk.Orientation.VERTICAL) self._tool_box.append(sep) def set_message(self, s): self._message.set_label(s) @backend_tools._register_tool_class(FigureCanvasGTK4) class SaveFigureGTK4(backend_tools.SaveFigureBase): def trigger(self, *args, **kwargs): NavigationToolbar2GTK4.save_figure(self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(FigureCanvasGTK4) class HelpGTK4(backend_tools.ToolHelpBase): def _normalize_shortcut(self, key): special = {'backspace': 'BackSpace', 'pagedown': 'Page_Down', 'pageup': 'Page_Up', 'scroll_lock': 'Scroll_Lock'} parts = key.split('+') mods = ['<' + mod + '>' for mod in parts[:-1]] key = parts[-1] if key in special: key = special[key] elif len(key) > 1: key = key.capitalize() elif key.isupper(): mods += [''] return ''.join(mods) + key def _is_valid_shortcut(self, key): return 'cmd+' not in key and (not key.startswith('MouseButton.')) def trigger(self, *args): section = Gtk.ShortcutsSection() for (name, tool) in sorted(self.toolmanager.tools.items()): if not tool.description: continue group = Gtk.ShortcutsGroup() section.append(group) child = group.get_first_child() while child is not None: child.set_visible(False) child = child.get_next_sibling() shortcut = Gtk.ShortcutsShortcut(accelerator=' '.join((self._normalize_shortcut(key) for key in self.toolmanager.get_tool_keymap(name) if self._is_valid_shortcut(key))), title=tool.name, subtitle=tool.description) group.append(shortcut) window = Gtk.ShortcutsWindow(title='Help', modal=True, transient_for=self._figure.canvas.get_root()) window.set_child(section) window.show() @backend_tools._register_tool_class(FigureCanvasGTK4) class ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): with io.BytesIO() as f: self.canvas.print_rgba(f) (w, h) = self.canvas.get_width_height() pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(), GdkPixbuf.Colorspace.RGB, True, 8, w, h, w * 4) clipboard = self.canvas.get_clipboard() clipboard.set(pb) backend_tools._register_tool_class(FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK) backend_tools._register_tool_class(FigureCanvasGTK4, _backend_gtk.RubberbandGTK) Toolbar = ToolbarGTK4 class FigureManagerGTK4(_FigureManagerGTK): _toolbar2_class = NavigationToolbar2GTK4 _toolmanager_toolbar_class = ToolbarGTK4 @_BackendGTK.export class _BackendGTK4(_BackendGTK): FigureCanvas = FigureCanvasGTK4 FigureManager = FigureManagerGTK4 # File: matplotlib-main/lib/matplotlib/backends/backend_gtk4agg.py import numpy as np from .. import cbook from . import backend_agg, backend_gtk4 from .backend_gtk4 import GLib, Gtk, _BackendGTK4 import cairo class FigureCanvasGTK4Agg(backend_agg.FigureCanvasAgg, backend_gtk4.FigureCanvasGTK4): def on_draw_event(self, widget, ctx): if self._idle_draw_id: GLib.source_remove(self._idle_draw_id) self._idle_draw_id = 0 self.draw() scale = self.device_pixel_ratio allocation = self.get_allocation() Gtk.render_background(self.get_style_context(), ctx, allocation.x, allocation.y, allocation.width, allocation.height) buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(np.asarray(self.get_renderer().buffer_rgba())) (height, width, _) = buf.shape image = cairo.ImageSurface.create_for_data(buf.ravel().data, cairo.FORMAT_ARGB32, width, height) image.set_device_scale(scale, scale) ctx.set_source_surface(image, 0, 0) ctx.paint() return False @_BackendGTK4.export class _BackendGTK4Agg(_BackendGTK4): FigureCanvas = FigureCanvasGTK4Agg # File: matplotlib-main/lib/matplotlib/backends/backend_gtk4cairo.py from contextlib import nullcontext from .backend_cairo import FigureCanvasCairo from .backend_gtk4 import GLib, Gtk, FigureCanvasGTK4, _BackendGTK4 class FigureCanvasGTK4Cairo(FigureCanvasCairo, FigureCanvasGTK4): def _set_device_pixel_ratio(self, ratio): return False def on_draw_event(self, widget, ctx): if self._idle_draw_id: GLib.source_remove(self._idle_draw_id) self._idle_draw_id = 0 self.draw() with self.toolbar._wait_cursor_for_draw_cm() if self.toolbar else nullcontext(): self._renderer.set_context(ctx) allocation = self.get_allocation() Gtk.render_background(self.get_style_context(), ctx, allocation.x, allocation.y, allocation.width, allocation.height) self.figure.draw(self._renderer) @_BackendGTK4.export class _BackendGTK4Cairo(_BackendGTK4): FigureCanvas = FigureCanvasGTK4Cairo # File: matplotlib-main/lib/matplotlib/backends/backend_macosx.py import os import matplotlib as mpl from matplotlib import _api, cbook from matplotlib._pylab_helpers import Gcf from . import _macosx from .backend_agg import FigureCanvasAgg from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, ResizeEvent, TimerBase, _allow_interrupt class TimerMac(_macosx.Timer, TimerBase): def _allow_interrupt_macos(): return _allow_interrupt(lambda rsock: _macosx.wake_on_fd_write(rsock.fileno()), _macosx.stop) class FigureCanvasMac(FigureCanvasAgg, _macosx.FigureCanvas, FigureCanvasBase): required_interactive_framework = 'macosx' _timer_cls = TimerMac manager_class = _api.classproperty(lambda cls: FigureManagerMac) def __init__(self, figure): super().__init__(figure=figure) self._draw_pending = False self._is_drawing = False self._timers = set() def draw(self): if self._is_drawing: return with cbook._setattr_cm(self, _is_drawing=True): super().draw() self.update() def draw_idle(self): if not (getattr(self, '_draw_pending', False) or getattr(self, '_is_drawing', False)): self._draw_pending = True self._single_shot_timer(self._draw_idle) def _single_shot_timer(self, callback): def callback_func(callback, timer): callback() self._timers.remove(timer) timer = self.new_timer(interval=0) timer.single_shot = True timer.add_callback(callback_func, callback, timer) self._timers.add(timer) timer.start() def _draw_idle(self): with self._idle_draw_cntx(): if not self._draw_pending: return self._draw_pending = False self.draw() def blit(self, bbox=None): super().blit(bbox) self.update() def resize(self, width, height): scale = self.figure.dpi / self.device_pixel_ratio width /= scale height /= scale self.figure.set_size_inches(width, height, forward=False) ResizeEvent('resize_event', self)._process() self.draw_idle() def start_event_loop(self, timeout=0): with _allow_interrupt_macos(): self._start_event_loop(timeout=timeout) class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2): def __init__(self, canvas): data_path = cbook._get_data_path('images') (_, tooltips, image_names, _) = zip(*NavigationToolbar2.toolitems) _macosx.NavigationToolbar2.__init__(self, canvas, tuple((str(data_path / image_name) + '.pdf' for image_name in image_names if image_name is not None)), tuple((tooltip for tooltip in tooltips if tooltip is not None))) NavigationToolbar2.__init__(self, canvas) def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1)) def remove_rubberband(self): self.canvas.remove_rubberband() def save_figure(self, *args): directory = os.path.expanduser(mpl.rcParams['savefig.directory']) filename = _macosx.choose_save_file('Save the figure', directory, self.canvas.get_default_filename()) if filename is None: return if mpl.rcParams['savefig.directory']: mpl.rcParams['savefig.directory'] = os.path.dirname(filename) self.canvas.figure.savefig(filename) class FigureManagerMac(_macosx.FigureManager, FigureManagerBase): _toolbar2_class = NavigationToolbar2Mac def __init__(self, canvas, num): self._shown = False _macosx.FigureManager.__init__(self, canvas) icon_path = str(cbook._get_data_path('images/matplotlib.pdf')) _macosx.FigureManager.set_icon(icon_path) FigureManagerBase.__init__(self, canvas, num) self._set_window_mode(mpl.rcParams['macosx.window_mode']) if self.toolbar is not None: self.toolbar.update() if mpl.is_interactive(): self.show() self.canvas.draw_idle() def _close_button_pressed(self): Gcf.destroy(self) self.canvas.flush_events() def destroy(self): while self.canvas._timers: timer = self.canvas._timers.pop() timer.stop() super().destroy() @classmethod def start_main_loop(cls): with _allow_interrupt_macos(): _macosx.show() def show(self): if self.canvas.figure.stale: self.canvas.draw_idle() if not self._shown: self._show() self._shown = True if mpl.rcParams['figure.raise_window']: self._raise() @_Backend.export class _BackendMac(_Backend): FigureCanvas = FigureCanvasMac FigureManager = FigureManagerMac mainloop = FigureManagerMac.start_main_loop # File: matplotlib-main/lib/matplotlib/backends/backend_mixed.py import numpy as np from matplotlib import cbook from .backend_agg import RendererAgg from matplotlib._tight_bbox import process_figure_for_rasterizing class MixedModeRenderer: def __init__(self, figure, width, height, dpi, vector_renderer, raster_renderer_class=None, bbox_inches_restore=None): if raster_renderer_class is None: raster_renderer_class = RendererAgg self._raster_renderer_class = raster_renderer_class self._width = width self._height = height self.dpi = dpi self._vector_renderer = vector_renderer self._raster_renderer = None self.figure = figure self._figdpi = figure.dpi self._bbox_inches_restore = bbox_inches_restore self._renderer = vector_renderer def __getattr__(self, attr): return getattr(self._renderer, attr) def start_rasterizing(self): self.figure.dpi = self.dpi if self._bbox_inches_restore: r = process_figure_for_rasterizing(self.figure, self._bbox_inches_restore) self._bbox_inches_restore = r self._raster_renderer = self._raster_renderer_class(self._width * self.dpi, self._height * self.dpi, self.dpi) self._renderer = self._raster_renderer def stop_rasterizing(self): self._renderer = self._vector_renderer height = self._height * self.dpi img = np.asarray(self._raster_renderer.buffer_rgba()) (slice_y, slice_x) = cbook._get_nonzero_slices(img[..., 3]) cropped_img = img[slice_y, slice_x] if cropped_img.size: gc = self._renderer.new_gc() self._renderer.draw_image(gc, slice_x.start * self._figdpi / self.dpi, (height - slice_y.stop) * self._figdpi / self.dpi, cropped_img[::-1]) self._raster_renderer = None self.figure.dpi = self._figdpi if self._bbox_inches_restore: r = process_figure_for_rasterizing(self.figure, self._bbox_inches_restore, self._figdpi) self._bbox_inches_restore = r # File: matplotlib-main/lib/matplotlib/backends/backend_nbagg.py """""" from base64 import b64encode import io import json import pathlib import uuid from ipykernel.comm import Comm from IPython.display import display, Javascript, HTML from matplotlib import is_interactive from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2 from .backend_webagg_core import FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg from .backend_webagg_core import TimerTornado, TimerAsyncio def connection_info(): result = ['{fig} - {socket}'.format(fig=manager.canvas.figure.get_label() or f'Figure {manager.num}', socket=manager.web_sockets) for manager in Gcf.get_all_fig_managers()] if not is_interactive(): result.append(f'Figures pending show: {len(Gcf.figs)}') return '\n'.join(result) _FONT_AWESOME_CLASSES = {'home': 'fa fa-home', 'back': 'fa fa-arrow-left', 'forward': 'fa fa-arrow-right', 'zoom_to_rect': 'fa fa-square-o', 'move': 'fa fa-arrows', 'download': 'fa fa-floppy-o', None: None} class NavigationIPy(NavigationToolbar2WebAgg): toolitems = [(text, tooltip_text, _FONT_AWESOME_CLASSES[image_file], name_of_method) for (text, tooltip_text, image_file, name_of_method) in NavigationToolbar2.toolitems + (('Download', 'Download plot', 'download', 'download'),) if image_file in _FONT_AWESOME_CLASSES] class FigureManagerNbAgg(FigureManagerWebAgg): _toolbar2_class = ToolbarCls = NavigationIPy def __init__(self, canvas, num): self._shown = False super().__init__(canvas, num) @classmethod def create_with_canvas(cls, canvas_class, figure, num): canvas = canvas_class(figure) manager = cls(canvas, num) if is_interactive(): manager.show() canvas.draw_idle() def destroy(event): canvas.mpl_disconnect(cid) Gcf.destroy(manager) cid = canvas.mpl_connect('close_event', destroy) return manager def display_js(self): display(Javascript(FigureManagerNbAgg.get_javascript())) def show(self): if not self._shown: self.display_js() self._create_comm() else: self.canvas.draw_idle() self._shown = True if hasattr(self, '_cidgcf'): self.canvas.mpl_disconnect(self._cidgcf) if not is_interactive(): from matplotlib._pylab_helpers import Gcf Gcf.figs.pop(self.num, None) def reshow(self): self._shown = False self.show() @property def connected(self): return bool(self.web_sockets) @classmethod def get_javascript(cls, stream=None): if stream is None: output = io.StringIO() else: output = stream super().get_javascript(stream=output) output.write((pathlib.Path(__file__).parent / 'web_backend/js/nbagg_mpl.js').read_text(encoding='utf-8')) if stream is None: return output.getvalue() def _create_comm(self): comm = CommSocket(self) self.add_web_socket(comm) return comm def destroy(self): self._send_event('close') for comm in list(self.web_sockets): comm.on_close() self.clearup_closed() def clearup_closed(self): self.web_sockets = {socket for socket in self.web_sockets if socket.is_open()} if len(self.web_sockets) == 0: CloseEvent('close_event', self.canvas)._process() def remove_comm(self, comm_id): self.web_sockets = {socket for socket in self.web_sockets if socket.comm.comm_id != comm_id} class FigureCanvasNbAgg(FigureCanvasWebAggCore): manager_class = FigureManagerNbAgg class CommSocket: def __init__(self, manager): self.supports_binary = None self.manager = manager self.uuid = str(uuid.uuid4()) display(HTML('
' % self.uuid)) try: self.comm = Comm('matplotlib', data={'id': self.uuid}) except AttributeError as err: raise RuntimeError('Unable to create an IPython notebook Comm instance. Are you in the IPython notebook?') from err self.comm.on_msg(self.on_message) manager = self.manager self._ext_close = False def _on_close(close_message): self._ext_close = True manager.remove_comm(close_message['content']['comm_id']) manager.clearup_closed() self.comm.on_close(_on_close) def is_open(self): return not (self._ext_close or self.comm._closed) def on_close(self): if self.is_open(): try: self.comm.close() except KeyError: pass def send_json(self, content): self.comm.send({'data': json.dumps(content)}) def send_binary(self, blob): if self.supports_binary: self.comm.send({'blob': 'image/png'}, buffers=[blob]) else: data = b64encode(blob).decode('ascii') data_uri = f'data:image/png;base64,{data}' self.comm.send({'data': data_uri}) def on_message(self, message): message = json.loads(message['content']['data']) if message['type'] == 'closing': self.on_close() self.manager.clearup_closed() elif message['type'] == 'supports_binary': self.supports_binary = message['value'] else: self.manager.handle_json(message) @_Backend.export class _BackendNbAgg(_Backend): FigureCanvas = FigureCanvasNbAgg FigureManager = FigureManagerNbAgg # File: matplotlib-main/lib/matplotlib/backends/backend_pdf.py """""" import codecs from datetime import timezone from datetime import datetime from enum import Enum from functools import total_ordering from io import BytesIO import itertools import logging import math import os import string import struct import sys import time import types import warnings import zlib import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import _api, _text_helpers, _type1font, cbook, dviread from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.figure import Figure from matplotlib.font_manager import get_font, fontManager as _fontManager from matplotlib._afm import AFM from matplotlib.ft2font import FIXED_WIDTH, ITALIC, LOAD_NO_SCALE, LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font from matplotlib.transforms import Affine2D, BboxBase from matplotlib.path import Path from matplotlib.dates import UTC from matplotlib import _path from . import _backend_pdf_ps _log = logging.getLogger(__name__) def _fill(strings, linelen=75): currpos = 0 lasti = 0 result = [] for (i, s) in enumerate(strings): length = len(s) if currpos + length < linelen: currpos += length + 1 else: result.append(b' '.join(strings[lasti:i])) lasti = i currpos = length result.append(b' '.join(strings[lasti:])) return b'\n'.join(result) def _create_pdf_info_dict(backend, metadata): source_date_epoch = os.getenv('SOURCE_DATE_EPOCH') if source_date_epoch: source_date = datetime.fromtimestamp(int(source_date_epoch), timezone.utc) source_date = source_date.replace(tzinfo=UTC) else: source_date = datetime.today() info = {'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', 'Producer': f'Matplotlib {backend} backend v{mpl.__version__}', 'CreationDate': source_date, **metadata} info = {k: v for (k, v) in info.items() if v is not None} def is_string_like(x): return isinstance(x, str) is_string_like.text_for_warning = 'an instance of str' def is_date(x): return isinstance(x, datetime) is_date.text_for_warning = 'an instance of datetime.datetime' def check_trapped(x): if isinstance(x, Name): return x.name in (b'True', b'False', b'Unknown') else: return x in ('True', 'False', 'Unknown') check_trapped.text_for_warning = 'one of {"True", "False", "Unknown"}' keywords = {'Title': is_string_like, 'Author': is_string_like, 'Subject': is_string_like, 'Keywords': is_string_like, 'Creator': is_string_like, 'Producer': is_string_like, 'CreationDate': is_date, 'ModDate': is_date, 'Trapped': check_trapped} for k in info: if k not in keywords: _api.warn_external(f'Unknown infodict keyword: {k!r}. Must be one of {set(keywords)!r}.') elif not keywords[k](info[k]): _api.warn_external(f'Bad value for infodict keyword {k}. Got {info[k]!r} which is not {keywords[k].text_for_warning}.') if 'Trapped' in info: info['Trapped'] = Name(info['Trapped']) return info def _datetime_to_pdf(d): r = d.strftime('D:%Y%m%d%H%M%S') z = d.utcoffset() if z is not None: z = z.seconds elif time.daylight: z = time.altzone else: z = time.timezone if z == 0: r += 'Z' elif z < 0: r += "+%02d'%02d'" % (-z // 3600, -z % 3600) else: r += "-%02d'%02d'" % (z // 3600, z % 3600) return r def _calculate_quad_point_coordinates(x, y, width, height, angle=0): angle = math.radians(-angle) sin_angle = math.sin(angle) cos_angle = math.cos(angle) a = x + height * sin_angle b = y + height * cos_angle c = x + width * cos_angle + height * sin_angle d = y - width * sin_angle + height * cos_angle e = x + width * cos_angle f = y - width * sin_angle return ((x, y), (e, f), (c, d), (a, b)) def _get_coordinates_of_block(x, y, width, height, angle=0): vertices = _calculate_quad_point_coordinates(x, y, width, height, angle) pad = 1e-05 if angle % 90 else 0 min_x = min((v[0] for v in vertices)) - pad min_y = min((v[1] for v in vertices)) - pad max_x = max((v[0] for v in vertices)) + pad max_y = max((v[1] for v in vertices)) + pad return (tuple(itertools.chain.from_iterable(vertices)), (min_x, min_y, max_x, max_y)) def _get_link_annotation(gc, x, y, width, height, angle=0): (quadpoints, rect) = _get_coordinates_of_block(x, y, width, height, angle) link_annotation = {'Type': Name('Annot'), 'Subtype': Name('Link'), 'Rect': rect, 'Border': [0, 0, 0], 'A': {'S': Name('URI'), 'URI': gc.get_url()}} if angle % 90: link_annotation['QuadPoints'] = quadpoints return link_annotation _str_escapes = str.maketrans({'\\': '\\\\', '(': '\\(', ')': '\\)', '\n': '\\n', '\r': '\\r'}) def pdfRepr(obj): if hasattr(obj, 'pdfRepr'): return obj.pdfRepr() elif isinstance(obj, (float, np.floating)): if not np.isfinite(obj): raise ValueError('Can only output finite numbers in PDF') r = b'%.10f' % obj return r.rstrip(b'0').rstrip(b'.') elif isinstance(obj, bool): return [b'false', b'true'][obj] elif isinstance(obj, (int, np.integer)): return b'%d' % obj elif isinstance(obj, str): return pdfRepr(obj.encode('ascii') if obj.isascii() else codecs.BOM_UTF16_BE + obj.encode('UTF-16BE')) elif isinstance(obj, bytes): return b'(' + obj.decode('latin-1').translate(_str_escapes).encode('latin-1') + b')' elif isinstance(obj, dict): return _fill([b'<<', *[Name(k).pdfRepr() + b' ' + pdfRepr(v) for (k, v) in obj.items()], b'>>']) elif isinstance(obj, (list, tuple)): return _fill([b'[', *[pdfRepr(val) for val in obj], b']']) elif obj is None: return b'null' elif isinstance(obj, datetime): return pdfRepr(_datetime_to_pdf(obj)) elif isinstance(obj, BboxBase): return _fill([pdfRepr(val) for val in obj.bounds]) else: raise TypeError(f"Don't know a PDF representation for {type(obj)} objects") def _font_supports_glyph(fonttype, glyph): if fonttype == 3: return glyph <= 255 if fonttype == 42: return glyph <= 65535 raise NotImplementedError() class Reference: def __init__(self, id): self.id = id def __repr__(self): return '' % self.id def pdfRepr(self): return b'%d 0 R' % self.id def write(self, contents, file): write = file.write write(b'%d 0 obj\n' % self.id) write(pdfRepr(contents)) write(b'\nendobj\n') @total_ordering class Name: __slots__ = ('name',) _hexify = {c: '#%02x' % c for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}} def __init__(self, name): if isinstance(name, Name): self.name = name.name else: if isinstance(name, bytes): name = name.decode('ascii') self.name = name.translate(self._hexify).encode('ascii') def __repr__(self): return '' % self.name def __str__(self): return '/' + self.name.decode('ascii') def __eq__(self, other): return isinstance(other, Name) and self.name == other.name def __lt__(self, other): return isinstance(other, Name) and self.name < other.name def __hash__(self): return hash(self.name) def pdfRepr(self): return b'/' + self.name class Verbatim: def __init__(self, x): self._x = x def pdfRepr(self): return self._x class Op(Enum): close_fill_stroke = b'b' fill_stroke = b'B' fill = b'f' closepath = b'h' close_stroke = b's' stroke = b'S' endpath = b'n' begin_text = b'BT' end_text = b'ET' curveto = b'c' rectangle = b're' lineto = b'l' moveto = b'm' concat_matrix = b'cm' use_xobject = b'Do' setgray_stroke = b'G' setgray_nonstroke = b'g' setrgb_stroke = b'RG' setrgb_nonstroke = b'rg' setcolorspace_stroke = b'CS' setcolorspace_nonstroke = b'cs' setcolor_stroke = b'SCN' setcolor_nonstroke = b'scn' setdash = b'd' setlinejoin = b'j' setlinecap = b'J' setgstate = b'gs' gsave = b'q' grestore = b'Q' textpos = b'Td' selectfont = b'Tf' textmatrix = b'Tm' show = b'Tj' showkern = b'TJ' setlinewidth = b'w' clip = b'W' shading = b'sh' def pdfRepr(self): return self.value @classmethod def paint_path(cls, fill, stroke): if stroke: if fill: return cls.fill_stroke else: return cls.stroke elif fill: return cls.fill else: return cls.endpath class Stream: __slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos') def __init__(self, id, len, file, extra=None, png=None): self.id = id self.len = len self.pdfFile = file self.file = file.fh self.compressobj = None if extra is None: self.extra = dict() else: self.extra = extra.copy() if png is not None: self.extra.update({'Filter': Name('FlateDecode'), 'DecodeParms': png}) self.pdfFile.recordXref(self.id) if mpl.rcParams['pdf.compression'] and (not png): self.compressobj = zlib.compressobj(mpl.rcParams['pdf.compression']) if self.len is None: self.file = BytesIO() else: self._writeHeader() self.pos = self.file.tell() def _writeHeader(self): write = self.file.write write(b'%d 0 obj\n' % self.id) dict = self.extra dict['Length'] = self.len if mpl.rcParams['pdf.compression']: dict['Filter'] = Name('FlateDecode') write(pdfRepr(dict)) write(b'\nstream\n') def end(self): self._flush() if self.len is None: contents = self.file.getvalue() self.len = len(contents) self.file = self.pdfFile.fh self._writeHeader() self.file.write(contents) self.file.write(b'\nendstream\nendobj\n') else: length = self.file.tell() - self.pos self.file.write(b'\nendstream\nendobj\n') self.pdfFile.writeObject(self.len, length) def write(self, data): if self.compressobj is None: self.file.write(data) else: compressed = self.compressobj.compress(data) self.file.write(compressed) def _flush(self): if self.compressobj is not None: compressed = self.compressobj.flush() self.file.write(compressed) self.compressobj = None def _get_pdf_charprocs(font_path, glyph_ids): font = get_font(font_path, hinting_factor=1) conv = 1000 / font.units_per_EM procs = {} for glyph_id in glyph_ids: g = font.load_glyph(glyph_id, LOAD_NO_SCALE) d1 = (np.array([g.horiAdvance, 0, *g.bbox]) * conv + 0.5).astype(int) (v, c) = font.get_path() v = (v * 64).astype(int) (quads,) = np.nonzero(c == 3) quads_on = quads[1::2] quads_mid_on = np.array(sorted({*quads_on} & {*quads - 1} & {*quads + 1}), int) implicit = quads_mid_on[(v[quads_mid_on] == ((v[quads_mid_on - 1] + v[quads_mid_on + 1]) / 2).astype(int)).all(axis=1)] if (font.postscript_name, glyph_id) in [('DejaVuSerif-Italic', 77), ('DejaVuSerif-Italic', 135)]: v[:, 0] -= 1 v = (v * conv + 0.5).astype(int) v[implicit] = ((v[implicit - 1] + v[implicit + 1]) / 2).astype(int) procs[font.get_glyph_name(glyph_id)] = ' '.join(map(str, d1)).encode('ascii') + b' d1\n' + _path.convert_to_string(Path(v, c), None, None, False, None, -1, [b'm', b'l', b'', b'c', b'h'], True) + b'f' return procs class PdfFile: def __init__(self, filename, metadata=None): super().__init__() self._object_seq = itertools.count(1) self.xrefTable = [[0, 65535, 'the zero object']] self.passed_in_file_object = False self.original_file_like = None self.tell_base = 0 (fh, opened) = cbook.to_filehandle(filename, 'wb', return_opened=True) if not opened: try: self.tell_base = filename.tell() except OSError: fh = BytesIO() self.original_file_like = filename else: fh = filename self.passed_in_file_object = True self.fh = fh self.currentstream = None fh.write(b'%PDF-1.4\n') fh.write(b'%\xac\xdc \xab\xba\n') self.rootObject = self.reserveObject('root') self.pagesObject = self.reserveObject('pages') self.pageList = [] self.fontObject = self.reserveObject('fonts') self._extGStateObject = self.reserveObject('extended graphics states') self.hatchObject = self.reserveObject('tiling patterns') self.gouraudObject = self.reserveObject('Gouraud triangles') self.XObjectObject = self.reserveObject('external objects') self.resourceObject = self.reserveObject('resources') root = {'Type': Name('Catalog'), 'Pages': self.pagesObject} self.writeObject(self.rootObject, root) self.infoDict = _create_pdf_info_dict('pdf', metadata or {}) self.fontNames = {} self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1)) self.dviFontInfo = {} self.type1Descriptors = {} self._character_tracker = _backend_pdf_ps.CharacterTracker() self.alphaStates = {} self._alpha_state_seq = (Name(f'A{i}') for i in itertools.count(1)) self._soft_mask_states = {} self._soft_mask_seq = (Name(f'SM{i}') for i in itertools.count(1)) self._soft_mask_groups = [] self.hatchPatterns = {} self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1)) self.gouraudTriangles = [] self._images = {} self._image_seq = (Name(f'I{i}') for i in itertools.count(1)) self.markers = {} self.multi_byte_charprocs = {} self.paths = [] self._annotations = [] self.pageAnnotations = [] procsets = [Name(x) for x in 'PDF Text ImageB ImageC ImageI'.split()] resources = {'Font': self.fontObject, 'XObject': self.XObjectObject, 'ExtGState': self._extGStateObject, 'Pattern': self.hatchObject, 'Shading': self.gouraudObject, 'ProcSet': procsets} self.writeObject(self.resourceObject, resources) def newPage(self, width, height): self.endStream() (self.width, self.height) = (width, height) contentObject = self.reserveObject('page contents') annotsObject = self.reserveObject('annotations') thePage = {'Type': Name('Page'), 'Parent': self.pagesObject, 'Resources': self.resourceObject, 'MediaBox': [0, 0, 72 * width, 72 * height], 'Contents': contentObject, 'Annots': annotsObject} pageObject = self.reserveObject('page') self.writeObject(pageObject, thePage) self.pageList.append(pageObject) self._annotations.append((annotsObject, self.pageAnnotations)) self.beginStream(contentObject.id, self.reserveObject('length of content stream')) self.output(Name('DeviceRGB'), Op.setcolorspace_stroke) self.output(Name('DeviceRGB'), Op.setcolorspace_nonstroke) self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin) self.pageAnnotations = [] def newTextnote(self, text, positionRect=[-100, -100, 0, 0]): theNote = {'Type': Name('Annot'), 'Subtype': Name('Text'), 'Contents': text, 'Rect': positionRect} self.pageAnnotations.append(theNote) def _get_subsetted_psname(self, ps_name, charmap): def toStr(n, base): if n < base: return string.ascii_uppercase[n] else: return toStr(n // base, base) + string.ascii_uppercase[n % base] hashed = hash(frozenset(charmap.keys())) % ((sys.maxsize + 1) * 2) prefix = toStr(hashed, 26) return prefix[:6] + '+' + ps_name def finalize(self): self.endStream() self._write_annotations() self.writeFonts() self.writeExtGSTates() self._write_soft_mask_groups() self.writeHatches() self.writeGouraudTriangles() xobjects = {name: ob for (image, name, ob) in self._images.values()} for tup in self.markers.values(): xobjects[tup[0]] = tup[1] for (name, value) in self.multi_byte_charprocs.items(): xobjects[name] = value for (name, path, trans, ob, join, cap, padding, filled, stroked) in self.paths: xobjects[name] = ob self.writeObject(self.XObjectObject, xobjects) self.writeImages() self.writeMarkers() self.writePathCollectionTemplates() self.writeObject(self.pagesObject, {'Type': Name('Pages'), 'Kids': self.pageList, 'Count': len(self.pageList)}) self.writeInfoDict() self.writeXref() self.writeTrailer() def close(self): self.endStream() if self.passed_in_file_object: self.fh.flush() else: if self.original_file_like is not None: self.original_file_like.write(self.fh.getvalue()) self.fh.close() def write(self, data): if self.currentstream is None: self.fh.write(data) else: self.currentstream.write(data) def output(self, *data): self.write(_fill([pdfRepr(x) for x in data])) self.write(b'\n') def beginStream(self, id, len, extra=None, png=None): assert self.currentstream is None self.currentstream = Stream(id, len, self, extra, png) def endStream(self): if self.currentstream is not None: self.currentstream.end() self.currentstream = None def outputStream(self, ref, data, *, extra=None): self.beginStream(ref.id, None, extra) self.currentstream.write(data) self.endStream() def _write_annotations(self): for (annotsObject, annotations) in self._annotations: self.writeObject(annotsObject, annotations) def fontName(self, fontprop): if isinstance(fontprop, str): filenames = [fontprop] elif mpl.rcParams['pdf.use14corefonts']: filenames = _fontManager._find_fonts_by_props(fontprop, fontext='afm', directory=RendererPdf._afm_font_dir) else: filenames = _fontManager._find_fonts_by_props(fontprop) first_Fx = None for fname in filenames: Fx = self.fontNames.get(fname) if not first_Fx: first_Fx = Fx if Fx is None: Fx = next(self._internal_font_seq) self.fontNames[fname] = Fx _log.debug('Assigning font %s = %r', Fx, fname) if not first_Fx: first_Fx = Fx return first_Fx def dviFontName(self, dvifont): dvi_info = self.dviFontInfo.get(dvifont.texname) if dvi_info is not None: return dvi_info.pdfname tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) psfont = tex_font_map[dvifont.texname] if psfont.filename is None: raise ValueError('No usable font file found for {} (TeX: {}); the font may lack a Type-1 version'.format(psfont.psname, dvifont.texname)) pdfname = next(self._internal_font_seq) _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname) self.dviFontInfo[dvifont.texname] = types.SimpleNamespace(dvifont=dvifont, pdfname=pdfname, fontfile=psfont.filename, basefont=psfont.psname, encodingfile=psfont.encoding, effects=psfont.effects) return pdfname def writeFonts(self): fonts = {} for (dviname, info) in sorted(self.dviFontInfo.items()): Fx = info.pdfname _log.debug('Embedding Type-1 font %s from dvi.', dviname) fonts[Fx] = self._embedTeXFont(info) for filename in sorted(self.fontNames): Fx = self.fontNames[filename] _log.debug('Embedding font %s.', filename) if filename.endswith('.afm'): _log.debug('Writing AFM font.') fonts[Fx] = self._write_afm_font(filename) else: _log.debug('Writing TrueType font.') chars = self._character_tracker.used.get(filename) if chars: fonts[Fx] = self.embedTTF(filename, chars) self.writeObject(self.fontObject, fonts) def _write_afm_font(self, filename): with open(filename, 'rb') as fh: font = AFM(fh) fontname = font.get_fontname() fontdict = {'Type': Name('Font'), 'Subtype': Name('Type1'), 'BaseFont': Name(fontname), 'Encoding': Name('WinAnsiEncoding')} fontdictObject = self.reserveObject('font dictionary') self.writeObject(fontdictObject, fontdict) return fontdictObject def _embedTeXFont(self, fontinfo): _log.debug('Embedding TeX font %s - fontinfo=%s', fontinfo.dvifont.texname, fontinfo.__dict__) widthsObject = self.reserveObject('font widths') self.writeObject(widthsObject, fontinfo.dvifont.widths) fontdictObject = self.reserveObject('font dictionary') fontdict = {'Type': Name('Font'), 'Subtype': Name('Type1'), 'FirstChar': 0, 'LastChar': len(fontinfo.dvifont.widths) - 1, 'Widths': widthsObject} if fontinfo.encodingfile is not None: fontdict['Encoding'] = {'Type': Name('Encoding'), 'Differences': [0, *map(Name, dviread._parse_enc(fontinfo.encodingfile))]} if fontinfo.fontfile is None: _log.warning('Because of TeX configuration (pdftex.map, see updmap option pdftexDownloadBase14) the font %s is not embedded. This is deprecated as of PDF 1.5 and it may cause the consumer application to show something that was not intended.', fontinfo.basefont) fontdict['BaseFont'] = Name(fontinfo.basefont) self.writeObject(fontdictObject, fontdict) return fontdictObject t1font = _type1font.Type1Font(fontinfo.fontfile) if fontinfo.effects: t1font = t1font.transform(fontinfo.effects) fontdict['BaseFont'] = Name(t1font.prop['FontName']) effects = (fontinfo.effects.get('slant', 0.0), fontinfo.effects.get('extend', 1.0)) fontdesc = self.type1Descriptors.get((fontinfo.fontfile, effects)) if fontdesc is None: fontdesc = self.createType1Descriptor(t1font, fontinfo.fontfile) self.type1Descriptors[fontinfo.fontfile, effects] = fontdesc fontdict['FontDescriptor'] = fontdesc self.writeObject(fontdictObject, fontdict) return fontdictObject def createType1Descriptor(self, t1font, fontfile): fontdescObject = self.reserveObject('font descriptor') fontfileObject = self.reserveObject('font file') italic_angle = t1font.prop['ItalicAngle'] fixed_pitch = t1font.prop['isFixedPitch'] flags = 0 if fixed_pitch: flags |= 1 << 0 if 0: flags |= 1 << 1 if 1: flags |= 1 << 2 else: flags |= 1 << 5 if italic_angle: flags |= 1 << 6 if 0: flags |= 1 << 16 if 0: flags |= 1 << 17 if 0: flags |= 1 << 18 ft2font = get_font(fontfile) descriptor = {'Type': Name('FontDescriptor'), 'FontName': Name(t1font.prop['FontName']), 'Flags': flags, 'FontBBox': ft2font.bbox, 'ItalicAngle': italic_angle, 'Ascent': ft2font.ascender, 'Descent': ft2font.descender, 'CapHeight': 1000, 'XHeight': 500, 'FontFile': fontfileObject, 'FontFamily': t1font.prop['FamilyName'], 'StemV': 50} self.writeObject(fontdescObject, descriptor) self.outputStream(fontfileObject, b''.join(t1font.parts[:2]), extra={'Length1': len(t1font.parts[0]), 'Length2': len(t1font.parts[1]), 'Length3': 0}) return fontdescObject def _get_xobject_glyph_name(self, filename, glyph_name): Fx = self.fontName(filename) return '-'.join([Fx.name.decode(), os.path.splitext(os.path.basename(filename))[0], glyph_name]) _identityToUnicodeCMap = b'/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo\n<< /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000> \nendcodespacerange\n%d beginbfrange\n%s\nendbfrange\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend' def embedTTF(self, filename, characters): font = get_font(filename) fonttype = mpl.rcParams['pdf.fonttype'] def cvt(length, upe=font.units_per_EM, nearest=True): value = length / upe * 1000 if nearest: return round(value) if value < 0: return math.floor(value) else: return math.ceil(value) def embedTTFType3(font, characters, descriptor): widthsObject = self.reserveObject('font widths') fontdescObject = self.reserveObject('font descriptor') fontdictObject = self.reserveObject('font dictionary') charprocsObject = self.reserveObject('character procs') differencesArray = [] (firstchar, lastchar) = (0, 255) bbox = [cvt(x, nearest=False) for x in font.bbox] fontdict = {'Type': Name('Font'), 'BaseFont': ps_name, 'FirstChar': firstchar, 'LastChar': lastchar, 'FontDescriptor': fontdescObject, 'Subtype': Name('Type3'), 'Name': descriptor['FontName'], 'FontBBox': bbox, 'FontMatrix': [0.001, 0, 0, 0.001, 0, 0], 'CharProcs': charprocsObject, 'Encoding': {'Type': Name('Encoding'), 'Differences': differencesArray}, 'Widths': widthsObject} from encodings import cp1252 def get_char_width(charcode): s = ord(cp1252.decoding_table[charcode]) width = font.load_char(s, flags=LOAD_NO_SCALE | LOAD_NO_HINTING).horiAdvance return cvt(width) with warnings.catch_warnings(): warnings.filterwarnings('ignore') widths = [get_char_width(charcode) for charcode in range(firstchar, lastchar + 1)] descriptor['MaxWidth'] = max(widths) glyph_ids = [] differences = [] multi_byte_chars = set() for c in characters: ccode = c gind = font.get_char_index(ccode) glyph_ids.append(gind) glyph_name = font.get_glyph_name(gind) if ccode <= 255: differences.append((ccode, glyph_name)) else: multi_byte_chars.add(glyph_name) differences.sort() last_c = -2 for (c, name) in differences: if c != last_c + 1: differencesArray.append(c) differencesArray.append(Name(name)) last_c = c rawcharprocs = _get_pdf_charprocs(filename, glyph_ids) charprocs = {} for charname in sorted(rawcharprocs): stream = rawcharprocs[charname] charprocDict = {} if charname in multi_byte_chars: charprocDict = {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': bbox} stream = stream[stream.find(b'd1') + 2:] charprocObject = self.reserveObject('charProc') self.outputStream(charprocObject, stream, extra=charprocDict) if charname in multi_byte_chars: name = self._get_xobject_glyph_name(filename, charname) self.multi_byte_charprocs[name] = charprocObject else: charprocs[charname] = charprocObject self.writeObject(fontdictObject, fontdict) self.writeObject(fontdescObject, descriptor) self.writeObject(widthsObject, widths) self.writeObject(charprocsObject, charprocs) return fontdictObject def embedTTFType42(font, characters, descriptor): fontdescObject = self.reserveObject('font descriptor') cidFontDictObject = self.reserveObject('CID font dictionary') type0FontDictObject = self.reserveObject('Type 0 font dictionary') cidToGidMapObject = self.reserveObject('CIDToGIDMap stream') fontfileObject = self.reserveObject('font file stream') wObject = self.reserveObject('Type 0 widths') toUnicodeMapObject = self.reserveObject('ToUnicode map') subset_str = ''.join((chr(c) for c in characters)) _log.debug('SUBSET %s characters: %s', filename, subset_str) fontdata = _backend_pdf_ps.get_glyphs_subset(filename, subset_str) _log.debug('SUBSET %s %d -> %d', filename, os.stat(filename).st_size, fontdata.getbuffer().nbytes) full_font = font font = FT2Font(fontdata) cidFontDict = {'Type': Name('Font'), 'Subtype': Name('CIDFontType2'), 'BaseFont': ps_name, 'CIDSystemInfo': {'Registry': 'Adobe', 'Ordering': 'Identity', 'Supplement': 0}, 'FontDescriptor': fontdescObject, 'W': wObject, 'CIDToGIDMap': cidToGidMapObject} type0FontDict = {'Type': Name('Font'), 'Subtype': Name('Type0'), 'BaseFont': ps_name, 'Encoding': Name('Identity-H'), 'DescendantFonts': [cidFontDictObject], 'ToUnicode': toUnicodeMapObject} descriptor['FontFile2'] = fontfileObject self.outputStream(fontfileObject, fontdata.getvalue(), extra={'Length1': fontdata.getbuffer().nbytes}) cid_to_gid_map = ['\x00'] * 65536 widths = [] max_ccode = 0 for c in characters: ccode = c gind = font.get_char_index(ccode) glyph = font.load_char(ccode, flags=LOAD_NO_SCALE | LOAD_NO_HINTING) widths.append((ccode, cvt(glyph.horiAdvance))) if ccode < 65536: cid_to_gid_map[ccode] = chr(gind) max_ccode = max(ccode, max_ccode) widths.sort() cid_to_gid_map = cid_to_gid_map[:max_ccode + 1] last_ccode = -2 w = [] max_width = 0 unicode_groups = [] for (ccode, width) in widths: if ccode != last_ccode + 1: w.append(ccode) w.append([width]) unicode_groups.append([ccode, ccode]) else: w[-1].append(width) unicode_groups[-1][1] = ccode max_width = max(max_width, width) last_ccode = ccode unicode_bfrange = [] for (start, end) in unicode_groups: if start > 65535: continue end = min(65535, end) unicode_bfrange.append(b'<%04x> <%04x> [%s]' % (start, end, b' '.join((b'<%04x>' % x for x in range(start, end + 1))))) unicode_cmap = self._identityToUnicodeCMap % (len(unicode_groups), b'\n'.join(unicode_bfrange)) glyph_ids = [] for ccode in characters: if not _font_supports_glyph(fonttype, ccode): gind = full_font.get_char_index(ccode) glyph_ids.append(gind) bbox = [cvt(x, nearest=False) for x in full_font.bbox] rawcharprocs = _get_pdf_charprocs(filename, glyph_ids) for charname in sorted(rawcharprocs): stream = rawcharprocs[charname] charprocDict = {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': bbox} stream = stream[stream.find(b'd1') + 2:] charprocObject = self.reserveObject('charProc') self.outputStream(charprocObject, stream, extra=charprocDict) name = self._get_xobject_glyph_name(filename, charname) self.multi_byte_charprocs[name] = charprocObject cid_to_gid_map = ''.join(cid_to_gid_map).encode('utf-16be') self.outputStream(cidToGidMapObject, cid_to_gid_map) self.outputStream(toUnicodeMapObject, unicode_cmap) descriptor['MaxWidth'] = max_width self.writeObject(cidFontDictObject, cidFontDict) self.writeObject(type0FontDictObject, type0FontDict) self.writeObject(fontdescObject, descriptor) self.writeObject(wObject, w) return type0FontDictObject ps_name = self._get_subsetted_psname(font.postscript_name, font.get_charmap()) ps_name = ps_name.encode('ascii', 'replace') ps_name = Name(ps_name) pclt = font.get_sfnt_table('pclt') or {'capHeight': 0, 'xHeight': 0} post = font.get_sfnt_table('post') or {'italicAngle': (0, 0)} ff = font.face_flags sf = font.style_flags flags = 0 symbolic = False if ff & FIXED_WIDTH: flags |= 1 << 0 if 0: flags |= 1 << 1 if symbolic: flags |= 1 << 2 else: flags |= 1 << 5 if sf & ITALIC: flags |= 1 << 6 if 0: flags |= 1 << 16 if 0: flags |= 1 << 17 if 0: flags |= 1 << 18 descriptor = {'Type': Name('FontDescriptor'), 'FontName': ps_name, 'Flags': flags, 'FontBBox': [cvt(x, nearest=False) for x in font.bbox], 'Ascent': cvt(font.ascender, nearest=False), 'Descent': cvt(font.descender, nearest=False), 'CapHeight': cvt(pclt['capHeight'], nearest=False), 'XHeight': cvt(pclt['xHeight']), 'ItalicAngle': post['italicAngle'][1], 'StemV': 0} if fonttype == 3: return embedTTFType3(font, characters, descriptor) elif fonttype == 42: return embedTTFType42(font, characters, descriptor) def alphaState(self, alpha): state = self.alphaStates.get(alpha, None) if state is not None: return state[0] name = next(self._alpha_state_seq) self.alphaStates[alpha] = (name, {'Type': Name('ExtGState'), 'CA': alpha[0], 'ca': alpha[1]}) return name def _soft_mask_state(self, smask): state = self._soft_mask_states.get(smask, None) if state is not None: return state[0] name = next(self._soft_mask_seq) groupOb = self.reserveObject('transparency group for soft mask') self._soft_mask_states[smask] = (name, {'Type': Name('ExtGState'), 'AIS': False, 'SMask': {'Type': Name('Mask'), 'S': Name('Luminosity'), 'BC': [1], 'G': groupOb}}) self._soft_mask_groups.append((groupOb, {'Type': Name('XObject'), 'Subtype': Name('Form'), 'FormType': 1, 'Group': {'S': Name('Transparency'), 'CS': Name('DeviceGray')}, 'Matrix': [1, 0, 0, 1, 0, 0], 'Resources': {'Shading': {'S': smask}}, 'BBox': [0, 0, 1, 1]}, [Name('S'), Op.shading])) return name def writeExtGSTates(self): self.writeObject(self._extGStateObject, dict([*self.alphaStates.values(), *self._soft_mask_states.values()])) def _write_soft_mask_groups(self): for (ob, attributes, content) in self._soft_mask_groups: self.beginStream(ob.id, None, attributes) self.output(*content) self.endStream() def hatchPattern(self, hatch_style): if hatch_style is not None: (edge, face, hatch) = hatch_style if edge is not None: edge = tuple(edge) if face is not None: face = tuple(face) hatch_style = (edge, face, hatch) pattern = self.hatchPatterns.get(hatch_style, None) if pattern is not None: return pattern name = next(self._hatch_pattern_seq) self.hatchPatterns[hatch_style] = name return name def writeHatches(self): hatchDict = dict() sidelen = 72.0 for (hatch_style, name) in self.hatchPatterns.items(): ob = self.reserveObject('hatch pattern') hatchDict[name] = ob res = {'Procsets': [Name(x) for x in 'PDF Text ImageB ImageC ImageI'.split()]} self.beginStream(ob.id, None, {'Type': Name('Pattern'), 'PatternType': 1, 'PaintType': 1, 'TilingType': 1, 'BBox': [0, 0, sidelen, sidelen], 'XStep': sidelen, 'YStep': sidelen, 'Resources': res, 'Matrix': [1, 0, 0, 1, 0, self.height * 72]}) (stroke_rgb, fill_rgb, hatch) = hatch_style self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2], Op.setrgb_stroke) if fill_rgb is not None: self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2], Op.setrgb_nonstroke, 0, 0, sidelen, sidelen, Op.rectangle, Op.fill) self.output(mpl.rcParams['hatch.linewidth'], Op.setlinewidth) self.output(*self.pathOperations(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)) self.output(Op.fill_stroke) self.endStream() self.writeObject(self.hatchObject, hatchDict) def addGouraudTriangles(self, points, colors): name = Name('GT%d' % len(self.gouraudTriangles)) ob = self.reserveObject(f'Gouraud triangle {name}') self.gouraudTriangles.append((name, ob, points, colors)) return (name, ob) def writeGouraudTriangles(self): gouraudDict = dict() for (name, ob, points, colors) in self.gouraudTriangles: gouraudDict[name] = ob shape = points.shape flat_points = points.reshape((shape[0] * shape[1], 2)) colordim = colors.shape[2] assert colordim in (1, 4) flat_colors = colors.reshape((shape[0] * shape[1], colordim)) if colordim == 4: colordim = 3 points_min = np.min(flat_points, axis=0) - (1 << 8) points_max = np.max(flat_points, axis=0) + (1 << 8) factor = 4294967295 / (points_max - points_min) self.beginStream(ob.id, None, {'ShadingType': 4, 'BitsPerCoordinate': 32, 'BitsPerComponent': 8, 'BitsPerFlag': 8, 'ColorSpace': Name('DeviceRGB' if colordim == 3 else 'DeviceGray'), 'AntiAlias': False, 'Decode': [points_min[0], points_max[0], points_min[1], points_max[1]] + [0, 1] * colordim}) streamarr = np.empty((shape[0] * shape[1],), dtype=[('flags', 'u1'), ('points', '>u4', (2,)), ('colors', 'u1', (colordim,))]) streamarr['flags'] = 0 streamarr['points'] = (flat_points - points_min) * factor streamarr['colors'] = flat_colors[:, :colordim] * 255.0 self.write(streamarr.tobytes()) self.endStream() self.writeObject(self.gouraudObject, gouraudDict) def imageObject(self, image): entry = self._images.get(id(image), None) if entry is not None: return entry[1] name = next(self._image_seq) ob = self.reserveObject(f'image {name}') self._images[id(image)] = (image, name, ob) return name def _unpack(self, im): im = im[::-1] if im.ndim == 2: return (im, None) else: rgb = im[:, :, :3] rgb = np.array(rgb, order='C') if im.shape[2] == 4: alpha = im[:, :, 3][..., None] if np.all(alpha == 255): alpha = None else: alpha = np.array(alpha, order='C') else: alpha = None return (rgb, alpha) def _writePng(self, img): buffer = BytesIO() img.save(buffer, format='png') buffer.seek(8) png_data = b'' bit_depth = palette = None while True: (length, type) = struct.unpack(b'!L4s', buffer.read(8)) if type in [b'IHDR', b'PLTE', b'IDAT']: data = buffer.read(length) if len(data) != length: raise RuntimeError('truncated data') if type == b'IHDR': bit_depth = int(data[8]) elif type == b'PLTE': palette = data elif type == b'IDAT': png_data += data elif type == b'IEND': break else: buffer.seek(length, 1) buffer.seek(4, 1) return (png_data, bit_depth, palette) def _writeImg(self, data, id, smask=None): (height, width, color_channels) = data.shape obj = {'Type': Name('XObject'), 'Subtype': Name('Image'), 'Width': width, 'Height': height, 'ColorSpace': Name({1: 'DeviceGray', 3: 'DeviceRGB'}[color_channels]), 'BitsPerComponent': 8} if smask: obj['SMask'] = smask if mpl.rcParams['pdf.compression']: if data.shape[-1] == 1: data = data.squeeze(axis=-1) png = {'Predictor': 10, 'Colors': color_channels, 'Columns': width} img = Image.fromarray(data) img_colors = img.getcolors(maxcolors=256) if color_channels == 3 and img_colors is not None: num_colors = len(img_colors) palette = np.array([comp for (_, color) in img_colors for comp in color], dtype=np.uint8) palette24 = palette[0::3].astype(np.uint32) << 16 | palette[1::3].astype(np.uint32) << 8 | palette[2::3] rgb24 = data[:, :, 0].astype(np.uint32) << 16 | data[:, :, 1].astype(np.uint32) << 8 | data[:, :, 2] indices = np.argsort(palette24).astype(np.uint8) rgb8 = indices[np.searchsorted(palette24, rgb24, sorter=indices)] img = Image.fromarray(rgb8, mode='P') img.putpalette(palette) (png_data, bit_depth, palette) = self._writePng(img) if bit_depth is None or palette is None: raise RuntimeError('invalid PNG header') palette = palette[:num_colors * 3] obj['ColorSpace'] = [Name('Indexed'), Name('DeviceRGB'), num_colors - 1, palette] obj['BitsPerComponent'] = bit_depth png['Colors'] = 1 png['BitsPerComponent'] = bit_depth else: (png_data, _, _) = self._writePng(img) else: png = None self.beginStream(id, self.reserveObject('length of image stream'), obj, png=png) if png: self.currentstream.write(png_data) else: self.currentstream.write(data.tobytes()) self.endStream() def writeImages(self): for (img, name, ob) in self._images.values(): (data, adata) = self._unpack(img) if adata is not None: smaskObject = self.reserveObject('smask') self._writeImg(adata, smaskObject.id) else: smaskObject = None self._writeImg(data, ob.id, smaskObject) def markerObject(self, path, trans, fill, stroke, lw, joinstyle, capstyle): pathops = self.pathOperations(path, trans, simplify=False) key = (tuple(pathops), bool(fill), bool(stroke), joinstyle, capstyle) result = self.markers.get(key) if result is None: name = Name('M%d' % len(self.markers)) ob = self.reserveObject('marker %d' % len(self.markers)) bbox = path.get_extents(trans) self.markers[key] = [name, ob, bbox, lw] else: if result[-1] < lw: result[-1] = lw name = result[0] return name def writeMarkers(self): for ((pathops, fill, stroke, joinstyle, capstyle), (name, ob, bbox, lw)) in self.markers.items(): bbox = bbox.padded(lw * 5) self.beginStream(ob.id, None, {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': list(bbox.extents)}) self.output(GraphicsContextPdf.joinstyles[joinstyle], Op.setlinejoin) self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) self.output(*pathops) self.output(Op.paint_path(fill, stroke)) self.endStream() def pathCollectionObject(self, gc, path, trans, padding, filled, stroked): name = Name('P%d' % len(self.paths)) ob = self.reserveObject('path %d' % len(self.paths)) self.paths.append((name, path, trans, ob, gc.get_joinstyle(), gc.get_capstyle(), padding, filled, stroked)) return name def writePathCollectionTemplates(self): for (name, path, trans, ob, joinstyle, capstyle, padding, filled, stroked) in self.paths: pathops = self.pathOperations(path, trans, simplify=False) bbox = path.get_extents(trans) if not np.all(np.isfinite(bbox.extents)): extents = [0, 0, 0, 0] else: bbox = bbox.padded(padding) extents = list(bbox.extents) self.beginStream(ob.id, None, {'Type': Name('XObject'), 'Subtype': Name('Form'), 'BBox': extents}) self.output(GraphicsContextPdf.joinstyles[joinstyle], Op.setlinejoin) self.output(GraphicsContextPdf.capstyles[capstyle], Op.setlinecap) self.output(*pathops) self.output(Op.paint_path(filled, stroked)) self.endStream() @staticmethod def pathOperations(path, transform, clip=None, simplify=None, sketch=None): return [Verbatim(_path.convert_to_string(path, transform, clip, simplify, sketch, 6, [Op.moveto.value, Op.lineto.value, b'', Op.curveto.value, Op.closepath.value], True))] def writePath(self, path, transform, clip=False, sketch=None): if clip: clip = (0.0, 0.0, self.width * 72, self.height * 72) simplify = path.should_simplify else: clip = None simplify = False cmds = self.pathOperations(path, transform, clip, simplify=simplify, sketch=sketch) self.output(*cmds) def reserveObject(self, name=''): id = next(self._object_seq) self.xrefTable.append([None, 0, name]) return Reference(id) def recordXref(self, id): self.xrefTable[id][0] = self.fh.tell() - self.tell_base def writeObject(self, object, contents): self.recordXref(object.id) object.write(contents, self) def writeXref(self): self.startxref = self.fh.tell() - self.tell_base self.write(b'xref\n0 %d\n' % len(self.xrefTable)) for (i, (offset, generation, name)) in enumerate(self.xrefTable): if offset is None: raise AssertionError('No offset for object %d (%s)' % (i, name)) else: key = b'f' if name == 'the zero object' else b'n' text = b'%010d %05d %b \n' % (offset, generation, key) self.write(text) def writeInfoDict(self): self.infoObject = self.reserveObject('info') self.writeObject(self.infoObject, self.infoDict) def writeTrailer(self): self.write(b'trailer\n') self.write(pdfRepr({'Size': len(self.xrefTable), 'Root': self.rootObject, 'Info': self.infoObject})) self.write(b'\nstartxref\n%d\n%%%%EOF\n' % self.startxref) class RendererPdf(_backend_pdf_ps.RendererPDFPSBase): _afm_font_dir = cbook._get_data_path('fonts/pdfcorefonts') _use_afm_rc_name = 'pdf.use14corefonts' def __init__(self, file, image_dpi, height, width): super().__init__(width, height) self.file = file self.gc = self.new_gc() self.image_dpi = image_dpi def finalize(self): self.file.output(*self.gc.finalize()) def check_gc(self, gc, fillcolor=None): orig_fill = getattr(gc, '_fillcolor', (0.0, 0.0, 0.0)) gc._fillcolor = fillcolor orig_alphas = getattr(gc, '_effective_alphas', (1.0, 1.0)) if gc.get_rgb() is None: gc.set_foreground((0, 0, 0, 0), isRGBA=True) if gc._forced_alpha: gc._effective_alphas = (gc._alpha, gc._alpha) elif fillcolor is None or len(fillcolor) < 4: gc._effective_alphas = (gc._rgb[3], 1.0) else: gc._effective_alphas = (gc._rgb[3], fillcolor[3]) delta = self.gc.delta(gc) if delta: self.file.output(*delta) gc._fillcolor = orig_fill gc._effective_alphas = orig_alphas def get_image_magnification(self): return self.image_dpi / 72.0 def draw_image(self, gc, x, y, im, transform=None): (h, w) = im.shape[:2] if w == 0 or h == 0: return if transform is None: gc.set_alpha(1.0) self.check_gc(gc) w = 72.0 * w / self.image_dpi h = 72.0 * h / self.image_dpi imob = self.file.imageObject(im) if transform is None: self.file.output(Op.gsave, w, 0, 0, h, x, y, Op.concat_matrix, imob, Op.use_xobject, Op.grestore) else: (tr1, tr2, tr3, tr4, tr5, tr6) = transform.frozen().to_values() self.file.output(Op.gsave, 1, 0, 0, 1, x, y, Op.concat_matrix, tr1, tr2, tr3, tr4, tr5, tr6, Op.concat_matrix, imob, Op.use_xobject, Op.grestore) def draw_path(self, gc, path, transform, rgbFace=None): self.check_gc(gc, rgbFace) self.file.writePath(path, transform, rgbFace is None and gc.get_hatch_path() is None, gc.get_sketch_params()) self.file.output(self.gc.paint()) def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): can_do_optimization = True facecolors = np.asarray(facecolors) edgecolors = np.asarray(edgecolors) if not len(facecolors): filled = False can_do_optimization = not gc.get_hatch() elif np.all(facecolors[:, 3] == facecolors[0, 3]): filled = facecolors[0, 3] != 0.0 else: can_do_optimization = False if not len(edgecolors): stroked = False elif np.all(np.asarray(linewidths) == 0.0): stroked = False elif np.all(edgecolors[:, 3] == edgecolors[0, 3]): stroked = edgecolors[0, 3] != 0.0 else: can_do_optimization = False len_path = len(paths[0].vertices) if len(paths) > 0 else 0 uses_per_path = self._iter_collection_uses_per_path(paths, all_transforms, offsets, facecolors, edgecolors) should_do_optimization = len_path + uses_per_path + 5 < len_path * uses_per_path if not can_do_optimization or not should_do_optimization: return RendererBase.draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position) padding = np.max(linewidths) path_codes = [] for (i, (path, transform)) in enumerate(self._iter_collection_raw_paths(master_transform, paths, all_transforms)): name = self.file.pathCollectionObject(gc, path, transform, padding, filled, stroked) path_codes.append(name) output = self.file.output output(*self.gc.push()) (lastx, lasty) = (0, 0) for (xo, yo, path_id, gc0, rgbFace) in self._iter_collection(gc, path_codes, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): self.check_gc(gc0, rgbFace) (dx, dy) = (xo - lastx, yo - lasty) output(1, 0, 0, 1, dx, dy, Op.concat_matrix, path_id, Op.use_xobject) (lastx, lasty) = (xo, yo) output(*self.gc.pop()) def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): len_marker_path = len(marker_path) uses = len(path) if len_marker_path * uses < len_marker_path + uses + 5: RendererBase.draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace) return self.check_gc(gc, rgbFace) fill = gc.fill(rgbFace) stroke = gc.stroke() output = self.file.output marker = self.file.markerObject(marker_path, marker_trans, fill, stroke, self.gc._linewidth, gc.get_joinstyle(), gc.get_capstyle()) output(Op.gsave) (lastx, lasty) = (0, 0) for (vertices, code) in path.iter_segments(trans, clip=(0, 0, self.file.width * 72, self.file.height * 72), simplify=False): if len(vertices): (x, y) = vertices[-2:] if not (0 <= x <= self.file.width * 72 and 0 <= y <= self.file.height * 72): continue (dx, dy) = (x - lastx, y - lasty) output(1, 0, 0, 1, dx, dy, Op.concat_matrix, marker, Op.use_xobject) (lastx, lasty) = (x, y) output(Op.grestore) def draw_gouraud_triangles(self, gc, points, colors, trans): assert len(points) == len(colors) if len(points) == 0: return assert points.ndim == 3 assert points.shape[1] == 3 assert points.shape[2] == 2 assert colors.ndim == 3 assert colors.shape[1] == 3 assert colors.shape[2] in (1, 4) shape = points.shape points = points.reshape((shape[0] * shape[1], 2)) tpoints = trans.transform(points) tpoints = tpoints.reshape(shape) (name, _) = self.file.addGouraudTriangles(tpoints, colors) output = self.file.output if colors.shape[2] == 1: gc.set_alpha(1.0) self.check_gc(gc) output(name, Op.shading) return alpha = colors[0, 0, 3] if np.allclose(alpha, colors[:, :, 3]): gc.set_alpha(alpha) self.check_gc(gc) output(name, Op.shading) else: alpha = colors[:, :, 3][:, :, None] (_, smask_ob) = self.file.addGouraudTriangles(tpoints, alpha) gstate = self.file._soft_mask_state(smask_ob) output(Op.gsave, gstate, Op.setgstate, name, Op.shading, Op.grestore) def _setup_textpos(self, x, y, angle, oldx=0, oldy=0, oldangle=0): if angle == oldangle == 0: self.file.output(x - oldx, y - oldy, Op.textpos) else: angle = math.radians(angle) self.file.output(math.cos(angle), math.sin(angle), -math.sin(angle), math.cos(angle), x, y, Op.textmatrix) self.file.output(0, 0, Op.textpos) def draw_mathtext(self, gc, x, y, s, prop, angle): (width, height, descent, glyphs, rects) = self._text2path.mathtext_parser.parse(s, 72, prop) if gc.get_url() is not None: self.file._annotations[-1][1].append(_get_link_annotation(gc, x, y, width, height, angle)) fonttype = mpl.rcParams['pdf.fonttype'] a = math.radians(angle) self.file.output(Op.gsave) self.file.output(math.cos(a), math.sin(a), -math.sin(a), math.cos(a), x, y, Op.concat_matrix) self.check_gc(gc, gc._rgb) prev_font = (None, None) (oldx, oldy) = (0, 0) unsupported_chars = [] self.file.output(Op.begin_text) for (font, fontsize, num, ox, oy) in glyphs: self.file._character_tracker.track_glyph(font, num) fontname = font.fname if not _font_supports_glyph(fonttype, num): unsupported_chars.append((font, fontsize, ox, oy, num)) else: self._setup_textpos(ox, oy, 0, oldx, oldy) (oldx, oldy) = (ox, oy) if (fontname, fontsize) != prev_font: self.file.output(self.file.fontName(fontname), fontsize, Op.selectfont) prev_font = (fontname, fontsize) self.file.output(self.encode_string(chr(num), fonttype), Op.show) self.file.output(Op.end_text) for (font, fontsize, ox, oy, num) in unsupported_chars: self._draw_xobject_glyph(font, fontsize, font.get_char_index(num), ox, oy) for (ox, oy, width, height) in rects: self.file.output(Op.gsave, ox, oy, width, height, Op.rectangle, Op.fill, Op.grestore) self.file.output(Op.grestore) def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() dvifile = texmanager.make_dvi(s, fontsize) with dviread.Dvi(dvifile, 72) as dvi: (page,) = dvi if gc.get_url() is not None: self.file._annotations[-1][1].append(_get_link_annotation(gc, x, y, page.width, page.height, angle)) (oldfont, seq) = (None, []) for (x1, y1, dvifont, glyph, width) in page.text: if dvifont != oldfont: pdfname = self.file.dviFontName(dvifont) seq += [['font', pdfname, dvifont.size]] oldfont = dvifont seq += [['text', x1, y1, [bytes([glyph])], x1 + width]] (i, curx, fontsize) = (0, 0, None) while i < len(seq) - 1: (elt, nxt) = seq[i:i + 2] if elt[0] == 'font': fontsize = elt[2] elif elt[0] == nxt[0] == 'text' and elt[2] == nxt[2]: offset = elt[4] - nxt[1] if abs(offset) < 0.1: elt[3][-1] += nxt[3][0] elt[4] += nxt[4] - nxt[1] else: elt[3] += [offset * 1000.0 / fontsize, nxt[3][0]] elt[4] = nxt[4] del seq[i + 1] continue i += 1 mytrans = Affine2D().rotate_deg(angle).translate(x, y) self.check_gc(gc, gc._rgb) self.file.output(Op.begin_text) (curx, cury, oldx, oldy) = (0, 0, 0, 0) for elt in seq: if elt[0] == 'font': self.file.output(elt[1], elt[2], Op.selectfont) elif elt[0] == 'text': (curx, cury) = mytrans.transform((elt[1], elt[2])) self._setup_textpos(curx, cury, angle, oldx, oldy) (oldx, oldy) = (curx, cury) if len(elt[3]) == 1: self.file.output(elt[3][0], Op.show) else: self.file.output(elt[3], Op.showkern) else: assert False self.file.output(Op.end_text) boxgc = self.new_gc() boxgc.copy_properties(gc) boxgc.set_linewidth(0) pathops = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] for (x1, y1, h, w) in page.boxes: path = Path([[x1, y1], [x1 + w, y1], [x1 + w, y1 + h], [x1, y1 + h], [0, 0]], pathops) self.draw_path(boxgc, path, mytrans, gc._rgb) def encode_string(self, s, fonttype): if fonttype in (1, 3): return s.encode('cp1252', 'replace') return s.encode('utf-16be', 'replace') def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): self.check_gc(gc, gc._rgb) if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) fontsize = prop.get_size_in_points() if mpl.rcParams['pdf.use14corefonts']: font = self._get_font_afm(prop) fonttype = 1 else: font = self._get_font_ttf(prop) self.file._character_tracker.track(font, s) fonttype = mpl.rcParams['pdf.fonttype'] if gc.get_url() is not None: font.set_text(s) (width, height) = font.get_width_height() self.file._annotations[-1][1].append(_get_link_annotation(gc, x, y, width / 64, height / 64, angle)) if fonttype not in [3, 42]: self.file.output(Op.begin_text, self.file.fontName(prop), fontsize, Op.selectfont) self._setup_textpos(x, y, angle) self.file.output(self.encode_string(s, fonttype), Op.show, Op.end_text) else: singlebyte_chunks = [] multibyte_glyphs = [] prev_was_multibyte = True prev_font = font for item in _text_helpers.layout(s, font, kern_mode=KERNING_UNFITTED): if _font_supports_glyph(fonttype, ord(item.char)): if prev_was_multibyte or item.ft_object != prev_font: singlebyte_chunks.append((item.ft_object, item.x, [])) prev_font = item.ft_object if item.prev_kern: singlebyte_chunks[-1][2].append(item.prev_kern) singlebyte_chunks[-1][2].append(item.char) prev_was_multibyte = False else: multibyte_glyphs.append((item.ft_object, item.x, item.glyph_idx)) prev_was_multibyte = True self.file.output(Op.gsave) a = math.radians(angle) self.file.output(math.cos(a), math.sin(a), -math.sin(a), math.cos(a), x, y, Op.concat_matrix) self.file.output(Op.begin_text) prev_start_x = 0 for (ft_object, start_x, kerns_or_chars) in singlebyte_chunks: ft_name = self.file.fontName(ft_object.fname) self.file.output(ft_name, fontsize, Op.selectfont) self._setup_textpos(start_x, 0, 0, prev_start_x, 0, 0) self.file.output([-1000 * next(group) / fontsize if tp == float else self.encode_string(''.join(group), fonttype) for (tp, group) in itertools.groupby(kerns_or_chars, type)], Op.showkern) prev_start_x = start_x self.file.output(Op.end_text) for (ft_object, start_x, glyph_idx) in multibyte_glyphs: self._draw_xobject_glyph(ft_object, fontsize, glyph_idx, start_x, 0) self.file.output(Op.grestore) def _draw_xobject_glyph(self, font, fontsize, glyph_idx, x, y): glyph_name = font.get_glyph_name(glyph_idx) name = self.file._get_xobject_glyph_name(font.fname, glyph_name) self.file.output(Op.gsave, 0.001 * fontsize, 0, 0, 0.001 * fontsize, x, y, Op.concat_matrix, Name(name), Op.use_xobject, Op.grestore) def new_gc(self): return GraphicsContextPdf(self.file) class GraphicsContextPdf(GraphicsContextBase): def __init__(self, file): super().__init__() self._fillcolor = (0.0, 0.0, 0.0) self._effective_alphas = (1.0, 1.0) self.file = file self.parent = None def __repr__(self): d = dict(self.__dict__) del d['file'] del d['parent'] return repr(d) def stroke(self): return self._linewidth > 0 and self._alpha > 0 and (len(self._rgb) <= 3 or self._rgb[3] != 0.0) def fill(self, *args): if len(args): _fillcolor = args[0] else: _fillcolor = self._fillcolor return self._hatch or (_fillcolor is not None and (len(_fillcolor) <= 3 or _fillcolor[3] != 0.0)) def paint(self): return Op.paint_path(self.fill(), self.stroke()) capstyles = {'butt': 0, 'round': 1, 'projecting': 2} joinstyles = {'miter': 0, 'round': 1, 'bevel': 2} def capstyle_cmd(self, style): return [self.capstyles[style], Op.setlinecap] def joinstyle_cmd(self, style): return [self.joinstyles[style], Op.setlinejoin] def linewidth_cmd(self, width): return [width, Op.setlinewidth] def dash_cmd(self, dashes): (offset, dash) = dashes if dash is None: dash = [] offset = 0 return [list(dash), offset, Op.setdash] def alpha_cmd(self, alpha, forced, effective_alphas): name = self.file.alphaState(effective_alphas) return [name, Op.setgstate] def hatch_cmd(self, hatch, hatch_color): if not hatch: if self._fillcolor is not None: return self.fillcolor_cmd(self._fillcolor) else: return [Name('DeviceRGB'), Op.setcolorspace_nonstroke] else: hatch_style = (hatch_color, self._fillcolor, hatch) name = self.file.hatchPattern(hatch_style) return [Name('Pattern'), Op.setcolorspace_nonstroke, name, Op.setcolor_nonstroke] def rgb_cmd(self, rgb): if mpl.rcParams['pdf.inheritcolor']: return [] if rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_stroke] else: return [*rgb[:3], Op.setrgb_stroke] def fillcolor_cmd(self, rgb): if rgb is None or mpl.rcParams['pdf.inheritcolor']: return [] elif rgb[0] == rgb[1] == rgb[2]: return [rgb[0], Op.setgray_nonstroke] else: return [*rgb[:3], Op.setrgb_nonstroke] def push(self): parent = GraphicsContextPdf(self.file) parent.copy_properties(self) parent.parent = self.parent self.parent = parent return [Op.gsave] def pop(self): assert self.parent is not None self.copy_properties(self.parent) self.parent = self.parent.parent return [Op.grestore] def clip_cmd(self, cliprect, clippath): cmds = [] while (self._cliprect, self._clippath) != (cliprect, clippath) and self.parent is not None: cmds.extend(self.pop()) if (self._cliprect, self._clippath) != (cliprect, clippath) or self.parent is None: cmds.extend(self.push()) if self._cliprect != cliprect: cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) if self._clippath != clippath: (path, affine) = clippath.get_transformed_path_and_affine() cmds.extend(PdfFile.pathOperations(path, affine, simplify=False) + [Op.clip, Op.endpath]) return cmds commands = ((('_cliprect', '_clippath'), clip_cmd), (('_alpha', '_forced_alpha', '_effective_alphas'), alpha_cmd), (('_capstyle',), capstyle_cmd), (('_fillcolor',), fillcolor_cmd), (('_joinstyle',), joinstyle_cmd), (('_linewidth',), linewidth_cmd), (('_dashes',), dash_cmd), (('_rgb',), rgb_cmd), (('_hatch', '_hatch_color'), hatch_cmd)) def delta(self, other): cmds = [] fill_performed = False for (params, cmd) in self.commands: different = False for p in params: ours = getattr(self, p) theirs = getattr(other, p) try: if ours is None or theirs is None: different = ours is not theirs else: different = bool(ours != theirs) except ValueError: ours = np.asarray(ours) theirs = np.asarray(theirs) different = ours.shape != theirs.shape or np.any(ours != theirs) if different: break if params == ('_hatch', '_hatch_color') and fill_performed: different = True if different: if params == ('_fillcolor',): fill_performed = True theirs = [getattr(other, p) for p in params] cmds.extend(cmd(self, *theirs)) for p in params: setattr(self, p, getattr(other, p)) return cmds def copy_properties(self, other): super().copy_properties(other) fillcolor = getattr(other, '_fillcolor', self._fillcolor) effective_alphas = getattr(other, '_effective_alphas', self._effective_alphas) self._fillcolor = fillcolor self._effective_alphas = effective_alphas def finalize(self): cmds = [] while self.parent is not None: cmds.extend(self.pop()) return cmds class PdfPages: _UNSET = object() def __init__(self, filename, keep_empty=_UNSET, metadata=None): self._filename = filename self._metadata = metadata self._file = None if keep_empty and keep_empty is not self._UNSET: _api.warn_deprecated('3.8', message='Keeping empty pdf files is deprecated since %(since)s and support will be removed %(removal)s.') self._keep_empty = keep_empty keep_empty = _api.deprecate_privatize_attribute('3.8') def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def _ensure_file(self): if self._file is None: self._file = PdfFile(self._filename, metadata=self._metadata) return self._file def close(self): if self._file is not None: self._file.finalize() self._file.close() self._file = None elif self._keep_empty: _api.warn_deprecated('3.8', message='Keeping empty pdf files is deprecated since %(since)s and support will be removed %(removal)s.') PdfFile(self._filename, metadata=self._metadata).close() def infodict(self): return self._ensure_file().infoDict def savefig(self, figure=None, **kwargs): if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError(f'No figure {figure}') figure = manager.canvas.figure figure.savefig(self, format='pdf', backend='pdf', **kwargs) def get_pagecount(self): return len(self._ensure_file().pageList) def attach_note(self, text, positionRect=[-100, -100, 0, 0]): self._ensure_file().newTextnote(text, positionRect) class FigureCanvasPdf(FigureCanvasBase): fixed_dpi = 72 filetypes = {'pdf': 'Portable Document Format'} def get_default_filetype(self): return 'pdf' def print_pdf(self, filename, *, bbox_inches_restore=None, metadata=None): dpi = self.figure.dpi self.figure.dpi = 72 (width, height) = self.figure.get_size_inches() if isinstance(filename, PdfPages): file = filename._ensure_file() else: file = PdfFile(filename, metadata=metadata) try: file.newPage(width, height) renderer = MixedModeRenderer(self.figure, width, height, dpi, RendererPdf(file, dpi, height, width), bbox_inches_restore=bbox_inches_restore) self.figure.draw(renderer) renderer.finalize() if not isinstance(filename, PdfPages): file.finalize() finally: if isinstance(filename, PdfPages): file.endStream() else: file.close() def draw(self): self.figure.draw_without_rendering() return super().draw() FigureManagerPdf = FigureManagerBase @_Backend.export class _BackendPdf(_Backend): FigureCanvas = FigureCanvasPdf # File: matplotlib-main/lib/matplotlib/backends/backend_pgf.py import codecs import datetime import functools from io import BytesIO import logging import math import os import pathlib import shutil import subprocess from tempfile import TemporaryDirectory import weakref from PIL import Image import matplotlib as mpl from matplotlib import _api, cbook, font_manager as fm from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, RendererBase from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.backends.backend_pdf import _create_pdf_info_dict, _datetime_to_pdf from matplotlib.path import Path from matplotlib.figure import Figure from matplotlib.font_manager import FontProperties from matplotlib._pylab_helpers import Gcf _log = logging.getLogger(__name__) _DOCUMENTCLASS = '\\documentclass{article}' def _get_preamble(): font_size_pt = FontProperties(size=mpl.rcParams['font.size']).get_size_in_points() return '\n'.join(['\\def\\mathdefault#1{#1}', '\\everymath=\\expandafter{\\the\\everymath\\displaystyle}', '\\IfFileExists{scrextend.sty}{', ' \\usepackage[fontsize=%fpt]{scrextend}' % font_size_pt, '}{', ' \\renewcommand{\\normalsize}{\\fontsize{%f}{%f}\\selectfont}' % (font_size_pt, 1.2 * font_size_pt), ' \\normalsize', '}', mpl.rcParams['pgf.preamble'], *(['\\ifdefined\\pdftexversion\\else % non-pdftex case.', ' \\usepackage{fontspec}'] + [' \\%s{%s}[Path=\\detokenize{%s/}]' % (command, path.name, path.parent.as_posix()) for (command, path) in zip(['setmainfont', 'setsansfont', 'setmonofont'], [pathlib.Path(fm.findfont(family)) for family in ['serif', 'sans\\-serif', 'monospace']])] + ['\\fi'] if mpl.rcParams['pgf.rcfonts'] else []), mpl.texmanager._usepackage_if_not_loaded('underscore', option='strings')]) latex_pt_to_in = 1.0 / 72.27 latex_in_to_pt = 1.0 / latex_pt_to_in mpl_pt_to_in = 1.0 / 72.0 mpl_in_to_pt = 1.0 / mpl_pt_to_in def _tex_escape(text): return text.replace('−', '\\ensuremath{-}') def _writeln(fh, line): fh.write(line) fh.write('%\n') def _escape_and_apply_props(s, prop): commands = [] families = {'serif': '\\rmfamily', 'sans': '\\sffamily', 'sans-serif': '\\sffamily', 'monospace': '\\ttfamily'} family = prop.get_family()[0] if family in families: commands.append(families[family]) elif not mpl.rcParams['pgf.rcfonts']: commands.append('\\fontfamily{\\familydefault}') elif any((font.name == family for font in fm.fontManager.ttflist)): commands.append('\\ifdefined\\pdftexversion\\else\\setmainfont{%s}\\rmfamily\\fi' % family) else: _log.warning('Ignoring unknown font: %s', family) size = prop.get_size_in_points() commands.append('\\fontsize{%f}{%f}' % (size, size * 1.2)) styles = {'normal': '', 'italic': '\\itshape', 'oblique': '\\slshape'} commands.append(styles[prop.get_style()]) boldstyles = ['semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'] if prop.get_weight() in boldstyles: commands.append('\\bfseries') commands.append('\\selectfont') return '{' + ''.join(commands) + '\\catcode`\\^=\\active\\def^{\\ifmmode\\sp\\else\\^{}\\fi}' + '\\catcode`\\%=\\active\\def%{\\%}' + _tex_escape(s) + '}' def _metadata_to_str(key, value): if isinstance(value, datetime.datetime): value = _datetime_to_pdf(value) elif key == 'Trapped': value = value.name.decode('ascii') else: value = str(value) return f'{key}={{{value}}}' def make_pdf_to_png_converter(): try: mpl._get_executable_info('pdftocairo') except mpl.ExecutableNotFoundError: pass else: return lambda pdffile, pngfile, dpi: subprocess.check_output(['pdftocairo', '-singlefile', '-transp', '-png', '-r', '%d' % dpi, pdffile, os.path.splitext(pngfile)[0]], stderr=subprocess.STDOUT) try: gs_info = mpl._get_executable_info('gs') except mpl.ExecutableNotFoundError: pass else: return lambda pdffile, pngfile, dpi: subprocess.check_output([gs_info.executable, '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT', '-dUseCIEColor', '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', '-sDEVICE=pngalpha', '-sOutputFile=%s' % pngfile, '-r%d' % dpi, pdffile], stderr=subprocess.STDOUT) raise RuntimeError('No suitable pdf to png renderer found.') class LatexError(Exception): def __init__(self, message, latex_output=''): super().__init__(message) self.latex_output = latex_output def __str__(self): (s,) = self.args if self.latex_output: s += '\n' + self.latex_output return s class LatexManager: @staticmethod def _build_latex_header(): latex_header = [_DOCUMENTCLASS, f"% !TeX program = {mpl.rcParams['pgf.texsystem']}", '\\usepackage{graphicx}', _get_preamble(), '\\begin{document}', '\\typeout{pgf_backend_query_start}'] return '\n'.join(latex_header) @classmethod def _get_cached_or_new(cls): return cls._get_cached_or_new_impl(cls._build_latex_header()) @classmethod @functools.lru_cache(1) def _get_cached_or_new_impl(cls, header): return cls() def _stdin_writeln(self, s): if self.latex is None: self._setup_latex_process() self.latex.stdin.write(s) self.latex.stdin.write('\n') self.latex.stdin.flush() def _expect(self, s): s = list(s) chars = [] while True: c = self.latex.stdout.read(1) chars.append(c) if chars[-len(s):] == s: break if not c: self.latex.kill() self.latex = None raise LatexError('LaTeX process halted', ''.join(chars)) return ''.join(chars) def _expect_prompt(self): return self._expect('\n*') def __init__(self): self._tmpdir = TemporaryDirectory() self.tmpdir = self._tmpdir.name self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup) self._setup_latex_process(expect_reply=False) (stdout, stderr) = self.latex.communicate('\n\\makeatletter\\@@end\n') if self.latex.returncode != 0: raise LatexError(f'LaTeX errored (probably missing font or error in preamble) while processing the following input:\n{self._build_latex_header()}', stdout) self.latex = None self._get_box_metrics = functools.lru_cache(self._get_box_metrics) def _setup_latex_process(self, *, expect_reply=True): try: self.latex = subprocess.Popen([mpl.rcParams['pgf.texsystem'], '-halt-on-error'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf-8', cwd=self.tmpdir) except FileNotFoundError as err: raise RuntimeError(f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change rcParams['pgf.texsystem'] to an available TeX implementation") from err except OSError as err: raise RuntimeError(f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err def finalize_latex(latex): latex.kill() try: latex.communicate() except RuntimeError: latex.wait() self._finalize_latex = weakref.finalize(self, finalize_latex, self.latex) self._stdin_writeln(self._build_latex_header()) if expect_reply: self._expect('*pgf_backend_query_start') self._expect_prompt() def get_width_height_descent(self, text, prop): return self._get_box_metrics(_escape_and_apply_props(text, prop)) def _get_box_metrics(self, tex): self._stdin_writeln('{\\catcode`\\^=\\active\\catcode`\\%%=\\active\\sbox0{%s}\\typeout{\\the\\wd0,\\the\\ht0,\\the\\dp0}}' % tex) try: answer = self._expect_prompt() except LatexError as err: raise ValueError('Error measuring {}\nLaTeX Output:\n{}'.format(tex, err.latex_output)) from err try: (width, height, offset) = answer.splitlines()[-3].split(',') except Exception as err: raise ValueError('Error measuring {}\nLaTeX Output:\n{}'.format(tex, answer)) from err (w, h, o) = (float(width[:-2]), float(height[:-2]), float(offset[:-2])) return (w, h + o, o) @functools.lru_cache(1) def _get_image_inclusion_command(): man = LatexManager._get_cached_or_new() man._stdin_writeln('\\includegraphics[interpolate=true]{%s}' % cbook._get_data_path('images/matplotlib.png').as_posix()) try: man._expect_prompt() return '\\includegraphics' except LatexError: LatexManager._get_cached_or_new_impl.cache_clear() return '\\pgfimage' class RendererPgf(RendererBase): def __init__(self, figure, fh): super().__init__() self.dpi = figure.dpi self.fh = fh self.figure = figure self.image_counter = 0 def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): _writeln(self.fh, '\\begin{pgfscope}') f = 1.0 / self.dpi self._print_pgf_clip(gc) self._print_pgf_path_styles(gc, rgbFace) (bl, tr) = marker_path.get_extents(marker_trans).get_points() coords = (bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f) _writeln(self.fh, '\\pgfsys@defobject{currentmarker}{\\pgfqpoint{%fin}{%fin}}{\\pgfqpoint{%fin}{%fin}}{' % coords) self._print_pgf_path(None, marker_path, marker_trans) self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0, fill=rgbFace is not None) _writeln(self.fh, '}') maxcoord = 16383 / 72.27 * self.dpi clip = (-maxcoord, -maxcoord, maxcoord, maxcoord) for (point, code) in path.iter_segments(trans, simplify=False, clip=clip): (x, y) = (point[0] * f, point[1] * f) _writeln(self.fh, '\\begin{pgfscope}') _writeln(self.fh, '\\pgfsys@transformshift{%fin}{%fin}' % (x, y)) _writeln(self.fh, '\\pgfsys@useobject{currentmarker}{}') _writeln(self.fh, '\\end{pgfscope}') _writeln(self.fh, '\\end{pgfscope}') def draw_path(self, gc, path, transform, rgbFace=None): _writeln(self.fh, '\\begin{pgfscope}') self._print_pgf_clip(gc) self._print_pgf_path_styles(gc, rgbFace) self._print_pgf_path(gc, path, transform, rgbFace) self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0, fill=rgbFace is not None) _writeln(self.fh, '\\end{pgfscope}') if gc.get_hatch(): _writeln(self.fh, '\\begin{pgfscope}') self._print_pgf_path_styles(gc, rgbFace) self._print_pgf_clip(gc) self._print_pgf_path(gc, path, transform, rgbFace) _writeln(self.fh, '\\pgfusepath{clip}') _writeln(self.fh, '\\pgfsys@defobject{currentpattern}{\\pgfqpoint{0in}{0in}}{\\pgfqpoint{1in}{1in}}{') _writeln(self.fh, '\\begin{pgfscope}') _writeln(self.fh, '\\pgfpathrectangle{\\pgfqpoint{0in}{0in}}{\\pgfqpoint{1in}{1in}}') _writeln(self.fh, '\\pgfusepath{clip}') scale = mpl.transforms.Affine2D().scale(self.dpi) self._print_pgf_path(None, gc.get_hatch_path(), scale) self._pgf_path_draw(stroke=True) _writeln(self.fh, '\\end{pgfscope}') _writeln(self.fh, '}') f = 1.0 / self.dpi ((xmin, ymin), (xmax, ymax)) = path.get_extents(transform).get_points() (xmin, xmax) = (f * xmin, f * xmax) (ymin, ymax) = (f * ymin, f * ymax) (repx, repy) = (math.ceil(xmax - xmin), math.ceil(ymax - ymin)) _writeln(self.fh, '\\pgfsys@transformshift{%fin}{%fin}' % (xmin, ymin)) for iy in range(repy): for ix in range(repx): _writeln(self.fh, '\\pgfsys@useobject{currentpattern}{}') _writeln(self.fh, '\\pgfsys@transformshift{1in}{0in}') _writeln(self.fh, '\\pgfsys@transformshift{-%din}{0in}' % repx) _writeln(self.fh, '\\pgfsys@transformshift{0in}{1in}') _writeln(self.fh, '\\end{pgfscope}') def _print_pgf_clip(self, gc): f = 1.0 / self.dpi bbox = gc.get_clip_rectangle() if bbox: (p1, p2) = bbox.get_points() (w, h) = p2 - p1 coords = (p1[0] * f, p1[1] * f, w * f, h * f) _writeln(self.fh, '\\pgfpathrectangle{\\pgfqpoint{%fin}{%fin}}{\\pgfqpoint{%fin}{%fin}}' % coords) _writeln(self.fh, '\\pgfusepath{clip}') (clippath, clippath_trans) = gc.get_clip_path() if clippath is not None: self._print_pgf_path(gc, clippath, clippath_trans) _writeln(self.fh, '\\pgfusepath{clip}') def _print_pgf_path_styles(self, gc, rgbFace): capstyles = {'butt': '\\pgfsetbuttcap', 'round': '\\pgfsetroundcap', 'projecting': '\\pgfsetrectcap'} _writeln(self.fh, capstyles[gc.get_capstyle()]) joinstyles = {'miter': '\\pgfsetmiterjoin', 'round': '\\pgfsetroundjoin', 'bevel': '\\pgfsetbeveljoin'} _writeln(self.fh, joinstyles[gc.get_joinstyle()]) has_fill = rgbFace is not None if gc.get_forced_alpha(): fillopacity = strokeopacity = gc.get_alpha() else: strokeopacity = gc.get_rgb()[3] fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0 if has_fill: _writeln(self.fh, '\\definecolor{currentfill}{rgb}{%f,%f,%f}' % tuple(rgbFace[:3])) _writeln(self.fh, '\\pgfsetfillcolor{currentfill}') if has_fill and fillopacity != 1.0: _writeln(self.fh, '\\pgfsetfillopacity{%f}' % fillopacity) lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt stroke_rgba = gc.get_rgb() _writeln(self.fh, '\\pgfsetlinewidth{%fpt}' % lw) _writeln(self.fh, '\\definecolor{currentstroke}{rgb}{%f,%f,%f}' % stroke_rgba[:3]) _writeln(self.fh, '\\pgfsetstrokecolor{currentstroke}') if strokeopacity != 1.0: _writeln(self.fh, '\\pgfsetstrokeopacity{%f}' % strokeopacity) (dash_offset, dash_list) = gc.get_dashes() if dash_list is None: _writeln(self.fh, '\\pgfsetdash{}{0pt}') else: _writeln(self.fh, '\\pgfsetdash{%s}{%fpt}' % (''.join(('{%fpt}' % dash for dash in dash_list)), dash_offset)) def _print_pgf_path(self, gc, path, transform, rgbFace=None): f = 1.0 / self.dpi bbox = gc.get_clip_rectangle() if gc else None maxcoord = 16383 / 72.27 * self.dpi if bbox and rgbFace is None: (p1, p2) = bbox.get_points() clip = (max(p1[0], -maxcoord), max(p1[1], -maxcoord), min(p2[0], maxcoord), min(p2[1], maxcoord)) else: clip = (-maxcoord, -maxcoord, maxcoord, maxcoord) for (points, code) in path.iter_segments(transform, clip=clip): if code == Path.MOVETO: (x, y) = tuple(points) _writeln(self.fh, '\\pgfpathmoveto{\\pgfqpoint{%fin}{%fin}}' % (f * x, f * y)) elif code == Path.CLOSEPOLY: _writeln(self.fh, '\\pgfpathclose') elif code == Path.LINETO: (x, y) = tuple(points) _writeln(self.fh, '\\pgfpathlineto{\\pgfqpoint{%fin}{%fin}}' % (f * x, f * y)) elif code == Path.CURVE3: (cx, cy, px, py) = tuple(points) coords = (cx * f, cy * f, px * f, py * f) _writeln(self.fh, '\\pgfpathquadraticcurveto{\\pgfqpoint{%fin}{%fin}}{\\pgfqpoint{%fin}{%fin}}' % coords) elif code == Path.CURVE4: (c1x, c1y, c2x, c2y, px, py) = tuple(points) coords = (c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f) _writeln(self.fh, '\\pgfpathcurveto{\\pgfqpoint{%fin}{%fin}}{\\pgfqpoint{%fin}{%fin}}{\\pgfqpoint{%fin}{%fin}}' % coords) sketch_params = gc.get_sketch_params() if gc else None if sketch_params is not None: (scale, length, randomness) = sketch_params if scale is not None: length *= 0.5 scale *= 2 _writeln(self.fh, '\\usepgfmodule{decorations}') _writeln(self.fh, '\\usepgflibrary{decorations.pathmorphing}') _writeln(self.fh, f'\\pgfkeys{{/pgf/decoration/.cd, segment length = {length * f:f}in, amplitude = {scale * f:f}in}}') _writeln(self.fh, f'\\pgfmathsetseed{{{int(randomness)}}}') _writeln(self.fh, '\\pgfdecoratecurrentpath{random steps}') def _pgf_path_draw(self, stroke=True, fill=False): actions = [] if stroke: actions.append('stroke') if fill: actions.append('fill') _writeln(self.fh, '\\pgfusepath{%s}' % ','.join(actions)) def option_scale_image(self): return True def option_image_nocomposite(self): return not mpl.rcParams['image.composite_image'] def draw_image(self, gc, x, y, im, transform=None): (h, w) = im.shape[:2] if w == 0 or h == 0: return if not os.path.exists(getattr(self.fh, 'name', '')): raise ValueError('streamed pgf-code does not support raster graphics, consider using the pgf-to-pdf option') path = pathlib.Path(self.fh.name) fname_img = '%s-img%d.png' % (path.stem, self.image_counter) Image.fromarray(im[::-1]).save(path.parent / fname_img) self.image_counter += 1 _writeln(self.fh, '\\begin{pgfscope}') self._print_pgf_clip(gc) f = 1.0 / self.dpi if transform is None: _writeln(self.fh, '\\pgfsys@transformshift{%fin}{%fin}' % (x * f, y * f)) (w, h) = (w * f, h * f) else: (tr1, tr2, tr3, tr4, tr5, tr6) = transform.frozen().to_values() _writeln(self.fh, '\\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}' % (tr1 * f, tr2 * f, tr3 * f, tr4 * f, (tr5 + x) * f, (tr6 + y) * f)) w = h = 1 interp = str(transform is None).lower() _writeln(self.fh, '\\pgftext[left,bottom]{%s[interpolate=%s,width=%fin,height=%fin]{%s}}' % (_get_image_inclusion_command(), interp, w, h, fname_img)) _writeln(self.fh, '\\end{pgfscope}') def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): self.draw_text(gc, x, y, s, prop, angle, ismath='TeX', mtext=mtext) def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): s = _escape_and_apply_props(s, prop) _writeln(self.fh, '\\begin{pgfscope}') self._print_pgf_clip(gc) alpha = gc.get_alpha() if alpha != 1.0: _writeln(self.fh, '\\pgfsetfillopacity{%f}' % alpha) _writeln(self.fh, '\\pgfsetstrokeopacity{%f}' % alpha) rgb = tuple(gc.get_rgb())[:3] _writeln(self.fh, '\\definecolor{textcolor}{rgb}{%f,%f,%f}' % rgb) _writeln(self.fh, '\\pgfsetstrokecolor{textcolor}') _writeln(self.fh, '\\pgfsetfillcolor{textcolor}') s = '\\color{textcolor}' + s dpi = self.figure.dpi text_args = [] if mtext and ((angle == 0 or mtext.get_rotation_mode() == 'anchor') and mtext.get_verticalalignment() != 'center_baseline'): pos = mtext.get_unitless_position() (x, y) = mtext.get_transform().transform(pos) halign = {'left': 'left', 'right': 'right', 'center': ''} valign = {'top': 'top', 'bottom': 'bottom', 'baseline': 'base', 'center': ''} text_args.extend([f'x={x / dpi:f}in', f'y={y / dpi:f}in', halign[mtext.get_horizontalalignment()], valign[mtext.get_verticalalignment()]]) else: text_args.append(f'x={x / dpi:f}in, y={y / dpi:f}in, left, base') if angle != 0: text_args.append('rotate=%f' % angle) _writeln(self.fh, '\\pgftext[%s]{%s}' % (','.join(text_args), s)) _writeln(self.fh, '\\end{pgfscope}') def get_text_width_height_descent(self, s, prop, ismath): (w, h, d) = LatexManager._get_cached_or_new().get_width_height_descent(s, prop) f = mpl_pt_to_in * self.dpi return (w * f, h * f, d * f) def flipy(self): return False def get_canvas_width_height(self): return (self.figure.get_figwidth() * self.dpi, self.figure.get_figheight() * self.dpi) def points_to_pixels(self, points): return points * mpl_pt_to_in * self.dpi class FigureCanvasPgf(FigureCanvasBase): filetypes = {'pgf': 'LaTeX PGF picture', 'pdf': 'LaTeX compiled PGF picture', 'png': 'Portable Network Graphics'} def get_default_filetype(self): return 'pdf' def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None): header_text = '%% Creator: Matplotlib, PGF backend\n%%\n%% To include the figure in your LaTeX document, write\n%% \\input{.pgf}\n%%\n%% Make sure the required packages are loaded in your preamble\n%% \\usepackage{pgf}\n%%\n%% Also ensure that all the required font packages are loaded; for instance,\n%% the lmodern package is sometimes necessary when using math font.\n%% \\usepackage{lmodern}\n%%\n%% Figures using additional raster images can only be included by \\input if\n%% they are in the same directory as the main LaTeX file. For loading figures\n%% from other directories you can use the `import` package\n%% \\usepackage{import}\n%%\n%% and then include the figures with\n%% \\import{}{.pgf}\n%%\n' header_info_preamble = ['%% Matplotlib used the following preamble'] for line in _get_preamble().splitlines(): header_info_preamble.append('%% ' + line) header_info_preamble.append('%%') header_info_preamble = '\n'.join(header_info_preamble) (w, h) = (self.figure.get_figwidth(), self.figure.get_figheight()) dpi = self.figure.dpi fh.write(header_text) fh.write(header_info_preamble) fh.write('\n') _writeln(fh, '\\begingroup') _writeln(fh, '\\makeatletter') _writeln(fh, '\\begin{pgfpicture}') _writeln(fh, '\\pgfpathrectangle{\\pgfpointorigin}{\\pgfqpoint{%fin}{%fin}}' % (w, h)) _writeln(fh, '\\pgfusepath{use as bounding box, clip}') renderer = MixedModeRenderer(self.figure, w, h, dpi, RendererPgf(self.figure, fh), bbox_inches_restore=bbox_inches_restore) self.figure.draw(renderer) _writeln(fh, '\\end{pgfpicture}') _writeln(fh, '\\makeatother') _writeln(fh, '\\endgroup') def print_pgf(self, fname_or_fh, **kwargs): with cbook.open_file_cm(fname_or_fh, 'w', encoding='utf-8') as file: if not cbook.file_requires_unicode(file): file = codecs.getwriter('utf-8')(file) self._print_pgf_to_fh(file, **kwargs) def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs): (w, h) = self.figure.get_size_inches() info_dict = _create_pdf_info_dict('pgf', metadata or {}) pdfinfo = ','.join((_metadata_to_str(k, v) for (k, v) in info_dict.items())) with TemporaryDirectory() as tmpdir: tmppath = pathlib.Path(tmpdir) self.print_pgf(tmppath / 'figure.pgf', **kwargs) (tmppath / 'figure.tex').write_text('\n'.join([_DOCUMENTCLASS, '\\usepackage[pdfinfo={%s}]{hyperref}' % pdfinfo, '\\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}' % (w, h), '\\usepackage{pgf}', _get_preamble(), '\\begin{document}', '\\centering', '\\input{figure.pgf}', '\\end{document}']), encoding='utf-8') texcommand = mpl.rcParams['pgf.texsystem'] cbook._check_and_log_subprocess([texcommand, '-interaction=nonstopmode', '-halt-on-error', 'figure.tex'], _log, cwd=tmpdir) with (tmppath / 'figure.pdf').open('rb') as orig, cbook.open_file_cm(fname_or_fh, 'wb') as dest: shutil.copyfileobj(orig, dest) def print_png(self, fname_or_fh, **kwargs): converter = make_pdf_to_png_converter() with TemporaryDirectory() as tmpdir: tmppath = pathlib.Path(tmpdir) pdf_path = tmppath / 'figure.pdf' png_path = tmppath / 'figure.png' self.print_pdf(pdf_path, **kwargs) converter(pdf_path, png_path, dpi=self.figure.dpi) with png_path.open('rb') as orig, cbook.open_file_cm(fname_or_fh, 'wb') as dest: shutil.copyfileobj(orig, dest) def get_renderer(self): return RendererPgf(self.figure, None) def draw(self): self.figure.draw_without_rendering() return super().draw() FigureManagerPgf = FigureManagerBase @_Backend.export class _BackendPgf(_Backend): FigureCanvas = FigureCanvasPgf class PdfPages: _UNSET = object() def __init__(self, filename, *, keep_empty=_UNSET, metadata=None): self._output_name = filename self._n_figures = 0 if keep_empty and keep_empty is not self._UNSET: _api.warn_deprecated('3.8', message='Keeping empty pdf files is deprecated since %(since)s and support will be removed %(removal)s.') self._keep_empty = keep_empty self._metadata = (metadata or {}).copy() self._info_dict = _create_pdf_info_dict('pgf', self._metadata) self._file = BytesIO() keep_empty = _api.deprecate_privatize_attribute('3.8') def _write_header(self, width_inches, height_inches): pdfinfo = ','.join((_metadata_to_str(k, v) for (k, v) in self._info_dict.items())) latex_header = '\n'.join([_DOCUMENTCLASS, '\\usepackage[pdfinfo={%s}]{hyperref}' % pdfinfo, '\\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}' % (width_inches, height_inches), '\\usepackage{pgf}', _get_preamble(), '\\setlength{\\parindent}{0pt}', '\\begin{document}%']) self._file.write(latex_header.encode('utf-8')) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def close(self): self._file.write(b'\\end{document}\\n') if self._n_figures > 0: self._run_latex() elif self._keep_empty: _api.warn_deprecated('3.8', message='Keeping empty pdf files is deprecated since %(since)s and support will be removed %(removal)s.') open(self._output_name, 'wb').close() self._file.close() def _run_latex(self): texcommand = mpl.rcParams['pgf.texsystem'] with TemporaryDirectory() as tmpdir: tex_source = pathlib.Path(tmpdir, 'pdf_pages.tex') tex_source.write_bytes(self._file.getvalue()) cbook._check_and_log_subprocess([texcommand, '-interaction=nonstopmode', '-halt-on-error', tex_source], _log, cwd=tmpdir) shutil.move(tex_source.with_suffix('.pdf'), self._output_name) def savefig(self, figure=None, **kwargs): if not isinstance(figure, Figure): if figure is None: manager = Gcf.get_active() else: manager = Gcf.get_fig_manager(figure) if manager is None: raise ValueError(f'No figure {figure}') figure = manager.canvas.figure (width, height) = figure.get_size_inches() if self._n_figures == 0: self._write_header(width, height) else: self._file.write(b'\\newpage\\ifdefined\\pdfpagewidth\\pdfpagewidth\\else\\pagewidth\\fi=%fin\\ifdefined\\pdfpageheight\\pdfpageheight\\else\\pageheight\\fi=%fin%%\n' % (width, height)) figure.savefig(self._file, format='pgf', backend='pgf', **kwargs) self._n_figures += 1 def get_pagecount(self): return self._n_figures # File: matplotlib-main/lib/matplotlib/backends/backend_ps.py """""" import codecs import datetime from enum import Enum import functools from io import StringIO import itertools import logging import math import os import pathlib import shutil from tempfile import TemporaryDirectory import time import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, _path, _text_helpers from matplotlib._afm import AFM from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, RendererBase from matplotlib.cbook import is_writable_file_like, file_requires_unicode from matplotlib.font_manager import get_font from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font from matplotlib._ttconv import convert_ttf_to_ps from matplotlib._mathtext_data import uni2type1 from matplotlib.path import Path from matplotlib.texmanager import TexManager from matplotlib.transforms import Affine2D from matplotlib.backends.backend_mixed import MixedModeRenderer from . import _backend_pdf_ps _log = logging.getLogger(__name__) debugPS = False @_api.caching_module_getattr class __getattr__: psDefs = _api.deprecated('3.8', obj_type='')(property(lambda self: _psDefs)) papersize = {'letter': (8.5, 11), 'legal': (8.5, 14), 'ledger': (11, 17), 'a0': (33.11, 46.81), 'a1': (23.39, 33.11), 'a2': (16.54, 23.39), 'a3': (11.69, 16.54), 'a4': (8.27, 11.69), 'a5': (5.83, 8.27), 'a6': (4.13, 5.83), 'a7': (2.91, 4.13), 'a8': (2.05, 2.91), 'a9': (1.46, 2.05), 'a10': (1.02, 1.46), 'b0': (40.55, 57.32), 'b1': (28.66, 40.55), 'b2': (20.27, 28.66), 'b3': (14.33, 20.27), 'b4': (10.11, 14.33), 'b5': (7.16, 10.11), 'b6': (5.04, 7.16), 'b7': (3.58, 5.04), 'b8': (2.51, 3.58), 'b9': (1.76, 2.51), 'b10': (1.26, 1.76)} def _get_papertype(w, h): for (key, (pw, ph)) in sorted(papersize.items(), reverse=True): if key.startswith('l'): continue if w < pw and h < ph: return key return 'a0' def _nums_to_str(*args, sep=' '): return sep.join((f'{arg:1.3f}'.rstrip('0').rstrip('.') for arg in args)) def _move_path_to_path_or_stream(src, dst): if is_writable_file_like(dst): fh = open(src, encoding='latin-1') if file_requires_unicode(dst) else open(src, 'rb') with fh: shutil.copyfileobj(fh, dst) else: shutil.move(src, dst, copy_function=shutil.copyfile) def _font_to_ps_type3(font_path, chars): font = get_font(font_path, hinting_factor=1) glyph_ids = [font.get_char_index(c) for c in chars] preamble = '%!PS-Adobe-3.0 Resource-Font\n%%Creator: Converted from TrueType to Type 3 by Matplotlib.\n10 dict begin\n/FontName /{font_name} def\n/PaintType 0 def\n/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def\n/FontBBox [{bbox}] def\n/FontType 3 def\n/Encoding [{encoding}] def\n/CharStrings {num_glyphs} dict dup begin\n/.notdef 0 def\n'.format(font_name=font.postscript_name, inv_units_per_em=1 / font.units_per_EM, bbox=' '.join(map(str, font.bbox)), encoding=' '.join((f'/{font.get_glyph_name(glyph_id)}' for glyph_id in glyph_ids)), num_glyphs=len(glyph_ids) + 1) postamble = '\nend readonly def\n\n/BuildGlyph {\n exch begin\n CharStrings exch\n 2 copy known not {pop /.notdef} if\n true 3 1 roll get exec\n end\n} _d\n\n/BuildChar {\n 1 index /Encoding get exch get\n 1 index /BuildGlyph get exec\n} _d\n\nFontName currentdict end definefont pop\n' entries = [] for glyph_id in glyph_ids: g = font.load_glyph(glyph_id, LOAD_NO_SCALE) (v, c) = font.get_path() entries.append('/%(name)s{%(bbox)s sc\n' % {'name': font.get_glyph_name(glyph_id), 'bbox': ' '.join(map(str, [g.horiAdvance, 0, *g.bbox]))} + _path.convert_to_string(Path(v * 64, c), None, None, False, None, 0, [b'm', b'l', b'', b'c', b''], True).decode('ascii') + 'ce} _d') return preamble + '\n'.join(entries) + postamble def _font_to_ps_type42(font_path, chars, fh): subset_str = ''.join((chr(c) for c in chars)) _log.debug('SUBSET %s characters: %s', font_path, subset_str) try: fontdata = _backend_pdf_ps.get_glyphs_subset(font_path, subset_str) _log.debug('SUBSET %s %d -> %d', font_path, os.stat(font_path).st_size, fontdata.getbuffer().nbytes) font = FT2Font(fontdata) glyph_ids = [font.get_char_index(c) for c in chars] with TemporaryDirectory() as tmpdir: tmpfile = os.path.join(tmpdir, 'tmp.ttf') with open(tmpfile, 'wb') as tmp: tmp.write(fontdata.getvalue()) convert_ttf_to_ps(os.fsencode(tmpfile), fh, 42, glyph_ids) except RuntimeError: _log.warning('The PostScript backend does not currently support the selected font.') raise def _log_if_debug_on(meth): @functools.wraps(meth) def wrapper(self, *args, **kwargs): if debugPS: self._pswriter.write(f'% {meth.__name__}\n') return meth(self, *args, **kwargs) return wrapper class RendererPS(_backend_pdf_ps.RendererPDFPSBase): _afm_font_dir = cbook._get_data_path('fonts/afm') _use_afm_rc_name = 'ps.useafm' def __init__(self, width, height, pswriter, imagedpi=72): super().__init__(width, height) self._pswriter = pswriter if mpl.rcParams['text.usetex']: self.textcnt = 0 self.psfrag = [] self.imagedpi = imagedpi self.color = None self.linewidth = None self.linejoin = None self.linecap = None self.linedash = None self.fontname = None self.fontsize = None self._hatches = {} self.image_magnification = imagedpi / 72 self._clip_paths = {} self._path_collection_id = 0 self._character_tracker = _backend_pdf_ps.CharacterTracker() self._logwarn_once = functools.cache(_log.warning) def _is_transparent(self, rgb_or_rgba): if rgb_or_rgba is None: return True elif len(rgb_or_rgba) == 4: if rgb_or_rgba[3] == 0: return True if rgb_or_rgba[3] != 1: self._logwarn_once('The PostScript backend does not support transparency; partially transparent artists will be rendered opaque.') return False else: return False def set_color(self, r, g, b, store=True): if (r, g, b) != self.color: self._pswriter.write(f'{_nums_to_str(r)} setgray\n' if r == g == b else f'{_nums_to_str(r, g, b)} setrgbcolor\n') if store: self.color = (r, g, b) def set_linewidth(self, linewidth, store=True): linewidth = float(linewidth) if linewidth != self.linewidth: self._pswriter.write(f'{_nums_to_str(linewidth)} setlinewidth\n') if store: self.linewidth = linewidth @staticmethod def _linejoin_cmd(linejoin): linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[linejoin] return f'{linejoin:d} setlinejoin\n' def set_linejoin(self, linejoin, store=True): if linejoin != self.linejoin: self._pswriter.write(self._linejoin_cmd(linejoin)) if store: self.linejoin = linejoin @staticmethod def _linecap_cmd(linecap): linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[linecap] return f'{linecap:d} setlinecap\n' def set_linecap(self, linecap, store=True): if linecap != self.linecap: self._pswriter.write(self._linecap_cmd(linecap)) if store: self.linecap = linecap def set_linedash(self, offset, seq, store=True): if self.linedash is not None: (oldo, oldseq) = self.linedash if np.array_equal(seq, oldseq) and oldo == offset: return self._pswriter.write(f'[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n' if seq is not None and len(seq) else '[] 0 setdash\n') if store: self.linedash = (offset, seq) def set_font(self, fontname, fontsize, store=True): if (fontname, fontsize) != (self.fontname, self.fontsize): self._pswriter.write(f'/{fontname} {fontsize:1.3f} selectfont\n') if store: self.fontname = fontname self.fontsize = fontsize def create_hatch(self, hatch): sidelen = 72 if hatch in self._hatches: return self._hatches[hatch] name = 'H%d' % len(self._hatches) linewidth = mpl.rcParams['hatch.linewidth'] pageheight = self.height * 72 self._pswriter.write(f' << /PatternType 1\n /PaintType 2\n /TilingType 2\n /BBox[0 0 {sidelen:d} {sidelen:d}]\n /XStep {sidelen:d}\n /YStep {sidelen:d}\n\n /PaintProc {{\n pop\n {linewidth:g} setlinewidth\n{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}\n gsave\n fill\n grestore\n stroke\n }} bind\n >>\n matrix\n 0 {pageheight:g} translate\n makepattern\n /{name} exch def\n') self._hatches[hatch] = name return name def get_image_magnification(self): return self.image_magnification def _convert_path(self, path, transform, clip=False, simplify=None): if clip: clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0) else: clip = None return _path.convert_to_string(path, transform, clip, simplify, None, 6, [b'm', b'l', b'', b'c', b'cl'], True).decode('ascii') def _get_clip_cmd(self, gc): clip = [] rect = gc.get_clip_rectangle() if rect is not None: clip.append(f'{_nums_to_str(*rect.p0, *rect.size)} rectclip\n') (path, trf) = gc.get_clip_path() if path is not None: key = (path, id(trf)) custom_clip_cmd = self._clip_paths.get(key) if custom_clip_cmd is None: custom_clip_cmd = 'c%d' % len(self._clip_paths) self._pswriter.write(f'/{custom_clip_cmd} {{\n{self._convert_path(path, trf, simplify=False)}\nclip\nnewpath\n}} bind def\n') self._clip_paths[key] = custom_clip_cmd clip.append(f'{custom_clip_cmd}\n') return ''.join(clip) @_log_if_debug_on def draw_image(self, gc, x, y, im, transform=None): (h, w) = im.shape[:2] imagecmd = 'false 3 colorimage' data = im[::-1, :, :3] hexdata = data.tobytes().hex('\n', -64) if transform is None: matrix = '1 0 0 1 0 0' xscale = w / self.image_magnification yscale = h / self.image_magnification else: matrix = ' '.join(map(str, transform.frozen().to_values())) xscale = 1.0 yscale = 1.0 self._pswriter.write(f'gsave\n{self._get_clip_cmd(gc)}\n{x:g} {y:g} translate\n[{matrix}] concat\n{xscale:g} {yscale:g} scale\n/DataString {w:d} string def\n{w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]\n{{\ncurrentfile DataString readhexstring pop\n}} bind {imagecmd}\n{hexdata}\ngrestore\n') @_log_if_debug_on def draw_path(self, gc, path, transform, rgbFace=None): clip = rgbFace is None and gc.get_hatch_path() is None simplify = path.should_simplify and clip ps = self._convert_path(path, transform, clip=clip, simplify=simplify) self._draw_ps(ps, gc, rgbFace) @_log_if_debug_on def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): ps_color = None if self._is_transparent(rgbFace) else f'{_nums_to_str(rgbFace[0])} setgray' if rgbFace[0] == rgbFace[1] == rgbFace[2] else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor' ps_cmd = ['/o {', 'gsave', 'newpath', 'translate'] lw = gc.get_linewidth() alpha = gc.get_alpha() if gc.get_forced_alpha() or len(gc.get_rgb()) == 3 else gc.get_rgb()[3] stroke = lw > 0 and alpha > 0 if stroke: ps_cmd.append('%.1f setlinewidth' % lw) ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle())) ps_cmd.append(self._linecap_cmd(gc.get_capstyle())) ps_cmd.append(self._convert_path(marker_path, marker_trans, simplify=False)) if rgbFace: if stroke: ps_cmd.append('gsave') if ps_color: ps_cmd.extend([ps_color, 'fill']) if stroke: ps_cmd.append('grestore') if stroke: ps_cmd.append('stroke') ps_cmd.extend(['grestore', '} bind def']) for (vertices, code) in path.iter_segments(trans, clip=(0, 0, self.width * 72, self.height * 72), simplify=False): if len(vertices): (x, y) = vertices[-2:] ps_cmd.append(f'{x:g} {y:g} o') ps = '\n'.join(ps_cmd) self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False) @_log_if_debug_on def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): len_path = len(paths[0].vertices) if len(paths) > 0 else 0 uses_per_path = self._iter_collection_uses_per_path(paths, all_transforms, offsets, facecolors, edgecolors) should_do_optimization = len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path if not should_do_optimization: return RendererBase.draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position) path_codes = [] for (i, (path, transform)) in enumerate(self._iter_collection_raw_paths(master_transform, paths, all_transforms)): name = 'p%d_%d' % (self._path_collection_id, i) path_bytes = self._convert_path(path, transform, simplify=False) self._pswriter.write(f'/{name} {{\nnewpath\ntranslate\n{path_bytes}\n}} bind def\n') path_codes.append(name) for (xo, yo, path_id, gc0, rgbFace) in self._iter_collection(gc, path_codes, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): ps = f'{xo:g} {yo:g} {path_id}' self._draw_ps(ps, gc0, rgbFace) self._path_collection_id += 1 @_log_if_debug_on def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): if self._is_transparent(gc.get_rgb()): return if not hasattr(self, 'psfrag'): self._logwarn_once("The PS backend determines usetex status solely based on rcParams['text.usetex'] and does not support having usetex=True only for some elements; this element will thus be rendered as if usetex=False.") self.draw_text(gc, x, y, s, prop, angle, False, mtext) return (w, h, bl) = self.get_text_width_height_descent(s, prop, ismath='TeX') fontsize = prop.get_size_in_points() thetext = 'psmarker%d' % self.textcnt color = _nums_to_str(*gc.get_rgb()[:3], sep=',') fontcmd = {'sans-serif': '{\\sffamily %s}', 'monospace': '{\\ttfamily %s}'}.get(mpl.rcParams['font.family'][0], '{\\rmfamily %s}') s = fontcmd % s tex = '\\color[rgb]{%s} %s' % (color, s) rangle = np.radians(angle + 90) pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle)) self.psfrag.append('\\psfrag{%s}[bl][bl][1][%f]{\\fontsize{%f}{%f}%s}' % (thetext, angle, fontsize, fontsize * 1.25, tex)) self._pswriter.write(f'gsave\n{pos} moveto\n({thetext})\nshow\ngrestore\n') self.textcnt += 1 @_log_if_debug_on def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): if self._is_transparent(gc.get_rgb()): return if ismath == 'TeX': return self.draw_tex(gc, x, y, s, prop, angle) if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) stream = [] if mpl.rcParams['ps.useafm']: font = self._get_font_afm(prop) ps_name = font.postscript_name.encode('ascii', 'replace').decode('ascii') scale = 0.001 * prop.get_size_in_points() thisx = 0 last_name = None for c in s: name = uni2type1.get(ord(c), f'uni{ord(c):04X}') try: width = font.get_width_from_char_name(name) except KeyError: name = 'question' width = font.get_width_char('?') kern = font.get_kern_dist_from_name(last_name, name) last_name = name thisx += kern * scale stream.append((ps_name, thisx, name)) thisx += width * scale else: font = self._get_font_ttf(prop) self._character_tracker.track(font, s) for item in _text_helpers.layout(s, font): ps_name = item.ft_object.postscript_name.encode('ascii', 'replace').decode('ascii') glyph_name = item.ft_object.get_glyph_name(item.glyph_idx) stream.append((ps_name, item.x, glyph_name)) self.set_color(*gc.get_rgb()) for (ps_name, group) in itertools.groupby(stream, lambda entry: entry[0]): self.set_font(ps_name, prop.get_size_in_points(), False) thetext = '\n'.join((f'{x:g} 0 m /{name:s} glyphshow' for (_, x, name) in group)) self._pswriter.write(f'gsave\n{self._get_clip_cmd(gc)}\n{x:g} {y:g} translate\n{angle:g} rotate\n{thetext}\ngrestore\n') @_log_if_debug_on def draw_mathtext(self, gc, x, y, s, prop, angle): (width, height, descent, glyphs, rects) = self._text2path.mathtext_parser.parse(s, 72, prop) self.set_color(*gc.get_rgb()) self._pswriter.write(f'gsave\n{x:g} {y:g} translate\n{angle:g} rotate\n') lastfont = None for (font, fontsize, num, ox, oy) in glyphs: self._character_tracker.track_glyph(font, num) if (font.postscript_name, fontsize) != lastfont: lastfont = (font.postscript_name, fontsize) self._pswriter.write(f'/{font.postscript_name} {fontsize} selectfont\n') glyph_name = font.get_name_char(chr(num)) if isinstance(font, AFM) else font.get_glyph_name(font.get_char_index(num)) self._pswriter.write(f'{ox:g} {oy:g} moveto\n/{glyph_name} glyphshow\n') for (ox, oy, w, h) in rects: self._pswriter.write(f'{ox} {oy} {w} {h} rectfill\n') self._pswriter.write('grestore\n') @_log_if_debug_on def draw_gouraud_triangles(self, gc, points, colors, trans): assert len(points) == len(colors) if len(points) == 0: return assert points.ndim == 3 assert points.shape[1] == 3 assert points.shape[2] == 2 assert colors.ndim == 3 assert colors.shape[1] == 3 assert colors.shape[2] == 4 shape = points.shape flat_points = points.reshape((shape[0] * shape[1], 2)) flat_points = trans.transform(flat_points) flat_colors = colors.reshape((shape[0] * shape[1], 4)) points_min = np.min(flat_points, axis=0) - (1 << 12) points_max = np.max(flat_points, axis=0) + (1 << 12) factor = np.ceil((2 ** 32 - 1) / (points_max - points_min)) (xmin, ymin) = points_min (xmax, ymax) = points_max data = np.empty(shape[0] * shape[1], dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')]) data['flags'] = 0 data['points'] = (flat_points - points_min) * factor data['colors'] = flat_colors[:, :3] * 255.0 hexdata = data.tobytes().hex('\n', -64) self._pswriter.write(f'gsave\n<< /ShadingType 4\n /ColorSpace [/DeviceRGB]\n /BitsPerCoordinate 32\n /BitsPerComponent 8\n /BitsPerFlag 8\n /AntiAlias true\n /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]\n /DataSource <\n{hexdata}\n>\n>>\nshfill\ngrestore\n') def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True): write = self._pswriter.write mightstroke = gc.get_linewidth() > 0 and (not self._is_transparent(gc.get_rgb())) if not mightstroke: stroke = False if self._is_transparent(rgbFace): fill = False hatch = gc.get_hatch() if mightstroke: self.set_linewidth(gc.get_linewidth()) self.set_linejoin(gc.get_joinstyle()) self.set_linecap(gc.get_capstyle()) self.set_linedash(*gc.get_dashes()) if mightstroke or hatch: self.set_color(*gc.get_rgb()[:3]) write('gsave\n') write(self._get_clip_cmd(gc)) write(ps.strip()) write('\n') if fill: if stroke or hatch: write('gsave\n') self.set_color(*rgbFace[:3], store=False) write('fill\n') if stroke or hatch: write('grestore\n') if hatch: hatch_name = self.create_hatch(hatch) write('gsave\n') write(_nums_to_str(*gc.get_hatch_color()[:3])) write(f' {hatch_name} setpattern fill grestore\n') if stroke: write('stroke\n') write('grestore\n') class _Orientation(Enum): (portrait, landscape) = range(2) def swap_if_landscape(self, shape): return shape[::-1] if self.name == 'landscape' else shape class FigureCanvasPS(FigureCanvasBase): fixed_dpi = 72 filetypes = {'ps': 'Postscript', 'eps': 'Encapsulated Postscript'} def get_default_filetype(self): return 'ps' def _print_ps(self, fmt, outfile, *, metadata=None, papertype=None, orientation='portrait', bbox_inches_restore=None, **kwargs): dpi = self.figure.dpi self.figure.dpi = 72 dsc_comments = {} if isinstance(outfile, (str, os.PathLike)): filename = pathlib.Path(outfile).name dsc_comments['Title'] = filename.encode('ascii', 'replace').decode('ascii') dsc_comments['Creator'] = (metadata or {}).get('Creator', f'Matplotlib v{mpl.__version__}, https://matplotlib.org/') source_date_epoch = os.getenv('SOURCE_DATE_EPOCH') dsc_comments['CreationDate'] = datetime.datetime.fromtimestamp(int(source_date_epoch), datetime.timezone.utc).strftime('%a %b %d %H:%M:%S %Y') if source_date_epoch else time.ctime() dsc_comments = '\n'.join((f'%%{k}: {v}' for (k, v) in dsc_comments.items())) if papertype is None: papertype = mpl.rcParams['ps.papersize'] papertype = papertype.lower() _api.check_in_list(['figure', 'auto', *papersize], papertype=papertype) orientation = _api.check_getitem(_Orientation, orientation=orientation.lower()) printer = self._print_figure_tex if mpl.rcParams['text.usetex'] else self._print_figure printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments, orientation=orientation, papertype=papertype, bbox_inches_restore=bbox_inches_restore, **kwargs) def _print_figure(self, fmt, outfile, *, dpi, dsc_comments, orientation, papertype, bbox_inches_restore=None): is_eps = fmt == 'eps' if not (isinstance(outfile, (str, os.PathLike)) or is_writable_file_like(outfile)): raise ValueError('outfile must be a path or a file-like object') (width, height) = self.figure.get_size_inches() if papertype == 'auto': papertype = _get_papertype(*orientation.swap_if_landscape((width, height))) if is_eps or papertype == 'figure': (paper_width, paper_height) = (width, height) else: (paper_width, paper_height) = orientation.swap_if_landscape(papersize[papertype]) xo = 72 * 0.5 * (paper_width - width) yo = 72 * 0.5 * (paper_height - height) llx = xo lly = yo urx = llx + self.figure.bbox.width ury = lly + self.figure.bbox.height rotation = 0 if orientation is _Orientation.landscape: (llx, lly, urx, ury) = (lly, llx, ury, urx) (xo, yo) = (72 * paper_height - yo, xo) rotation = 90 bbox = (llx, lly, urx, ury) self._pswriter = StringIO() ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) renderer = MixedModeRenderer(self.figure, width, height, dpi, ps_renderer, bbox_inches_restore=bbox_inches_restore) self.figure.draw(renderer) def print_figure_impl(fh): if is_eps: print('%!PS-Adobe-3.0 EPSF-3.0', file=fh) else: print('%!PS-Adobe-3.0', file=fh) if papertype != 'figure': print(f'%%DocumentPaperSizes: {papertype}', file=fh) print('%%Pages: 1', file=fh) print(f'%%LanguageLevel: 3\n{dsc_comments}\n%%Orientation: {orientation.name}\n{_get_bbox_header(bbox)}\n%%EndComments\n', end='', file=fh) Ndict = len(_psDefs) print('%%BeginProlog', file=fh) if not mpl.rcParams['ps.useafm']: Ndict += len(ps_renderer._character_tracker.used) print('/mpldict %d dict def' % Ndict, file=fh) print('mpldict begin', file=fh) print('\n'.join(_psDefs), file=fh) if not mpl.rcParams['ps.useafm']: for (font_path, chars) in ps_renderer._character_tracker.used.items(): if not chars: continue fonttype = mpl.rcParams['ps.fonttype'] if len(chars) > 255: fonttype = 42 fh.flush() if fonttype == 3: fh.write(_font_to_ps_type3(font_path, chars)) else: _font_to_ps_type42(font_path, chars, fh) print('end', file=fh) print('%%EndProlog', file=fh) if not is_eps: print('%%Page: 1 1', file=fh) print('mpldict begin', file=fh) print('%s translate' % _nums_to_str(xo, yo), file=fh) if rotation: print('%d rotate' % rotation, file=fh) print(f'0 0 {_nums_to_str(width * 72, height * 72)} rectclip', file=fh) print(self._pswriter.getvalue(), file=fh) print('end', file=fh) print('showpage', file=fh) if not is_eps: print('%%EOF', file=fh) fh.flush() if mpl.rcParams['ps.usedistiller']: with TemporaryDirectory() as tmpdir: tmpfile = os.path.join(tmpdir, 'tmp.ps') with open(tmpfile, 'w', encoding='latin-1') as fh: print_figure_impl(fh) if mpl.rcParams['ps.usedistiller'] == 'ghostscript': _try_distill(gs_distill, tmpfile, is_eps, ptype=papertype, bbox=bbox) elif mpl.rcParams['ps.usedistiller'] == 'xpdf': _try_distill(xpdf_distill, tmpfile, is_eps, ptype=papertype, bbox=bbox) _move_path_to_path_or_stream(tmpfile, outfile) else: with cbook.open_file_cm(outfile, 'w', encoding='latin-1') as file: if not file_requires_unicode(file): file = codecs.getwriter('latin-1')(file) print_figure_impl(file) def _print_figure_tex(self, fmt, outfile, *, dpi, dsc_comments, orientation, papertype, bbox_inches_restore=None): is_eps = fmt == 'eps' (width, height) = self.figure.get_size_inches() xo = 0 yo = 0 llx = xo lly = yo urx = llx + self.figure.bbox.width ury = lly + self.figure.bbox.height bbox = (llx, lly, urx, ury) self._pswriter = StringIO() ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi) renderer = MixedModeRenderer(self.figure, width, height, dpi, ps_renderer, bbox_inches_restore=bbox_inches_restore) self.figure.draw(renderer) with TemporaryDirectory() as tmpdir: tmppath = pathlib.Path(tmpdir, 'tmp.ps') tmppath.write_text(f"%!PS-Adobe-3.0 EPSF-3.0\n%%LanguageLevel: 3\n{dsc_comments}\n{_get_bbox_header(bbox)}\n%%EndComments\n%%BeginProlog\n/mpldict {len(_psDefs)} dict def\nmpldict begin\n{''.join(_psDefs)}\nend\n%%EndProlog\nmpldict begin\n{_nums_to_str(xo, yo)} translate\n0 0 {_nums_to_str(width * 72, height * 72)} rectclip\n{self._pswriter.getvalue()}\nend\nshowpage\n", encoding='latin-1') if orientation is _Orientation.landscape: (width, height) = (height, width) bbox = (lly, llx, ury, urx) if is_eps or papertype == 'figure': (paper_width, paper_height) = orientation.swap_if_landscape(self.figure.get_size_inches()) else: if papertype == 'auto': papertype = _get_papertype(width, height) (paper_width, paper_height) = papersize[papertype] psfrag_rotated = _convert_psfrags(tmppath, ps_renderer.psfrag, paper_width, paper_height, orientation.name) if mpl.rcParams['ps.usedistiller'] == 'ghostscript' or mpl.rcParams['text.usetex']: _try_distill(gs_distill, tmppath, is_eps, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) elif mpl.rcParams['ps.usedistiller'] == 'xpdf': _try_distill(xpdf_distill, tmppath, is_eps, ptype=papertype, bbox=bbox, rotated=psfrag_rotated) _move_path_to_path_or_stream(tmppath, outfile) print_ps = functools.partialmethod(_print_ps, 'ps') print_eps = functools.partialmethod(_print_ps, 'eps') def draw(self): self.figure.draw_without_rendering() return super().draw() def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation): with mpl.rc_context({'text.latex.preamble': mpl.rcParams['text.latex.preamble'] + mpl.texmanager._usepackage_if_not_loaded('color') + mpl.texmanager._usepackage_if_not_loaded('graphicx') + mpl.texmanager._usepackage_if_not_loaded('psfrag') + '\\geometry{papersize={%(width)sin,%(height)sin},margin=0in}' % {'width': paper_width, 'height': paper_height}}): dvifile = TexManager().make_dvi('\n\\begin{figure}\n \\centering\\leavevmode\n %(psfrags)s\n \\includegraphics*[angle=%(angle)s]{%(epsfile)s}\n\\end{figure}' % {'psfrags': '\n'.join(psfrags), 'angle': 90 if orientation == 'landscape' else 0, 'epsfile': tmppath.resolve().as_posix()}, fontsize=10) with TemporaryDirectory() as tmpdir: psfile = os.path.join(tmpdir, 'tmp.ps') cbook._check_and_log_subprocess(['dvips', '-q', '-R0', '-o', psfile, dvifile], _log) shutil.move(psfile, tmppath) with open(tmppath) as fh: psfrag_rotated = 'Landscape' in fh.read(1000) return psfrag_rotated def _try_distill(func, tmppath, *args, **kwargs): try: func(str(tmppath), *args, **kwargs) except mpl.ExecutableNotFoundError as exc: _log.warning('%s. Distillation step skipped.', exc) def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): if eps: paper_option = ['-dEPSCrop'] elif ptype == 'figure': paper_option = [f'-dDEVICEWIDTHPOINTS={bbox[2]}', f'-dDEVICEHEIGHTPOINTS={bbox[3]}'] else: paper_option = [f'-sPAPERSIZE={ptype}'] psfile = tmpfile + '.ps' dpi = mpl.rcParams['ps.distiller.res'] cbook._check_and_log_subprocess([mpl._get_executable_info('gs').executable, '-dBATCH', '-dNOPAUSE', '-r%d' % dpi, '-sDEVICE=ps2write', *paper_option, f'-sOutputFile={psfile}', tmpfile], _log) os.remove(tmpfile) shutil.move(psfile, tmpfile) if eps: pstoeps(tmpfile, bbox, rotated=rotated) def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False): mpl._get_executable_info('gs') mpl._get_executable_info('pdftops') if eps: paper_option = ['-dEPSCrop'] elif ptype == 'figure': paper_option = [f'-dDEVICEWIDTHPOINTS#{bbox[2]}', f'-dDEVICEHEIGHTPOINTS#{bbox[3]}'] else: paper_option = [f'-sPAPERSIZE#{ptype}'] with TemporaryDirectory() as tmpdir: tmppdf = pathlib.Path(tmpdir, 'tmp.pdf') tmpps = pathlib.Path(tmpdir, 'tmp.ps') cbook._check_and_log_subprocess(['ps2pdf', '-dAutoFilterColorImages#false', '-dAutoFilterGrayImages#false', '-sAutoRotatePages#None', '-sGrayImageFilter#FlateEncode', '-sColorImageFilter#FlateEncode', *paper_option, tmpfile, tmppdf], _log) cbook._check_and_log_subprocess(['pdftops', '-paper', 'match', '-level3', tmppdf, tmpps], _log) shutil.move(tmpps, tmpfile) if eps: pstoeps(tmpfile) @_api.deprecated('3.9') def get_bbox_header(lbrt, rotated=False): return (_get_bbox_header(lbrt), _get_rotate_command(lbrt) if rotated else '') def _get_bbox_header(lbrt): (l, b, r, t) = lbrt return f'%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}' def _get_rotate_command(lbrt): (l, b, r, t) = lbrt return f'{l + r:.2f} {0:.2f} translate\n90 rotate' def pstoeps(tmpfile, bbox=None, rotated=False): epsfile = tmpfile + '.eps' with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph: write = epsh.write for line in tmph: if line.startswith(b'%!PS'): write(b'%!PS-Adobe-3.0 EPSF-3.0\n') if bbox: write(_get_bbox_header(bbox).encode('ascii') + b'\n') elif line.startswith(b'%%EndComments'): write(line) write(b'%%BeginProlog\nsave\ncountdictstack\nmark\nnewpath\n/showpage {} def\n/setpagedevice {pop} def\n%%EndProlog\n%%Page 1 1\n') if rotated: write(_get_rotate_command(bbox).encode('ascii') + b'\n') break elif bbox and line.startswith((b'%%Bound', b'%%HiResBound', b'%%DocumentMedia', b'%%Pages')): pass else: write(line) for line in tmph: if line.startswith(b'%%EOF'): write(b'cleartomark\ncountdictstack\nexch sub { end } repeat\nrestore\nshowpage\n%%EOF\n') elif line.startswith(b'%%PageBoundingBox'): pass else: write(line) os.remove(tmpfile) shutil.move(epsfile, tmpfile) FigureManagerPS = FigureManagerBase _psDefs = ['/_d { bind def } bind def', '/m { moveto } _d', '/l { lineto } _d', '/r { rlineto } _d', '/c { curveto } _d', '/cl { closepath } _d', '/ce { closepath eofill } _d', '/sc { setcachedevice } _d'] @_Backend.export class _BackendPS(_Backend): backend_version = 'Level II' FigureCanvas = FigureCanvasPS # File: matplotlib-main/lib/matplotlib/backends/backend_qt.py import functools import os import sys import traceback import matplotlib as mpl from matplotlib import _api, backend_tools, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors, ToolContainerBase, MouseButton, CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent, _allow_interrupt import matplotlib.backends.qt_editor.figureoptions as figureoptions from . import qt_compat from .qt_compat import QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted SPECIAL_KEYS = {_to_int(getattr(QtCore.Qt.Key, k)): v for (k, v) in [('Key_Escape', 'escape'), ('Key_Tab', 'tab'), ('Key_Backspace', 'backspace'), ('Key_Return', 'enter'), ('Key_Enter', 'enter'), ('Key_Insert', 'insert'), ('Key_Delete', 'delete'), ('Key_Pause', 'pause'), ('Key_SysReq', 'sysreq'), ('Key_Clear', 'clear'), ('Key_Home', 'home'), ('Key_End', 'end'), ('Key_Left', 'left'), ('Key_Up', 'up'), ('Key_Right', 'right'), ('Key_Down', 'down'), ('Key_PageUp', 'pageup'), ('Key_PageDown', 'pagedown'), ('Key_Shift', 'shift'), ('Key_Control', 'control' if sys.platform != 'darwin' else 'cmd'), ('Key_Meta', 'meta' if sys.platform != 'darwin' else 'control'), ('Key_Alt', 'alt'), ('Key_CapsLock', 'caps_lock'), ('Key_F1', 'f1'), ('Key_F2', 'f2'), ('Key_F3', 'f3'), ('Key_F4', 'f4'), ('Key_F5', 'f5'), ('Key_F6', 'f6'), ('Key_F7', 'f7'), ('Key_F8', 'f8'), ('Key_F9', 'f9'), ('Key_F10', 'f10'), ('Key_F10', 'f11'), ('Key_F12', 'f12'), ('Key_Super_L', 'super'), ('Key_Super_R', 'super')]} _MODIFIER_KEYS = [(_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)), _to_int(getattr(QtCore.Qt.Key, key))) for (mod, key) in [('ControlModifier', 'Key_Control'), ('AltModifier', 'Key_Alt'), ('ShiftModifier', 'Key_Shift'), ('MetaModifier', 'Key_Meta')]] cursord = {k: getattr(QtCore.Qt.CursorShape, v) for (k, v) in [(cursors.MOVE, 'SizeAllCursor'), (cursors.HAND, 'PointingHandCursor'), (cursors.POINTER, 'ArrowCursor'), (cursors.SELECT_REGION, 'CrossCursor'), (cursors.WAIT, 'WaitCursor'), (cursors.RESIZE_HORIZONTAL, 'SizeHorCursor'), (cursors.RESIZE_VERTICAL, 'SizeVerCursor')]} @functools.lru_cache(1) def _create_qApp(): app = QtWidgets.QApplication.instance() if app is None: if not mpl._c_internal_utils.display_is_valid(): raise RuntimeError('Invalid DISPLAY variable') if QT_API in {'PyQt6', 'PySide6'}: other_bindings = ('PyQt5', 'PySide2') qt_version = 6 elif QT_API in {'PyQt5', 'PySide2'}: other_bindings = ('PyQt6', 'PySide6') qt_version = 5 else: raise RuntimeError('Should never be here') for binding in other_bindings: mod = sys.modules.get(f'{binding}.QtWidgets') if mod is not None and mod.QApplication.instance() is not None: other_core = sys.modules.get(f'{binding}.QtCore') _api.warn_external(f'Matplotlib is using {QT_API} which wraps {QtCore.qVersion()} however an instantiated QApplication from {binding} which wraps {other_core.qVersion()} exists. Mixing Qt major versions may not work as expected.') break if qt_version == 5: try: QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: pass try: QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy(QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) except AttributeError: pass app = QtWidgets.QApplication(['matplotlib']) if sys.platform == 'darwin': image = str(cbook._get_data_path('images/matplotlib.svg')) icon = QtGui.QIcon(image) app.setWindowIcon(icon) app.setQuitOnLastWindowClosed(True) cbook._setup_new_guiapp() if qt_version == 5: app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) return app def _allow_interrupt_qt(qapp_or_eventloop): def prepare_notifier(rsock): sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read) @sn.activated.connect def _may_clear_sock(): try: rsock.recv(1) except BlockingIOError: pass return sn def handle_sigint(): if hasattr(qapp_or_eventloop, 'closeAllWindows'): qapp_or_eventloop.closeAllWindows() qapp_or_eventloop.quit() return _allow_interrupt(prepare_notifier, handle_sigint) class TimerQT(TimerBase): def __init__(self, *args, **kwargs): self._timer = QtCore.QTimer() self._timer.timeout.connect(self._on_timer) super().__init__(*args, **kwargs) def __del__(self): if not _isdeleted(self._timer): self._timer_stop() def _timer_set_single_shot(self): self._timer.setSingleShot(self._single) def _timer_set_interval(self): self._timer.setInterval(self._interval) def _timer_start(self): self._timer.start() def _timer_stop(self): self._timer.stop() class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget): required_interactive_framework = 'qt' _timer_cls = TimerQT manager_class = _api.classproperty(lambda cls: FigureManagerQT) buttond = {getattr(QtCore.Qt.MouseButton, k): v for (k, v) in [('LeftButton', MouseButton.LEFT), ('RightButton', MouseButton.RIGHT), ('MiddleButton', MouseButton.MIDDLE), ('XButton1', MouseButton.BACK), ('XButton2', MouseButton.FORWARD)]} def __init__(self, figure=None): _create_qApp() super().__init__(figure=figure) self._draw_pending = False self._is_drawing = False self._draw_rect_callback = lambda painter: None self._in_resize_event = False self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent) self.setMouseTracking(True) self.resize(*self.get_width_height()) palette = QtGui.QPalette(QtGui.QColor('white')) self.setPalette(palette) def _update_pixel_ratio(self): if self._set_device_pixel_ratio(self.devicePixelRatioF() or 1): event = QtGui.QResizeEvent(self.size(), self.size()) self.resizeEvent(event) def _update_screen(self, screen): self._update_pixel_ratio() if screen is not None: screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio) screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio) def showEvent(self, event): window = self.window().windowHandle() window.screenChanged.connect(self._update_screen) self._update_screen(window.screen()) def set_cursor(self, cursor): self.setCursor(_api.check_getitem(cursord, cursor=cursor)) def mouseEventCoords(self, pos=None): if pos is None: pos = self.mapFromGlobal(QtGui.QCursor.pos()) elif hasattr(pos, 'position'): pos = pos.position() elif hasattr(pos, 'pos'): pos = pos.pos() x = pos.x() y = self.figure.bbox.height / self.device_pixel_ratio - pos.y() return (x * self.device_pixel_ratio, y * self.device_pixel_ratio) def enterEvent(self, event): mods = QtWidgets.QApplication.instance().queryKeyboardModifiers() if self.figure is None: return LocationEvent('figure_enter_event', self, *self.mouseEventCoords(event), modifiers=self._mpl_modifiers(mods), guiEvent=event)._process() def leaveEvent(self, event): QtWidgets.QApplication.restoreOverrideCursor() if self.figure is None: return LocationEvent('figure_leave_event', self, *self.mouseEventCoords(), modifiers=self._mpl_modifiers(), guiEvent=event)._process() def mousePressEvent(self, event): button = self.buttond.get(event.button()) if button is not None and self.figure is not None: MouseEvent('button_press_event', self, *self.mouseEventCoords(event), button, modifiers=self._mpl_modifiers(), guiEvent=event)._process() def mouseDoubleClickEvent(self, event): button = self.buttond.get(event.button()) if button is not None and self.figure is not None: MouseEvent('button_press_event', self, *self.mouseEventCoords(event), button, dblclick=True, modifiers=self._mpl_modifiers(), guiEvent=event)._process() def mouseMoveEvent(self, event): if self.figure is None: return MouseEvent('motion_notify_event', self, *self.mouseEventCoords(event), modifiers=self._mpl_modifiers(), guiEvent=event)._process() def mouseReleaseEvent(self, event): button = self.buttond.get(event.button()) if button is not None and self.figure is not None: MouseEvent('button_release_event', self, *self.mouseEventCoords(event), button, modifiers=self._mpl_modifiers(), guiEvent=event)._process() def wheelEvent(self, event): if event.pixelDelta().isNull() or QtWidgets.QApplication.instance().platformName() == 'xcb': steps = event.angleDelta().y() / 120 else: steps = event.pixelDelta().y() if steps and self.figure is not None: MouseEvent('scroll_event', self, *self.mouseEventCoords(event), step=steps, modifiers=self._mpl_modifiers(), guiEvent=event)._process() def keyPressEvent(self, event): key = self._get_key(event) if key is not None and self.figure is not None: KeyEvent('key_press_event', self, key, *self.mouseEventCoords(), guiEvent=event)._process() def keyReleaseEvent(self, event): key = self._get_key(event) if key is not None and self.figure is not None: KeyEvent('key_release_event', self, key, *self.mouseEventCoords(), guiEvent=event)._process() def resizeEvent(self, event): if self._in_resize_event: return if self.figure is None: return self._in_resize_event = True try: w = event.size().width() * self.device_pixel_ratio h = event.size().height() * self.device_pixel_ratio dpival = self.figure.dpi winch = w / dpival hinch = h / dpival self.figure.set_size_inches(winch, hinch, forward=False) QtWidgets.QWidget.resizeEvent(self, event) ResizeEvent('resize_event', self)._process() self.draw_idle() finally: self._in_resize_event = False def sizeHint(self): (w, h) = self.get_width_height() return QtCore.QSize(w, h) def minimumSizeHint(self): return QtCore.QSize(10, 10) @staticmethod def _mpl_modifiers(modifiers=None, *, exclude=None): if modifiers is None: modifiers = QtWidgets.QApplication.instance().keyboardModifiers() modifiers = _to_int(modifiers) return [SPECIAL_KEYS[key].replace('control', 'ctrl') for (mask, key) in _MODIFIER_KEYS if exclude != key and modifiers & mask] def _get_key(self, event): event_key = event.key() mods = self._mpl_modifiers(exclude=event_key) try: key = SPECIAL_KEYS[event_key] except KeyError: if event_key > sys.maxunicode: return None key = chr(event_key) if 'shift' in mods: mods.remove('shift') else: key = key.lower() return '+'.join(mods + [key]) def flush_events(self): QtWidgets.QApplication.instance().processEvents() def start_event_loop(self, timeout=0): if hasattr(self, '_event_loop') and self._event_loop.isRunning(): raise RuntimeError('Event loop already running') self._event_loop = event_loop = QtCore.QEventLoop() if timeout > 0: _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit) with _allow_interrupt_qt(event_loop): qt_compat._exec(event_loop) def stop_event_loop(self, event=None): if hasattr(self, '_event_loop'): self._event_loop.quit() def draw(self): if self._is_drawing: return with cbook._setattr_cm(self, _is_drawing=True): super().draw() self.update() def draw_idle(self): if not (getattr(self, '_draw_pending', False) or getattr(self, '_is_drawing', False)): self._draw_pending = True QtCore.QTimer.singleShot(0, self._draw_idle) def blit(self, bbox=None): if bbox is None and self.figure: bbox = self.figure.bbox (l, b, w, h) = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds) t = b + h self.repaint(l, self.rect().height() - t, w, h) def _draw_idle(self): with self._idle_draw_cntx(): if not self._draw_pending: return self._draw_pending = False if self.height() <= 0 or self.width() <= 0: return try: self.draw() except Exception: traceback.print_exc() def drawRectangle(self, rect): if rect is not None: (x0, y0, w, h) = (int(pt / self.device_pixel_ratio) for pt in rect) x1 = x0 + w y1 = y0 + h def _draw_rect_callback(painter): pen = QtGui.QPen(QtGui.QColor('black'), 1 / self.device_pixel_ratio) pen.setDashPattern([3, 3]) for (color, offset) in [(QtGui.QColor('black'), 0), (QtGui.QColor('white'), 3)]: pen.setDashOffset(offset) pen.setColor(color) painter.setPen(pen) painter.drawLine(x0, y0, x0, y1) painter.drawLine(x0, y0, x1, y0) painter.drawLine(x0, y1, x1, y1) painter.drawLine(x1, y0, x1, y1) else: def _draw_rect_callback(painter): return self._draw_rect_callback = _draw_rect_callback self.update() class MainWindow(QtWidgets.QMainWindow): closing = QtCore.Signal() def closeEvent(self, event): self.closing.emit() super().closeEvent(event) class FigureManagerQT(FigureManagerBase): def __init__(self, canvas, num): self.window = MainWindow() super().__init__(canvas, num) self.window.closing.connect(self._widgetclosed) if sys.platform != 'darwin': image = str(cbook._get_data_path('images/matplotlib.svg')) icon = QtGui.QIcon(image) self.window.setWindowIcon(icon) self.window._destroying = False if self.toolbar: self.window.addToolBar(self.toolbar) tbs_height = self.toolbar.sizeHint().height() else: tbs_height = 0 cs = canvas.sizeHint() cs_height = cs.height() height = cs_height + tbs_height self.window.resize(cs.width(), height) self.window.setCentralWidget(self.canvas) if mpl.is_interactive(): self.window.show() self.canvas.draw_idle() self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) self.canvas.setFocus() self.window.raise_() def full_screen_toggle(self): if self.window.isFullScreen(): self.window.showNormal() else: self.window.showFullScreen() def _widgetclosed(self): CloseEvent('close_event', self.canvas)._process() if self.window._destroying: return self.window._destroying = True try: Gcf.destroy(self) except AttributeError: pass def resize(self, width, height): width = int(width / self.canvas.device_pixel_ratio) height = int(height / self.canvas.device_pixel_ratio) extra_width = self.window.width() - self.canvas.width() extra_height = self.window.height() - self.canvas.height() self.canvas.resize(width, height) self.window.resize(width + extra_width, height + extra_height) @classmethod def start_main_loop(cls): qapp = QtWidgets.QApplication.instance() if qapp: with _allow_interrupt_qt(qapp): qt_compat._exec(qapp) def show(self): self.window._destroying = False self.window.show() if mpl.rcParams['figure.raise_window']: self.window.activateWindow() self.window.raise_() def destroy(self, *args): if QtWidgets.QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() self.window.close() def get_window_title(self): return self.window.windowTitle() def set_window_title(self, title): self.window.setWindowTitle(title) class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): _message = QtCore.Signal(str) message = _api.deprecate_privatize_attribute('3.8') toolitems = [*NavigationToolbar2.toolitems] toolitems.insert([name for (name, *_) in toolitems].index('Subplots') + 1, ('Customize', 'Edit axis, curve and image parameters', 'qt4_editor_options', 'edit_parameters')) def __init__(self, canvas, parent=None, coordinates=True): QtWidgets.QToolBar.__init__(self, parent) self.setAllowedAreas(QtCore.Qt.ToolBarArea(_to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) self.coordinates = coordinates self._actions = {} self._subplot_dialog = None for (text, tooltip_text, image_file, callback) in self.toolitems: if text is None: self.addSeparator() else: slot = getattr(self, callback) slot = functools.wraps(slot)(functools.partial(slot)) slot = QtCore.Slot()(slot) a = self.addAction(self._icon(image_file + '.png'), text, slot) self._actions[callback] = a if callback in ['zoom', 'pan']: a.setCheckable(True) if tooltip_text is not None: a.setToolTip(tooltip_text) if self.coordinates: self.locLabel = QtWidgets.QLabel('', self) self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag(_to_int(QtCore.Qt.AlignmentFlag.AlignRight) | _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) self.locLabel.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Ignored)) labelAction = self.addWidget(self.locLabel) labelAction.setVisible(True) NavigationToolbar2.__init__(self, canvas) def _icon(self, name): path_regular = cbook._get_data_path('images', name) path_large = path_regular.with_name(path_regular.name.replace('.png', '_large.png')) filename = str(path_large if path_large.exists() else path_regular) pm = QtGui.QPixmap(filename) pm.setDevicePixelRatio(self.devicePixelRatioF() or 1) if self.palette().color(self.backgroundRole()).value() < 128: icon_color = self.palette().color(self.foregroundRole()) mask = pm.createMaskFromColor(QtGui.QColor('black'), QtCore.Qt.MaskMode.MaskOutColor) pm.fill(icon_color) pm.setMask(mask) return QtGui.QIcon(pm) def edit_parameters(self): axes = self.canvas.figure.get_axes() if not axes: QtWidgets.QMessageBox.warning(self.canvas.parent(), 'Error', 'There are no Axes to edit.') return elif len(axes) == 1: (ax,) = axes else: titles = [ax.get_label() or ax.get_title() or ax.get_title('left') or ax.get_title('right') or ' - '.join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or f'' for ax in axes] duplicate_titles = [title for title in titles if titles.count(title) > 1] for (i, ax) in enumerate(axes): if titles[i] in duplicate_titles: titles[i] += f' (id: {id(ax):#x})' (item, ok) = QtWidgets.QInputDialog.getItem(self.canvas.parent(), 'Customize', 'Select Axes:', titles, 0, False) if not ok: return ax = axes[titles.index(item)] figureoptions.figure_edit(ax, self) def _update_buttons_checked(self): if 'pan' in self._actions: self._actions['pan'].setChecked(self.mode.name == 'PAN') if 'zoom' in self._actions: self._actions['zoom'].setChecked(self.mode.name == 'ZOOM') def pan(self, *args): super().pan(*args) self._update_buttons_checked() def zoom(self, *args): super().zoom(*args) self._update_buttons_checked() def set_message(self, s): self._message.emit(s) if self.coordinates: self.locLabel.setText(s) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) def configure_subplots(self): if self._subplot_dialog is None: self._subplot_dialog = SubplotToolQt(self.canvas.figure, self.canvas.parent()) self.canvas.mpl_connect('close_event', lambda e: self._subplot_dialog.reject()) self._subplot_dialog.update_from_current_subplotpars() self._subplot_dialog.setModal(True) self._subplot_dialog.show() return self._subplot_dialog def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(filetypes.items()) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser(mpl.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for (name, exts) in sorted_filetypes: exts_list = ' '.join(['*.%s' % ext for ext in exts]) filter = f'{name} ({exts_list})' if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) (fname, filter) = QtWidgets.QFileDialog.getSaveFileName(self.canvas.parent(), 'Choose a filename to save to', start, filters, selectedFilter) if fname: if startpath != '': mpl.rcParams['savefig.directory'] = os.path.dirname(fname) try: self.canvas.figure.savefig(fname) except Exception as e: QtWidgets.QMessageBox.critical(self, 'Error saving file', str(e), QtWidgets.QMessageBox.StandardButton.Ok, QtWidgets.QMessageBox.StandardButton.NoButton) def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 if 'back' in self._actions: self._actions['back'].setEnabled(can_backward) if 'forward' in self._actions: self._actions['forward'].setEnabled(can_forward) class SubplotToolQt(QtWidgets.QDialog): def __init__(self, targetfig, parent): super().__init__() self.setWindowIcon(QtGui.QIcon(str(cbook._get_data_path('images/matplotlib.png')))) self.setObjectName('SubplotTool') self._spinboxes = {} main_layout = QtWidgets.QHBoxLayout() self.setLayout(main_layout) for (group, spinboxes, buttons) in [('Borders', ['top', 'bottom', 'left', 'right'], [('Export values', self._export_values)]), ('Spacings', ['hspace', 'wspace'], [('Tight layout', self._tight_layout), ('Reset', self._reset), ('Close', self.close)])]: layout = QtWidgets.QVBoxLayout() main_layout.addLayout(layout) box = QtWidgets.QGroupBox(group) layout.addWidget(box) inner = QtWidgets.QFormLayout(box) for name in spinboxes: self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox() spinbox.setRange(0, 1) spinbox.setDecimals(3) spinbox.setSingleStep(0.005) spinbox.setKeyboardTracking(False) spinbox.valueChanged.connect(self._on_value_changed) inner.addRow(name, spinbox) layout.addStretch(1) for (name, method) in buttons: button = QtWidgets.QPushButton(name) button.setAutoDefault(False) button.clicked.connect(method) layout.addWidget(button) if name == 'Close': button.setFocus() self._figure = targetfig self._defaults = {} self._export_values_dialog = None self.update_from_current_subplotpars() def update_from_current_subplotpars(self): self._defaults = {spinbox: getattr(self._figure.subplotpars, name) for (name, spinbox) in self._spinboxes.items()} self._reset() def _export_values(self): self._export_values_dialog = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout() self._export_values_dialog.setLayout(layout) text = QtWidgets.QPlainTextEdit() text.setReadOnly(True) layout.addWidget(text) text.setPlainText(',\n'.join((f'{attr}={spinbox.value():.3}' for (attr, spinbox) in self._spinboxes.items()))) size = text.maximumSize() size.setHeight(QtGui.QFontMetrics(text.document().defaultFont()).size(0, text.toPlainText()).height() + 20) text.setMaximumSize(size) self._export_values_dialog.show() def _on_value_changed(self): spinboxes = self._spinboxes for (lower, higher) in [('bottom', 'top'), ('left', 'right')]: spinboxes[higher].setMinimum(spinboxes[lower].value() + 0.001) spinboxes[lower].setMaximum(spinboxes[higher].value() - 0.001) self._figure.subplots_adjust(**{attr: spinbox.value() for (attr, spinbox) in spinboxes.items()}) self._figure.canvas.draw_idle() def _tight_layout(self): self._figure.tight_layout() for (attr, spinbox) in self._spinboxes.items(): spinbox.blockSignals(True) spinbox.setValue(getattr(self._figure.subplotpars, attr)) spinbox.blockSignals(False) self._figure.canvas.draw_idle() def _reset(self): for (spinbox, value) in self._defaults.items(): spinbox.setRange(0, 1) spinbox.blockSignals(True) spinbox.setValue(value) spinbox.blockSignals(False) self._on_value_changed() class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): def __init__(self, toolmanager, parent=None): ToolContainerBase.__init__(self, toolmanager) QtWidgets.QToolBar.__init__(self, parent) self.setAllowedAreas(QtCore.Qt.ToolBarArea(_to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) message_label = QtWidgets.QLabel('') message_label.setAlignment(QtCore.Qt.AlignmentFlag(_to_int(QtCore.Qt.AlignmentFlag.AlignRight) | _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) message_label.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Ignored)) self._message_action = self.addWidget(message_label) self._toolitems = {} self._groups = {} def add_toolitem(self, name, group, position, image_file, description, toggle): button = QtWidgets.QToolButton(self) if image_file: button.setIcon(NavigationToolbar2QT._icon(self, image_file)) button.setText(name) if description: button.setToolTip(description) def handler(): self.trigger_tool(name) if toggle: button.setCheckable(True) button.toggled.connect(handler) else: button.clicked.connect(handler) self._toolitems.setdefault(name, []) self._add_to_group(group, name, button, position) self._toolitems[name].append((button, handler)) def _add_to_group(self, group, name, button, position): gr = self._groups.get(group, []) if not gr: sep = self.insertSeparator(self._message_action) gr.append(sep) before = gr[position] widget = self.insertWidget(before, button) gr.insert(position, widget) self._groups[group] = gr def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for (button, handler) in self._toolitems[name]: button.toggled.disconnect(handler) button.setChecked(toggled) button.toggled.connect(handler) def remove_toolitem(self, name): for (button, handler) in self._toolitems.pop(name, []): button.setParent(None) def set_message(self, s): self.widgetForAction(self._message_action).setText(s) @backend_tools._register_tool_class(FigureCanvasQT) class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._subplot_dialog = None def trigger(self, *args): NavigationToolbar2QT.configure_subplots(self) @backend_tools._register_tool_class(FigureCanvasQT) class SaveFigureQt(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2QT.save_figure(self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(FigureCanvasQT) class RubberbandQt(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): NavigationToolbar2QT.draw_rubberband(self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): NavigationToolbar2QT.remove_rubberband(self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(FigureCanvasQT) class HelpQt(backend_tools.ToolHelpBase): def trigger(self, *args): QtWidgets.QMessageBox.information(None, 'Help', self._get_help_html()) @backend_tools._register_tool_class(FigureCanvasQT) class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): pixmap = self.canvas.grab() QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap) FigureManagerQT._toolbar2_class = NavigationToolbar2QT FigureManagerQT._toolmanager_toolbar_class = ToolbarQt @_Backend.export class _BackendQT(_Backend): backend_version = __version__ FigureCanvas = FigureCanvasQT FigureManager = FigureManagerQT mainloop = FigureManagerQT.start_main_loop # File: matplotlib-main/lib/matplotlib/backends/backend_qt5.py from .. import backends backends._QT_FORCE_QT5_BINDING = True from .backend_qt import SPECIAL_KEYS, cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT, FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt, SaveFigureQt, ConfigureSubplotsQt, RubberbandQt, HelpQt, ToolCopyToClipboardQT, FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2, TimerBase, ToolContainerBase, figureoptions, Gcf from . import backend_qt as _backend_qt @_BackendQT.export class _BackendQT5(_BackendQT): pass def __getattr__(name): if name == 'qApp': return _backend_qt.qApp raise AttributeError(f'module {__name__!r} has no attribute {name!r}') # File: matplotlib-main/lib/matplotlib/backends/backend_qt5agg.py """""" from .. import backends backends._QT_FORCE_QT5_BINDING = True from .backend_qtagg import _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT, FigureCanvasAgg, FigureCanvasQT @_BackendQTAgg.export class _BackendQT5Agg(_BackendQTAgg): pass # File: matplotlib-main/lib/matplotlib/backends/backend_qtagg.py """""" import ctypes from matplotlib.transforms import Bbox from .qt_compat import QT_API, QtCore, QtGui from .backend_agg import FigureCanvasAgg from .backend_qt import _BackendQT, FigureCanvasQT from .backend_qt import FigureManagerQT, NavigationToolbar2QT class FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT): def paintEvent(self, event): self._draw_idle() if not hasattr(self, 'renderer'): return painter = QtGui.QPainter(self) try: rect = event.rect() width = rect.width() * self.device_pixel_ratio height = rect.height() * self.device_pixel_ratio (left, top) = self.mouseEventCoords(rect.topLeft()) bottom = top - height right = left + width bbox = Bbox([[left, bottom], [right, top]]) buf = memoryview(self.copy_from_bbox(bbox)) if QT_API == 'PyQt6': from PyQt6 import sip ptr = int(sip.voidptr(buf)) else: ptr = buf painter.eraseRect(rect) qimage = QtGui.QImage(ptr, buf.shape[1], buf.shape[0], QtGui.QImage.Format.Format_RGBA8888) qimage.setDevicePixelRatio(self.device_pixel_ratio) origin = QtCore.QPoint(rect.left(), rect.top()) painter.drawImage(origin, qimage) if QT_API == 'PySide2' and QtCore.__version_info__ < (5, 12): ctypes.c_long.from_address(id(buf)).value = 1 self._draw_rect_callback(painter) finally: painter.end() def print_figure(self, *args, **kwargs): super().print_figure(*args, **kwargs) self._draw_pending = True @_BackendQT.export class _BackendQTAgg(_BackendQT): FigureCanvas = FigureCanvasQTAgg # File: matplotlib-main/lib/matplotlib/backends/backend_qtcairo.py import ctypes from .backend_cairo import cairo, FigureCanvasCairo from .backend_qt import _BackendQT, FigureCanvasQT from .qt_compat import QT_API, QtCore, QtGui class FigureCanvasQTCairo(FigureCanvasCairo, FigureCanvasQT): def draw(self): if hasattr(self._renderer.gc, 'ctx'): self._renderer.dpi = self.figure.dpi self.figure.draw(self._renderer) super().draw() def paintEvent(self, event): width = int(self.device_pixel_ratio * self.width()) height = int(self.device_pixel_ratio * self.height()) if (width, height) != self._renderer.get_canvas_width_height(): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) self._renderer.set_context(cairo.Context(surface)) self._renderer.dpi = self.figure.dpi self.figure.draw(self._renderer) buf = self._renderer.gc.ctx.get_target().get_data() if QT_API == 'PyQt6': from PyQt6 import sip ptr = int(sip.voidptr(buf)) else: ptr = buf qimage = QtGui.QImage(ptr, width, height, QtGui.QImage.Format.Format_ARGB32_Premultiplied) if QT_API == 'PySide2' and QtCore.__version_info__ < (5, 12): ctypes.c_long.from_address(id(buf)).value = 1 qimage.setDevicePixelRatio(self.device_pixel_ratio) painter = QtGui.QPainter(self) painter.eraseRect(event.rect()) painter.drawImage(0, 0, qimage) self._draw_rect_callback(painter) painter.end() @_BackendQT.export class _BackendQTCairo(_BackendQT): FigureCanvas = FigureCanvasQTCairo # File: matplotlib-main/lib/matplotlib/backends/backend_svg.py import base64 import codecs import datetime import gzip import hashlib from io import BytesIO import itertools import logging import os import re import uuid import numpy as np from PIL import Image import matplotlib as mpl from matplotlib import cbook, font_manager as fm from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, RendererBase from matplotlib.backends.backend_mixed import MixedModeRenderer from matplotlib.colors import rgb2hex from matplotlib.dates import UTC from matplotlib.path import Path from matplotlib import _path from matplotlib.transforms import Affine2D, Affine2DBase _log = logging.getLogger(__name__) def _escape_cdata(s): s = s.replace('&', '&') s = s.replace('<', '<') s = s.replace('>', '>') return s _escape_xml_comment = re.compile('-(?=-)') def _escape_comment(s): s = _escape_cdata(s) return _escape_xml_comment.sub('- ', s) def _escape_attrib(s): s = s.replace('&', '&') s = s.replace("'", ''') s = s.replace('"', '"') s = s.replace('<', '<') s = s.replace('>', '>') return s def _quote_escape_attrib(s): return '"' + _escape_cdata(s) + '"' if '"' not in s else "'" + _escape_cdata(s) + "'" if "'" not in s else '"' + _escape_attrib(s) + '"' def _short_float_fmt(x): return f'{x:f}'.rstrip('0').rstrip('.') class XMLWriter: def __init__(self, file): self.__write = file.write if hasattr(file, 'flush'): self.flush = file.flush self.__open = 0 self.__tags = [] self.__data = [] self.__indentation = ' ' * 64 def __flush(self, indent=True): if self.__open: if indent: self.__write('>\n') else: self.__write('>') self.__open = 0 if self.__data: data = ''.join(self.__data) self.__write(_escape_cdata(data)) self.__data = [] def start(self, tag, attrib={}, **extra): self.__flush() tag = _escape_cdata(tag) self.__data = [] self.__tags.append(tag) self.__write(self.__indentation[:len(self.__tags) - 1]) self.__write(f'<{tag}') for (k, v) in {**attrib, **extra}.items(): if v: k = _escape_cdata(k) v = _quote_escape_attrib(v) self.__write(f' {k}={v}') self.__open = 1 return len(self.__tags) - 1 def comment(self, comment): self.__flush() self.__write(self.__indentation[:len(self.__tags)]) self.__write(f'\n') def data(self, text): self.__data.append(text) def end(self, tag=None, indent=True): if tag: assert self.__tags, f'unbalanced end({tag})' assert _escape_cdata(tag) == self.__tags[-1], f'expected end({self.__tags[-1]}), got {tag}' else: assert self.__tags, 'unbalanced end()' tag = self.__tags.pop() if self.__data: self.__flush(indent) elif self.__open: self.__open = 0 self.__write('/>\n') return if indent: self.__write(self.__indentation[:len(self.__tags)]) self.__write(f'\n') def close(self, id): while len(self.__tags) > id: self.end() def element(self, tag, text=None, attrib={}, **extra): self.start(tag, attrib, **extra) if text: self.data(text) self.end(indent=False) def flush(self): pass def _generate_transform(transform_list): parts = [] for (type, value) in transform_list: if type == 'scale' and (value == (1,) or value == (1, 1)) or (type == 'translate' and value == (0, 0)) or (type == 'rotate' and value == (0,)): continue if type == 'matrix' and isinstance(value, Affine2DBase): value = value.to_values() parts.append('{}({})'.format(type, ' '.join((_short_float_fmt(x) for x in value)))) return ' '.join(parts) def _generate_css(attrib): return '; '.join((f'{k}: {v}' for (k, v) in attrib.items())) _capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'} def _check_is_str(info, key): if not isinstance(info, str): raise TypeError(f'Invalid type for {key} metadata. Expected str, not {type(info)}.') def _check_is_iterable_of_str(infos, key): if np.iterable(infos): for info in infos: if not isinstance(info, str): raise TypeError(f'Invalid type for {key} metadata. Expected iterable of str, not {type(info)}.') else: raise TypeError(f'Invalid type for {key} metadata. Expected str or iterable of str, not {type(infos)}.') class RendererSVG(RendererBase): def __init__(self, width, height, svgwriter, basename=None, image_dpi=72, *, metadata=None): self.width = width self.height = height self.writer = XMLWriter(svgwriter) self.image_dpi = image_dpi if basename is None: basename = getattr(svgwriter, 'name', '') if not isinstance(basename, str): basename = '' self.basename = basename self._groupd = {} self._image_counter = itertools.count() self._clip_path_ids = {} self._clipd = {} self._markers = {} self._path_collection_id = 0 self._hatchd = {} self._has_gouraud = False self._n_gradients = 0 super().__init__() self._glyph_map = dict() str_height = _short_float_fmt(height) str_width = _short_float_fmt(width) svgwriter.write(svgProlog) self._start_id = self.writer.start('svg', width=f'{str_width}pt', height=f'{str_height}pt', viewBox=f'0 0 {str_width} {str_height}', xmlns='http://www.w3.org/2000/svg', version='1.1', id=mpl.rcParams['svg.id'], attrib={'xmlns:xlink': 'http://www.w3.org/1999/xlink'}) self._write_metadata(metadata) self._write_default_style() def _get_clippath_id(self, clippath): if clippath not in self._clip_path_ids: self._clip_path_ids[clippath] = len(self._clip_path_ids) return self._clip_path_ids[clippath] def finalize(self): self._write_clips() self._write_hatches() self.writer.close(self._start_id) self.writer.flush() def _write_metadata(self, metadata): if metadata is None: metadata = {} metadata = {'Format': 'image/svg+xml', 'Type': 'http://purl.org/dc/dcmitype/StillImage', 'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org/', **metadata} writer = self.writer if 'Title' in metadata: title = metadata['Title'] _check_is_str(title, 'Title') writer.element('title', text=title) date = metadata.get('Date', None) if date is not None: if isinstance(date, str): dates = [date] elif isinstance(date, (datetime.datetime, datetime.date)): dates = [date.isoformat()] elif np.iterable(date): dates = [] for d in date: if isinstance(d, str): dates.append(d) elif isinstance(d, (datetime.datetime, datetime.date)): dates.append(d.isoformat()) else: raise TypeError(f'Invalid type for Date metadata. Expected iterable of str, date, or datetime, not {type(d)}.') else: raise TypeError(f'Invalid type for Date metadata. Expected str, date, datetime, or iterable of the same, not {type(date)}.') metadata['Date'] = '/'.join(dates) elif 'Date' not in metadata: date = os.getenv('SOURCE_DATE_EPOCH') if date: date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc) metadata['Date'] = date.replace(tzinfo=UTC).isoformat() else: metadata['Date'] = datetime.datetime.today().isoformat() mid = None def ensure_metadata(mid): if mid is not None: return mid mid = writer.start('metadata') writer.start('rdf:RDF', attrib={'xmlns:dc': 'http://purl.org/dc/elements/1.1/', 'xmlns:cc': 'http://creativecommons.org/ns#', 'xmlns:rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'}) writer.start('cc:Work') return mid uri = metadata.pop('Type', None) if uri is not None: mid = ensure_metadata(mid) writer.element('dc:type', attrib={'rdf:resource': uri}) for key in ['Title', 'Coverage', 'Date', 'Description', 'Format', 'Identifier', 'Language', 'Relation', 'Source']: info = metadata.pop(key, None) if info is not None: mid = ensure_metadata(mid) _check_is_str(info, key) writer.element(f'dc:{key.lower()}', text=info) for key in ['Creator', 'Contributor', 'Publisher', 'Rights']: agents = metadata.pop(key, None) if agents is None: continue if isinstance(agents, str): agents = [agents] _check_is_iterable_of_str(agents, key) mid = ensure_metadata(mid) writer.start(f'dc:{key.lower()}') for agent in agents: writer.start('cc:Agent') writer.element('dc:title', text=agent) writer.end('cc:Agent') writer.end(f'dc:{key.lower()}') keywords = metadata.pop('Keywords', None) if keywords is not None: if isinstance(keywords, str): keywords = [keywords] _check_is_iterable_of_str(keywords, 'Keywords') mid = ensure_metadata(mid) writer.start('dc:subject') writer.start('rdf:Bag') for keyword in keywords: writer.element('rdf:li', text=keyword) writer.end('rdf:Bag') writer.end('dc:subject') if mid is not None: writer.close(mid) if metadata: raise ValueError('Unknown metadata key(s) passed to SVG writer: ' + ','.join(metadata)) def _write_default_style(self): writer = self.writer default_style = _generate_css({'stroke-linejoin': 'round', 'stroke-linecap': 'butt'}) writer.start('defs') writer.element('style', type='text/css', text='*{%s}' % default_style) writer.end('defs') def _make_id(self, type, content): salt = mpl.rcParams['svg.hashsalt'] if salt is None: salt = str(uuid.uuid4()) m = hashlib.sha256() m.update(salt.encode('utf8')) m.update(str(content).encode('utf8')) return f'{type}{m.hexdigest()[:10]}' def _make_flip_transform(self, transform): return transform + Affine2D().scale(1, -1).translate(0, self.height) def _get_hatch(self, gc, rgbFace): if rgbFace is not None: rgbFace = tuple(rgbFace) edge = gc.get_hatch_color() if edge is not None: edge = tuple(edge) dictkey = (gc.get_hatch(), rgbFace, edge) oid = self._hatchd.get(dictkey) if oid is None: oid = self._make_id('h', dictkey) self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge), oid) else: (_, oid) = oid return oid def _write_hatches(self): if not len(self._hatchd): return HATCH_SIZE = 72 writer = self.writer writer.start('defs') for ((path, face, stroke), oid) in self._hatchd.values(): writer.start('pattern', id=oid, patternUnits='userSpaceOnUse', x='0', y='0', width=str(HATCH_SIZE), height=str(HATCH_SIZE)) path_data = self._convert_path(path, Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE), simplify=False) if face is None: fill = 'none' else: fill = rgb2hex(face) writer.element('rect', x='0', y='0', width=str(HATCH_SIZE + 1), height=str(HATCH_SIZE + 1), fill=fill) hatch_style = {'fill': rgb2hex(stroke), 'stroke': rgb2hex(stroke), 'stroke-width': str(mpl.rcParams['hatch.linewidth']), 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter'} if stroke[3] < 1: hatch_style['stroke-opacity'] = str(stroke[3]) writer.element('path', d=path_data, style=_generate_css(hatch_style)) writer.end('pattern') writer.end('defs') def _get_style_dict(self, gc, rgbFace): attrib = {} forced_alpha = gc.get_forced_alpha() if gc.get_hatch() is not None: attrib['fill'] = f'url(#{self._get_hatch(gc, rgbFace)})' if rgbFace is not None and len(rgbFace) == 4 and (rgbFace[3] != 1.0) and (not forced_alpha): attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) elif rgbFace is None: attrib['fill'] = 'none' else: if tuple(rgbFace[:3]) != (0, 0, 0): attrib['fill'] = rgb2hex(rgbFace) if len(rgbFace) == 4 and rgbFace[3] != 1.0 and (not forced_alpha): attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) if forced_alpha and gc.get_alpha() != 1.0: attrib['opacity'] = _short_float_fmt(gc.get_alpha()) (offset, seq) = gc.get_dashes() if seq is not None: attrib['stroke-dasharray'] = ','.join((_short_float_fmt(val) for val in seq)) attrib['stroke-dashoffset'] = _short_float_fmt(float(offset)) linewidth = gc.get_linewidth() if linewidth: rgb = gc.get_rgb() attrib['stroke'] = rgb2hex(rgb) if not forced_alpha and rgb[3] != 1.0: attrib['stroke-opacity'] = _short_float_fmt(rgb[3]) if linewidth != 1.0: attrib['stroke-width'] = _short_float_fmt(linewidth) if gc.get_joinstyle() != 'round': attrib['stroke-linejoin'] = gc.get_joinstyle() if gc.get_capstyle() != 'butt': attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()] return attrib def _get_style(self, gc, rgbFace): return _generate_css(self._get_style_dict(gc, rgbFace)) def _get_clip_attrs(self, gc): cliprect = gc.get_clip_rectangle() (clippath, clippath_trans) = gc.get_clip_path() if clippath is not None: clippath_trans = self._make_flip_transform(clippath_trans) dictkey = (self._get_clippath_id(clippath), str(clippath_trans)) elif cliprect is not None: (x, y, w, h) = cliprect.bounds y = self.height - (y + h) dictkey = (x, y, w, h) else: return {} clip = self._clipd.get(dictkey) if clip is None: oid = self._make_id('p', dictkey) if clippath is not None: self._clipd[dictkey] = ((clippath, clippath_trans), oid) else: self._clipd[dictkey] = (dictkey, oid) else: (_, oid) = clip return {'clip-path': f'url(#{oid})'} def _write_clips(self): if not len(self._clipd): return writer = self.writer writer.start('defs') for (clip, oid) in self._clipd.values(): writer.start('clipPath', id=oid) if len(clip) == 2: (clippath, clippath_trans) = clip path_data = self._convert_path(clippath, clippath_trans, simplify=False) writer.element('path', d=path_data) else: (x, y, w, h) = clip writer.element('rect', x=_short_float_fmt(x), y=_short_float_fmt(y), width=_short_float_fmt(w), height=_short_float_fmt(h)) writer.end('clipPath') writer.end('defs') def open_group(self, s, gid=None): if gid: self.writer.start('g', id=gid) else: self._groupd[s] = self._groupd.get(s, 0) + 1 self.writer.start('g', id=f'{s}_{self._groupd[s]:d}') def close_group(self, s): self.writer.end('g') def option_image_nocomposite(self): return not mpl.rcParams['image.composite_image'] def _convert_path(self, path, transform=None, clip=None, simplify=None, sketch=None): if clip: clip = (0.0, 0.0, self.width, self.height) else: clip = None return _path.convert_to_string(path, transform, clip, simplify, sketch, 6, [b'M', b'L', b'Q', b'C', b'z'], False).decode('ascii') def draw_path(self, gc, path, transform, rgbFace=None): trans_and_flip = self._make_flip_transform(transform) clip = rgbFace is None and gc.get_hatch_path() is None simplify = path.should_simplify and clip path_data = self._convert_path(path, trans_and_flip, clip=clip, simplify=simplify, sketch=gc.get_sketch_params()) if gc.get_url() is not None: self.writer.start('a', {'xlink:href': gc.get_url()}) self.writer.element('path', d=path_data, **self._get_clip_attrs(gc), style=self._get_style(gc, rgbFace)) if gc.get_url() is not None: self.writer.end('a') def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): if not len(path.vertices): return writer = self.writer path_data = self._convert_path(marker_path, marker_trans + Affine2D().scale(1.0, -1.0), simplify=False) style = self._get_style_dict(gc, rgbFace) dictkey = (path_data, _generate_css(style)) oid = self._markers.get(dictkey) style = _generate_css({k: v for (k, v) in style.items() if k.startswith('stroke')}) if oid is None: oid = self._make_id('m', dictkey) writer.start('defs') writer.element('path', id=oid, d=path_data, style=style) writer.end('defs') self._markers[dictkey] = oid writer.start('g', **self._get_clip_attrs(gc)) if gc.get_url() is not None: self.writer.start('a', {'xlink:href': gc.get_url()}) trans_and_flip = self._make_flip_transform(trans) attrib = {'xlink:href': f'#{oid}'} clip = (0, 0, self.width * 72, self.height * 72) for (vertices, code) in path.iter_segments(trans_and_flip, clip=clip, simplify=False): if len(vertices): (x, y) = vertices[-2:] attrib['x'] = _short_float_fmt(x) attrib['y'] = _short_float_fmt(y) attrib['style'] = self._get_style(gc, rgbFace) writer.element('use', attrib=attrib) if gc.get_url() is not None: self.writer.end('a') writer.end('g') def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): len_path = len(paths[0].vertices) if len(paths) > 0 else 0 uses_per_path = self._iter_collection_uses_per_path(paths, all_transforms, offsets, facecolors, edgecolors) should_do_optimization = len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path if not should_do_optimization: return super().draw_path_collection(gc, master_transform, paths, all_transforms, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position) writer = self.writer path_codes = [] writer.start('defs') for (i, (path, transform)) in enumerate(self._iter_collection_raw_paths(master_transform, paths, all_transforms)): transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0) d = self._convert_path(path, transform, simplify=False) oid = 'C{:x}_{:x}_{}'.format(self._path_collection_id, i, self._make_id('', d)) writer.element('path', id=oid, d=d) path_codes.append(oid) writer.end('defs') for (xo, yo, path_id, gc0, rgbFace) in self._iter_collection(gc, path_codes, offsets, offset_trans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): url = gc0.get_url() if url is not None: writer.start('a', attrib={'xlink:href': url}) clip_attrs = self._get_clip_attrs(gc0) if clip_attrs: writer.start('g', **clip_attrs) attrib = {'xlink:href': f'#{path_id}', 'x': _short_float_fmt(xo), 'y': _short_float_fmt(self.height - yo), 'style': self._get_style(gc0, rgbFace)} writer.element('use', attrib=attrib) if clip_attrs: writer.end('g') if url is not None: writer.end('a') self._path_collection_id += 1 def _draw_gouraud_triangle(self, transformed_points, colors): avg_color = np.average(colors, axis=0) if avg_color[-1] == 0: return writer = self.writer writer.start('defs') for i in range(3): (x1, y1) = transformed_points[i] (x2, y2) = transformed_points[(i + 1) % 3] (x3, y3) = transformed_points[(i + 2) % 3] rgba_color = colors[i] if x2 == x3: xb = x2 yb = y1 elif y2 == y3: xb = x1 yb = y2 else: m1 = (y2 - y3) / (x2 - x3) b1 = y2 - m1 * x2 m2 = -(1.0 / m1) b2 = y1 - m2 * x1 xb = (-b1 + b2) / (m1 - m2) yb = m2 * xb + b2 writer.start('linearGradient', id=f'GR{self._n_gradients:x}_{i:d}', gradientUnits='userSpaceOnUse', x1=_short_float_fmt(x1), y1=_short_float_fmt(y1), x2=_short_float_fmt(xb), y2=_short_float_fmt(yb)) writer.element('stop', offset='1', style=_generate_css({'stop-color': rgb2hex(avg_color), 'stop-opacity': _short_float_fmt(rgba_color[-1])})) writer.element('stop', offset='0', style=_generate_css({'stop-color': rgb2hex(rgba_color), 'stop-opacity': '0'})) writer.end('linearGradient') writer.end('defs') dpath = f'M {_short_float_fmt(x1)},{_short_float_fmt(y1)} L {_short_float_fmt(x2)},{_short_float_fmt(y2)} {_short_float_fmt(x3)},{_short_float_fmt(y3)} Z' writer.element('path', attrib={'d': dpath, 'fill': rgb2hex(avg_color), 'fill-opacity': '1', 'shape-rendering': 'crispEdges'}) writer.start('g', attrib={'stroke': 'none', 'stroke-width': '0', 'shape-rendering': 'crispEdges', 'filter': 'url(#colorMat)'}) writer.element('path', attrib={'d': dpath, 'fill': f'url(#GR{self._n_gradients:x}_0)', 'shape-rendering': 'crispEdges'}) writer.element('path', attrib={'d': dpath, 'fill': f'url(#GR{self._n_gradients:x}_1)', 'filter': 'url(#colorAdd)', 'shape-rendering': 'crispEdges'}) writer.element('path', attrib={'d': dpath, 'fill': f'url(#GR{self._n_gradients:x}_2)', 'filter': 'url(#colorAdd)', 'shape-rendering': 'crispEdges'}) writer.end('g') self._n_gradients += 1 def draw_gouraud_triangles(self, gc, triangles_array, colors_array, transform): writer = self.writer writer.start('g', **self._get_clip_attrs(gc)) transform = transform.frozen() trans_and_flip = self._make_flip_transform(transform) if not self._has_gouraud: self._has_gouraud = True writer.start('filter', id='colorAdd') writer.element('feComposite', attrib={'in': 'SourceGraphic'}, in2='BackgroundImage', operator='arithmetic', k2='1', k3='1') writer.end('filter') writer.start('filter', id='colorMat') writer.element('feColorMatrix', attrib={'type': 'matrix'}, values='1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n1 1 1 1 0 \n0 0 0 0 1 ') writer.end('filter') for (points, colors) in zip(triangles_array, colors_array): self._draw_gouraud_triangle(trans_and_flip.transform(points), colors) writer.end('g') def option_scale_image(self): return True def get_image_magnification(self): return self.image_dpi / 72.0 def draw_image(self, gc, x, y, im, transform=None): (h, w) = im.shape[:2] if w == 0 or h == 0: return clip_attrs = self._get_clip_attrs(gc) if clip_attrs: self.writer.start('g', **clip_attrs) url = gc.get_url() if url is not None: self.writer.start('a', attrib={'xlink:href': url}) attrib = {} oid = gc.get_gid() if mpl.rcParams['svg.image_inline']: buf = BytesIO() Image.fromarray(im).save(buf, format='png') oid = oid or self._make_id('image', buf.getvalue()) attrib['xlink:href'] = 'data:image/png;base64,\n' + base64.b64encode(buf.getvalue()).decode('ascii') else: if self.basename is None: raise ValueError('Cannot save image data to filesystem when writing SVG to an in-memory buffer') filename = f'{self.basename}.image{next(self._image_counter)}.png' _log.info('Writing image file for inclusion: %s', filename) Image.fromarray(im).save(filename) oid = oid or 'Im_' + self._make_id('image', filename) attrib['xlink:href'] = filename attrib['id'] = oid if transform is None: w = 72.0 * w / self.image_dpi h = 72.0 * h / self.image_dpi self.writer.element('image', transform=_generate_transform([('scale', (1, -1)), ('translate', (0, -h))]), x=_short_float_fmt(x), y=_short_float_fmt(-(self.height - y - h)), width=_short_float_fmt(w), height=_short_float_fmt(h), attrib=attrib) else: alpha = gc.get_alpha() if alpha != 1.0: attrib['opacity'] = _short_float_fmt(alpha) flipped = Affine2D().scale(1.0 / w, 1.0 / h) + transform + Affine2D().translate(x, y).scale(1.0, -1.0).translate(0.0, self.height) attrib['transform'] = _generate_transform([('matrix', flipped.frozen())]) attrib['style'] = 'image-rendering:crisp-edges;image-rendering:pixelated' self.writer.element('image', width=_short_float_fmt(w), height=_short_float_fmt(h), attrib=attrib) if url is not None: self.writer.end('a') if clip_attrs: self.writer.end('g') def _update_glyph_map_defs(self, glyph_map_new): writer = self.writer if glyph_map_new: writer.start('defs') for (char_id, (vertices, codes)) in glyph_map_new.items(): char_id = self._adjust_char_id(char_id) path_data = self._convert_path(Path(vertices * 64, codes), simplify=False) writer.element('path', id=char_id, d=path_data, transform=_generate_transform([('scale', (1 / 64,))])) writer.end('defs') self._glyph_map.update(glyph_map_new) def _adjust_char_id(self, char_id): return char_id.replace('%20', '_') def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None): writer = self.writer writer.comment(s) glyph_map = self._glyph_map text2path = self._text2path color = rgb2hex(gc.get_rgb()) fontsize = prop.get_size_in_points() style = {} if color != '#000000': style['fill'] = color alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3] if alpha != 1: style['opacity'] = _short_float_fmt(alpha) font_scale = fontsize / text2path.FONT_SCALE attrib = {'style': _generate_css(style), 'transform': _generate_transform([('translate', (x, y)), ('rotate', (-angle,)), ('scale', (font_scale, -font_scale))])} writer.start('g', attrib=attrib) if not ismath: font = text2path._get_font(prop) _glyphs = text2path.get_glyphs_with_font(font, s, glyph_map=glyph_map, return_new_glyphs_only=True) (glyph_info, glyph_map_new, rects) = _glyphs self._update_glyph_map_defs(glyph_map_new) for (glyph_id, xposition, yposition, scale) in glyph_info: writer.element('use', transform=_generate_transform([('translate', (xposition, yposition)), ('scale', (scale,))]), attrib={'xlink:href': f'#{glyph_id}'}) else: if ismath == 'TeX': _glyphs = text2path.get_glyphs_tex(prop, s, glyph_map=glyph_map, return_new_glyphs_only=True) else: _glyphs = text2path.get_glyphs_mathtext(prop, s, glyph_map=glyph_map, return_new_glyphs_only=True) (glyph_info, glyph_map_new, rects) = _glyphs self._update_glyph_map_defs(glyph_map_new) for (char_id, xposition, yposition, scale) in glyph_info: char_id = self._adjust_char_id(char_id) writer.element('use', transform=_generate_transform([('translate', (xposition, yposition)), ('scale', (scale,))]), attrib={'xlink:href': f'#{char_id}'}) for (verts, codes) in rects: path = Path(verts, codes) path_data = self._convert_path(path, simplify=False) writer.element('path', d=path_data) writer.end('g') def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): writer = self.writer color = rgb2hex(gc.get_rgb()) font_style = {} color_style = {} if color != '#000000': color_style['fill'] = color alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3] if alpha != 1: color_style['opacity'] = _short_float_fmt(alpha) if not ismath: attrib = {} if prop.get_style() != 'normal': font_style['font-style'] = prop.get_style() if prop.get_variant() != 'normal': font_style['font-variant'] = prop.get_variant() weight = fm.weight_dict[prop.get_weight()] if weight != 400: font_style['font-weight'] = f'{weight}' def _normalize_sans(name): return 'sans-serif' if name in ['sans', 'sans serif'] else name def _expand_family_entry(fn): fn = _normalize_sans(fn) if fn in fm.font_family_aliases: for name in fm.FontManager._expand_aliases(fn): yield _normalize_sans(name) yield fn def _get_all_quoted_names(prop): return [name if name in fm.font_family_aliases else repr(name) for entry in prop.get_family() for name in _expand_family_entry(entry)] font_style['font-size'] = f'{_short_float_fmt(prop.get_size())}px' font_style['font-family'] = ', '.join(dict.fromkeys(_get_all_quoted_names(prop))) if prop.get_stretch() != 'normal': font_style['font-stretch'] = prop.get_stretch() attrib['style'] = _generate_css({**font_style, **color_style}) if mtext and (angle == 0 or mtext.get_rotation_mode() == 'anchor'): transform = mtext.get_transform() (ax, ay) = transform.transform(mtext.get_unitless_position()) ay = self.height - ay angle_rad = np.deg2rad(angle) dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)]) v_offset = np.dot(dir_vert, [x - ax, y - ay]) ax = ax + v_offset * dir_vert[0] ay = ay + v_offset * dir_vert[1] ha_mpl_to_svg = {'left': 'start', 'right': 'end', 'center': 'middle'} font_style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()] attrib['x'] = _short_float_fmt(ax) attrib['y'] = _short_float_fmt(ay) attrib['style'] = _generate_css({**font_style, **color_style}) attrib['transform'] = _generate_transform([('rotate', (-angle, ax, ay))]) else: attrib['transform'] = _generate_transform([('translate', (x, y)), ('rotate', (-angle,))]) writer.element('text', s, attrib=attrib) else: writer.comment(s) (width, height, descent, glyphs, rects) = self._text2path.mathtext_parser.parse(s, 72, prop) writer.start('g', style=_generate_css({**font_style, **color_style}), transform=_generate_transform([('translate', (x, y)), ('rotate', (-angle,))])) writer.start('text') spans = {} for (font, fontsize, thetext, new_x, new_y) in glyphs: entry = fm.ttfFontProperty(font) font_style = {} if entry.style != 'normal': font_style['font-style'] = entry.style if entry.variant != 'normal': font_style['font-variant'] = entry.variant if entry.weight != 400: font_style['font-weight'] = f'{entry.weight}' font_style['font-size'] = f'{_short_float_fmt(fontsize)}px' font_style['font-family'] = f'{entry.name!r}' if entry.stretch != 'normal': font_style['font-stretch'] = entry.stretch style = _generate_css({**font_style, **color_style}) if thetext == 32: thetext = 160 spans.setdefault(style, []).append((new_x, -new_y, thetext)) for (style, chars) in spans.items(): chars.sort() for (x, y, t) in chars: writer.element('tspan', chr(t), x=_short_float_fmt(x), y=_short_float_fmt(y), style=style) writer.end('text') for (x, y, width, height) in rects: writer.element('rect', x=_short_float_fmt(x), y=_short_float_fmt(-y - 1), width=_short_float_fmt(width), height=_short_float_fmt(height)) writer.end('g') def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): clip_attrs = self._get_clip_attrs(gc) if clip_attrs: self.writer.start('g', **clip_attrs) if gc.get_url() is not None: self.writer.start('a', {'xlink:href': gc.get_url()}) if mpl.rcParams['svg.fonttype'] == 'path': self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext) else: self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext) if gc.get_url() is not None: self.writer.end('a') if clip_attrs: self.writer.end('g') def flipy(self): return True def get_canvas_width_height(self): return (self.width, self.height) def get_text_width_height_descent(self, s, prop, ismath): return self._text2path.get_text_width_height_descent(s, prop, ismath) class FigureCanvasSVG(FigureCanvasBase): filetypes = {'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics'} fixed_dpi = 72 def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None): with cbook.open_file_cm(filename, 'w', encoding='utf-8') as fh: if not cbook.file_requires_unicode(fh): fh = codecs.getwriter('utf-8')(fh) dpi = self.figure.dpi self.figure.dpi = 72 (width, height) = self.figure.get_size_inches() (w, h) = (width * 72, height * 72) renderer = MixedModeRenderer(self.figure, width, height, dpi, RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata), bbox_inches_restore=bbox_inches_restore) self.figure.draw(renderer) renderer.finalize() def print_svgz(self, filename, **kwargs): with cbook.open_file_cm(filename, 'wb') as fh, gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter: return self.print_svg(gzipwriter, **kwargs) def get_default_filetype(self): return 'svg' def draw(self): self.figure.draw_without_rendering() return super().draw() FigureManagerSVG = FigureManagerBase svgProlog = '\n\n' @_Backend.export class _BackendSVG(_Backend): backend_version = mpl.__version__ FigureCanvas = FigureCanvasSVG # File: matplotlib-main/lib/matplotlib/backends/backend_template.py """""" from matplotlib import _api from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase from matplotlib.figure import Figure class RendererTemplate(RendererBase): def __init__(self, dpi): super().__init__() self.dpi = dpi def draw_path(self, gc, path, transform, rgbFace=None): pass def draw_image(self, gc, x, y, im): pass def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): pass def flipy(self): return True def get_canvas_width_height(self): return (100, 100) def get_text_width_height_descent(self, s, prop, ismath): return (1, 1, 1) def new_gc(self): return GraphicsContextTemplate() def points_to_pixels(self, points): return points class GraphicsContextTemplate(GraphicsContextBase): class FigureManagerTemplate(FigureManagerBase): class FigureCanvasTemplate(FigureCanvasBase): manager_class = FigureManagerTemplate def draw(self): renderer = RendererTemplate(self.figure.dpi) self.figure.draw(renderer) filetypes = {**FigureCanvasBase.filetypes, 'foo': 'My magic Foo format'} def print_foo(self, filename, **kwargs): self.draw() def get_default_filetype(self): return 'foo' FigureCanvas = FigureCanvasTemplate FigureManager = FigureManagerTemplate # File: matplotlib-main/lib/matplotlib/backends/backend_tkagg.py from . import _backend_tk from .backend_agg import FigureCanvasAgg from ._backend_tk import _BackendTk, FigureCanvasTk from ._backend_tk import FigureManagerTk, NavigationToolbar2Tk class FigureCanvasTkAgg(FigureCanvasAgg, FigureCanvasTk): def draw(self): super().draw() self.blit() def blit(self, bbox=None): _backend_tk.blit(self._tkphoto, self.renderer.buffer_rgba(), (0, 1, 2, 3), bbox=bbox) @_BackendTk.export class _BackendTkAgg(_BackendTk): FigureCanvas = FigureCanvasTkAgg # File: matplotlib-main/lib/matplotlib/backends/backend_tkcairo.py import sys import numpy as np from . import _backend_tk from .backend_cairo import cairo, FigureCanvasCairo from ._backend_tk import _BackendTk, FigureCanvasTk class FigureCanvasTkCairo(FigureCanvasCairo, FigureCanvasTk): def draw(self): width = int(self.figure.bbox.width) height = int(self.figure.bbox.height) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) self._renderer.set_context(cairo.Context(surface)) self._renderer.dpi = self.figure.dpi self.figure.draw(self._renderer) buf = np.reshape(surface.get_data(), (height, width, 4)) _backend_tk.blit(self._tkphoto, buf, (2, 1, 0, 3) if sys.byteorder == 'little' else (1, 2, 3, 0)) @_BackendTk.export class _BackendTkCairo(_BackendTk): FigureCanvas = FigureCanvasTkCairo # File: matplotlib-main/lib/matplotlib/backends/backend_webagg.py """""" from contextlib import contextmanager import errno from io import BytesIO import json import mimetypes from pathlib import Path import random import sys import signal import threading try: import tornado except ImportError as err: raise RuntimeError('The WebAgg backend requires Tornado.') from err import tornado.web import tornado.ioloop import tornado.websocket import matplotlib as mpl from matplotlib.backend_bases import _Backend from matplotlib._pylab_helpers import Gcf from . import backend_webagg_core as core from .backend_webagg_core import TimerAsyncio, TimerTornado webagg_server_thread = threading.Thread(target=lambda : tornado.ioloop.IOLoop.instance().start()) class FigureManagerWebAgg(core.FigureManagerWebAgg): _toolbar2_class = core.NavigationToolbar2WebAgg @classmethod def pyplot_show(cls, *, block=None): WebAggApplication.initialize() url = 'http://{address}:{port}{prefix}'.format(address=WebAggApplication.address, port=WebAggApplication.port, prefix=WebAggApplication.url_prefix) if mpl.rcParams['webagg.open_in_browser']: import webbrowser if not webbrowser.open(url): print(f'To view figure, visit {url}') else: print(f'To view figure, visit {url}') WebAggApplication.start() class FigureCanvasWebAgg(core.FigureCanvasWebAggCore): manager_class = FigureManagerWebAgg class WebAggApplication(tornado.web.Application): initialized = False started = False class FavIcon(tornado.web.RequestHandler): def get(self): self.set_header('Content-Type', 'image/png') self.write(Path(mpl.get_data_path(), 'images/matplotlib.png').read_bytes()) class SingleFigurePage(tornado.web.RequestHandler): def __init__(self, application, request, *, url_prefix='', **kwargs): self.url_prefix = url_prefix super().__init__(application, request, **kwargs) def get(self, fignum): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) ws_uri = f'ws://{self.request.host}{self.url_prefix}/' self.render('single_figure.html', prefix=self.url_prefix, ws_uri=ws_uri, fig_id=fignum, toolitems=core.NavigationToolbar2WebAgg.toolitems, canvas=manager.canvas) class AllFiguresPage(tornado.web.RequestHandler): def __init__(self, application, request, *, url_prefix='', **kwargs): self.url_prefix = url_prefix super().__init__(application, request, **kwargs) def get(self): ws_uri = f'ws://{self.request.host}{self.url_prefix}/' self.render('all_figures.html', prefix=self.url_prefix, ws_uri=ws_uri, figures=sorted(Gcf.figs.items()), toolitems=core.NavigationToolbar2WebAgg.toolitems) class MplJs(tornado.web.RequestHandler): def get(self): self.set_header('Content-Type', 'application/javascript') js_content = core.FigureManagerWebAgg.get_javascript() self.write(js_content) class Download(tornado.web.RequestHandler): def get(self, fignum, fmt): fignum = int(fignum) manager = Gcf.get_fig_manager(fignum) self.set_header('Content-Type', mimetypes.types_map.get(fmt, 'binary')) buff = BytesIO() manager.canvas.figure.savefig(buff, format=fmt) self.write(buff.getvalue()) class WebSocket(tornado.websocket.WebSocketHandler): supports_binary = True def open(self, fignum): self.fignum = int(fignum) self.manager = Gcf.get_fig_manager(self.fignum) self.manager.add_web_socket(self) if hasattr(self, 'set_nodelay'): self.set_nodelay(True) def on_close(self): self.manager.remove_web_socket(self) def on_message(self, message): message = json.loads(message) if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: manager = Gcf.get_fig_manager(self.fignum) if manager is not None: manager.handle_json(message) def send_json(self, content): self.write_message(json.dumps(content)) def send_binary(self, blob): if self.supports_binary: self.write_message(blob, binary=True) else: data_uri = 'data:image/png;base64,{}'.format(blob.encode('base64').replace('\n', '')) self.write_message(data_uri) def __init__(self, url_prefix=''): if url_prefix: assert url_prefix[0] == '/' and url_prefix[-1] != '/', 'url_prefix must start with a "/" and not end with one.' super().__init__([(url_prefix + '/_static/(.*)', tornado.web.StaticFileHandler, {'path': core.FigureManagerWebAgg.get_static_file_path()}), (url_prefix + '/_images/(.*)', tornado.web.StaticFileHandler, {'path': Path(mpl.get_data_path(), 'images')}), (url_prefix + '/favicon.ico', self.FavIcon), (url_prefix + '/([0-9]+)', self.SingleFigurePage, {'url_prefix': url_prefix}), (url_prefix + '/?', self.AllFiguresPage, {'url_prefix': url_prefix}), (url_prefix + '/js/mpl.js', self.MplJs), (url_prefix + '/([0-9]+)/ws', self.WebSocket), (url_prefix + '/([0-9]+)/download.([a-z0-9.]+)', self.Download)], template_path=core.FigureManagerWebAgg.get_static_file_path()) @classmethod def initialize(cls, url_prefix='', port=None, address=None): if cls.initialized: return app = cls(url_prefix=url_prefix) cls.url_prefix = url_prefix def random_ports(port, n): for i in range(min(5, n)): yield (port + i) for i in range(n - 5): yield (port + random.randint(-2 * n, 2 * n)) if address is None: cls.address = mpl.rcParams['webagg.address'] else: cls.address = address cls.port = mpl.rcParams['webagg.port'] for port in random_ports(cls.port, mpl.rcParams['webagg.port_retries']): try: app.listen(port, cls.address) except OSError as e: if e.errno != errno.EADDRINUSE: raise else: cls.port = port break else: raise SystemExit('The webagg server could not be started because an available port could not be found') cls.initialized = True @classmethod def start(cls): import asyncio try: asyncio.get_running_loop() except RuntimeError: pass else: cls.started = True if cls.started: return '' ioloop = tornado.ioloop.IOLoop.instance() def shutdown(): ioloop.stop() print('Server is stopped') sys.stdout.flush() cls.started = False @contextmanager def catch_sigint(): old_handler = signal.signal(signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(shutdown)) try: yield finally: signal.signal(signal.SIGINT, old_handler) cls.started = True print('Press Ctrl+C to stop WebAgg server') sys.stdout.flush() with catch_sigint(): ioloop.start() def ipython_inline_display(figure): import tornado.template WebAggApplication.initialize() import asyncio try: asyncio.get_running_loop() except RuntimeError: if not webagg_server_thread.is_alive(): webagg_server_thread.start() fignum = figure.number tpl = Path(core.FigureManagerWebAgg.get_static_file_path(), 'ipython_inline_figure.html').read_text() t = tornado.template.Template(tpl) return t.generate(prefix=WebAggApplication.url_prefix, fig_id=fignum, toolitems=core.NavigationToolbar2WebAgg.toolitems, canvas=figure.canvas, port=WebAggApplication.port).decode('utf-8') @_Backend.export class _BackendWebAgg(_Backend): FigureCanvas = FigureCanvasWebAgg FigureManager = FigureManagerWebAgg # File: matplotlib-main/lib/matplotlib/backends/backend_webagg_core.py """""" import asyncio import datetime from io import BytesIO, StringIO import json import logging import os from pathlib import Path import numpy as np from PIL import Image from matplotlib import _api, backend_bases, backend_tools from matplotlib.backends import backend_agg from matplotlib.backend_bases import _Backend, KeyEvent, LocationEvent, MouseEvent, ResizeEvent _log = logging.getLogger(__name__) _SPECIAL_KEYS_LUT = {'Alt': 'alt', 'AltGraph': 'alt', 'CapsLock': 'caps_lock', 'Control': 'control', 'Meta': 'meta', 'NumLock': 'num_lock', 'ScrollLock': 'scroll_lock', 'Shift': 'shift', 'Super': 'super', 'Enter': 'enter', 'Tab': 'tab', 'ArrowDown': 'down', 'ArrowLeft': 'left', 'ArrowRight': 'right', 'ArrowUp': 'up', 'End': 'end', 'Home': 'home', 'PageDown': 'pagedown', 'PageUp': 'pageup', 'Backspace': 'backspace', 'Delete': 'delete', 'Insert': 'insert', 'Escape': 'escape', 'Pause': 'pause', 'Select': 'select', 'Dead': 'dead', 'F1': 'f1', 'F2': 'f2', 'F3': 'f3', 'F4': 'f4', 'F5': 'f5', 'F6': 'f6', 'F7': 'f7', 'F8': 'f8', 'F9': 'f9', 'F10': 'f10', 'F11': 'f11', 'F12': 'f12'} def _handle_key(key): value = key[key.index('k') + 1:] if 'shift+' in key: if len(value) == 1: key = key.replace('shift+', '') if value in _SPECIAL_KEYS_LUT: value = _SPECIAL_KEYS_LUT[value] key = key[:key.index('k')] + value return key class TimerTornado(backend_bases.TimerBase): def __init__(self, *args, **kwargs): self._timer = None super().__init__(*args, **kwargs) def _timer_start(self): import tornado self._timer_stop() if self._single: ioloop = tornado.ioloop.IOLoop.instance() self._timer = ioloop.add_timeout(datetime.timedelta(milliseconds=self.interval), self._on_timer) else: self._timer = tornado.ioloop.PeriodicCallback(self._on_timer, max(self.interval, 1e-06)) self._timer.start() def _timer_stop(self): import tornado if self._timer is None: return elif self._single: ioloop = tornado.ioloop.IOLoop.instance() ioloop.remove_timeout(self._timer) else: self._timer.stop() self._timer = None def _timer_set_interval(self): if self._timer is not None: self._timer_stop() self._timer_start() class TimerAsyncio(backend_bases.TimerBase): def __init__(self, *args, **kwargs): self._task = None super().__init__(*args, **kwargs) async def _timer_task(self, interval): while True: try: await asyncio.sleep(interval) self._on_timer() if self._single: break except asyncio.CancelledError: break def _timer_start(self): self._timer_stop() self._task = asyncio.ensure_future(self._timer_task(max(self.interval / 1000.0, 1e-06))) def _timer_stop(self): if self._task is not None: self._task.cancel() self._task = None def _timer_set_interval(self): if self._task is not None: self._timer_stop() self._timer_start() class FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg): manager_class = _api.classproperty(lambda cls: FigureManagerWebAgg) _timer_cls = TimerAsyncio supports_blit = False def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._png_is_old = True self._force_full = True self._last_buff = np.empty((0, 0)) self._current_image_mode = 'full' self._last_mouse_xy = (None, None) def show(self): from matplotlib.pyplot import show show() def draw(self): self._png_is_old = True try: super().draw() finally: self.manager.refresh_all() def blit(self, bbox=None): self._png_is_old = True self.manager.refresh_all() def draw_idle(self): self.send_event('draw') def set_cursor(self, cursor): cursor = _api.check_getitem({backend_tools.Cursors.HAND: 'pointer', backend_tools.Cursors.POINTER: 'default', backend_tools.Cursors.SELECT_REGION: 'crosshair', backend_tools.Cursors.MOVE: 'move', backend_tools.Cursors.WAIT: 'wait', backend_tools.Cursors.RESIZE_HORIZONTAL: 'ew-resize', backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize'}, cursor=cursor) self.send_event('cursor', cursor=cursor) def set_image_mode(self, mode): _api.check_in_list(['full', 'diff'], mode=mode) if self._current_image_mode != mode: self._current_image_mode = mode self.handle_send_image_mode(None) def get_diff_image(self): if self._png_is_old: renderer = self.get_renderer() pixels = np.asarray(renderer.buffer_rgba()) buff = pixels.view(np.uint32).squeeze(2) if self._force_full or buff.shape != self._last_buff.shape or (pixels[:, :, 3] != 255).any(): self.set_image_mode('full') output = buff else: self.set_image_mode('diff') diff = buff != self._last_buff output = np.where(diff, buff, 0) self._last_buff = buff.copy() self._force_full = False self._png_is_old = False data = output.view(dtype=np.uint8).reshape((*output.shape, 4)) with BytesIO() as png: Image.fromarray(data).save(png, format='png') return png.getvalue() def handle_event(self, event): e_type = event['type'] handler = getattr(self, f'handle_{e_type}', self.handle_unknown_event) return handler(event) def handle_unknown_event(self, event): _log.warning('Unhandled message type %s. %s', event['type'], event) def handle_ack(self, event): pass def handle_draw(self, event): self.draw() def _handle_mouse(self, event): x = event['x'] y = event['y'] y = self.get_renderer().height - y self._last_mouse_xy = (x, y) button = event['button'] + 1 e_type = event['type'] modifiers = event['modifiers'] guiEvent = event.get('guiEvent') if e_type in ['button_press', 'button_release']: MouseEvent(e_type + '_event', self, x, y, button, modifiers=modifiers, guiEvent=guiEvent)._process() elif e_type == 'dblclick': MouseEvent('button_press_event', self, x, y, button, dblclick=True, modifiers=modifiers, guiEvent=guiEvent)._process() elif e_type == 'scroll': MouseEvent('scroll_event', self, x, y, step=event['step'], modifiers=modifiers, guiEvent=guiEvent)._process() elif e_type == 'motion_notify': MouseEvent(e_type + '_event', self, x, y, modifiers=modifiers, guiEvent=guiEvent)._process() elif e_type in ['figure_enter', 'figure_leave']: LocationEvent(e_type + '_event', self, x, y, modifiers=modifiers, guiEvent=guiEvent)._process() handle_button_press = handle_button_release = handle_dblclick = handle_figure_enter = handle_figure_leave = handle_motion_notify = handle_scroll = _handle_mouse def _handle_key(self, event): KeyEvent(event['type'] + '_event', self, _handle_key(event['key']), *self._last_mouse_xy, guiEvent=event.get('guiEvent'))._process() handle_key_press = handle_key_release = _handle_key def handle_toolbar_button(self, event): getattr(self.toolbar, event['name'])() def handle_refresh(self, event): figure_label = self.figure.get_label() if not figure_label: figure_label = f'Figure {self.manager.num}' self.send_event('figure_label', label=figure_label) self._force_full = True if self.toolbar: self.toolbar.set_history_buttons() self.draw_idle() def handle_resize(self, event): x = int(event.get('width', 800)) * self.device_pixel_ratio y = int(event.get('height', 800)) * self.device_pixel_ratio fig = self.figure fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False) self._png_is_old = True self.manager.resize(*fig.bbox.size, forward=False) ResizeEvent('resize_event', self)._process() self.draw_idle() def handle_send_image_mode(self, event): self.send_event('image_mode', mode=self._current_image_mode) def handle_set_device_pixel_ratio(self, event): self._handle_set_device_pixel_ratio(event.get('device_pixel_ratio', 1)) def handle_set_dpi_ratio(self, event): self._handle_set_device_pixel_ratio(event.get('dpi_ratio', 1)) def _handle_set_device_pixel_ratio(self, device_pixel_ratio): if self._set_device_pixel_ratio(device_pixel_ratio): self._force_full = True self.draw_idle() def send_event(self, event_type, **kwargs): if self.manager: self.manager._send_event(event_type, **kwargs) _ALLOWED_TOOL_ITEMS = {'home', 'back', 'forward', 'pan', 'zoom', 'download', None} class NavigationToolbar2WebAgg(backend_bases.NavigationToolbar2): toolitems = [(text, tooltip_text, image_file, name_of_method) for (text, tooltip_text, image_file, name_of_method) in (*backend_bases.NavigationToolbar2.toolitems, ('Download', 'Download plot', 'filesave', 'download')) if name_of_method in _ALLOWED_TOOL_ITEMS] def __init__(self, canvas): self.message = '' super().__init__(canvas) def set_message(self, message): if message != self.message: self.canvas.send_event('message', message=message) self.message = message def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.send_event('rubberband', x0=x0, y0=y0, x1=x1, y1=y1) def remove_rubberband(self): self.canvas.send_event('rubberband', x0=-1, y0=-1, x1=-1, y1=-1) def save_figure(self, *args): self.canvas.send_event('save') def pan(self): super().pan() self.canvas.send_event('navigate_mode', mode=self.mode.name) def zoom(self): super().zoom() self.canvas.send_event('navigate_mode', mode=self.mode.name) def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 self.canvas.send_event('history_buttons', Back=can_backward, Forward=can_forward) class FigureManagerWebAgg(backend_bases.FigureManagerBase): _toolbar2_class = None ToolbarCls = NavigationToolbar2WebAgg _window_title = 'Matplotlib' def __init__(self, canvas, num): self.web_sockets = set() super().__init__(canvas, num) def show(self): pass def resize(self, w, h, forward=True): self._send_event('resize', size=(w / self.canvas.device_pixel_ratio, h / self.canvas.device_pixel_ratio), forward=forward) def set_window_title(self, title): self._send_event('figure_label', label=title) self._window_title = title def get_window_title(self): return self._window_title def add_web_socket(self, web_socket): assert hasattr(web_socket, 'send_binary') assert hasattr(web_socket, 'send_json') self.web_sockets.add(web_socket) self.resize(*self.canvas.figure.bbox.size) self._send_event('refresh') def remove_web_socket(self, web_socket): self.web_sockets.remove(web_socket) def handle_json(self, content): self.canvas.handle_event(content) def refresh_all(self): if self.web_sockets: diff = self.canvas.get_diff_image() if diff is not None: for s in self.web_sockets: s.send_binary(diff) @classmethod def get_javascript(cls, stream=None): if stream is None: output = StringIO() else: output = stream output.write((Path(__file__).parent / 'web_backend/js/mpl.js').read_text(encoding='utf-8')) toolitems = [] for (name, tooltip, image, method) in cls.ToolbarCls.toolitems: if name is None: toolitems.append(['', '', '', '']) else: toolitems.append([name, tooltip, image, method]) output.write(f'mpl.toolbar_items = {json.dumps(toolitems)};\n\n') extensions = [] for (filetype, ext) in sorted(FigureCanvasWebAggCore.get_supported_filetypes_grouped().items()): extensions.append(ext[0]) output.write(f'mpl.extensions = {json.dumps(extensions)};\n\n') output.write('mpl.default_extension = {};'.format(json.dumps(FigureCanvasWebAggCore.get_default_filetype()))) if stream is None: return output.getvalue() @classmethod def get_static_file_path(cls): return os.path.join(os.path.dirname(__file__), 'web_backend') def _send_event(self, event_type, **kwargs): payload = {'type': event_type, **kwargs} for s in self.web_sockets: s.send_json(payload) @_Backend.export class _BackendWebAggCoreAgg(_Backend): FigureCanvas = FigureCanvasWebAggCore FigureManager = FigureManagerWebAgg # File: matplotlib-main/lib/matplotlib/backends/backend_wx.py """""" import functools import logging import math import pathlib import sys import weakref import numpy as np import PIL.Image import matplotlib as mpl from matplotlib.backend_bases import _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase, TimerBase, ToolContainerBase, cursors, CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent from matplotlib import _api, cbook, backend_tools, _c_internal_utils from matplotlib._pylab_helpers import Gcf from matplotlib.path import Path from matplotlib.transforms import Affine2D import wx import wx.svg _log = logging.getLogger(__name__) PIXELS_PER_INCH = 75 @functools.lru_cache(1) def _create_wxapp(): wxapp = wx.App(False) wxapp.SetExitOnFrameDelete(True) cbook._setup_new_guiapp() _c_internal_utils.Win32_SetProcessDpiAwareness_max() return wxapp class TimerWx(TimerBase): def __init__(self, *args, **kwargs): self._timer = wx.Timer() self._timer.Notify = self._on_timer super().__init__(*args, **kwargs) def _timer_start(self): self._timer.Start(self._interval, self._single) def _timer_stop(self): self._timer.Stop() def _timer_set_interval(self): if self._timer.IsRunning(): self._timer_start() @_api.deprecated('2.0', name='wx', obj_type='backend', removal='the future', alternative='wxagg', addendum='See the Matplotlib usage FAQ for more info on backends.') class RendererWx(RendererBase): fontweights = {100: wx.FONTWEIGHT_LIGHT, 200: wx.FONTWEIGHT_LIGHT, 300: wx.FONTWEIGHT_LIGHT, 400: wx.FONTWEIGHT_NORMAL, 500: wx.FONTWEIGHT_NORMAL, 600: wx.FONTWEIGHT_NORMAL, 700: wx.FONTWEIGHT_BOLD, 800: wx.FONTWEIGHT_BOLD, 900: wx.FONTWEIGHT_BOLD, 'ultralight': wx.FONTWEIGHT_LIGHT, 'light': wx.FONTWEIGHT_LIGHT, 'normal': wx.FONTWEIGHT_NORMAL, 'medium': wx.FONTWEIGHT_NORMAL, 'semibold': wx.FONTWEIGHT_NORMAL, 'bold': wx.FONTWEIGHT_BOLD, 'heavy': wx.FONTWEIGHT_BOLD, 'ultrabold': wx.FONTWEIGHT_BOLD, 'black': wx.FONTWEIGHT_BOLD} fontangles = {'italic': wx.FONTSTYLE_ITALIC, 'normal': wx.FONTSTYLE_NORMAL, 'oblique': wx.FONTSTYLE_SLANT} fontnames = {'Sans': wx.FONTFAMILY_SWISS, 'Roman': wx.FONTFAMILY_ROMAN, 'Script': wx.FONTFAMILY_SCRIPT, 'Decorative': wx.FONTFAMILY_DECORATIVE, 'Modern': wx.FONTFAMILY_MODERN, 'Courier': wx.FONTFAMILY_MODERN, 'courier': wx.FONTFAMILY_MODERN} def __init__(self, bitmap, dpi): super().__init__() _log.debug('%s - __init__()', type(self)) self.width = bitmap.GetWidth() self.height = bitmap.GetHeight() self.bitmap = bitmap self.fontd = {} self.dpi = dpi self.gc = None def flipy(self): return True def get_text_width_height_descent(self, s, prop, ismath): if ismath: s = cbook.strip_math(s) if self.gc is None: gc = self.new_gc() else: gc = self.gc gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) gfx_ctx.SetFont(font, wx.BLACK) (w, h, descent, leading) = gfx_ctx.GetFullTextExtent(s) return (w, h, descent) def get_canvas_width_height(self): return (self.width, self.height) def handle_clip_rectangle(self, gc): new_bounds = gc.get_clip_rectangle() if new_bounds is not None: new_bounds = new_bounds.bounds gfx_ctx = gc.gfx_ctx if gfx_ctx._lastcliprect != new_bounds: gfx_ctx._lastcliprect = new_bounds if new_bounds is None: gfx_ctx.ResetClip() else: gfx_ctx.Clip(new_bounds[0], self.height - new_bounds[1] - new_bounds[3], new_bounds[2], new_bounds[3]) @staticmethod def convert_path(gfx_ctx, path, transform): wxpath = gfx_ctx.CreatePath() for (points, code) in path.iter_segments(transform): if code == Path.MOVETO: wxpath.MoveToPoint(*points) elif code == Path.LINETO: wxpath.AddLineToPoint(*points) elif code == Path.CURVE3: wxpath.AddQuadCurveToPoint(*points) elif code == Path.CURVE4: wxpath.AddCurveToPoint(*points) elif code == Path.CLOSEPOLY: wxpath.CloseSubpath() return wxpath def draw_path(self, gc, path, transform, rgbFace=None): gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx transform = transform + Affine2D().scale(1.0, -1.0).translate(0.0, self.height) wxpath = self.convert_path(gfx_ctx, path, transform) if rgbFace is not None: gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace))) gfx_ctx.DrawPath(wxpath) else: gfx_ctx.StrokePath(wxpath) gc.unselect() def draw_image(self, gc, x, y, im): bbox = gc.get_clip_rectangle() if bbox is not None: (l, b, w, h) = bbox.bounds else: l = 0 b = 0 w = self.width h = self.height (rows, cols) = im.shape[:2] bitmap = wx.Bitmap.FromBufferRGBA(cols, rows, im.tobytes()) gc.select() gc.gfx_ctx.DrawBitmap(bitmap, int(l), int(self.height - b), int(w), int(-h)) gc.unselect() def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): if ismath: s = cbook.strip_math(s) _log.debug('%s - draw_text()', type(self)) gc.select() self.handle_clip_rectangle(gc) gfx_ctx = gc.gfx_ctx font = self.get_wx_font(s, prop) color = gc.get_wxcolour(gc.get_rgb()) gfx_ctx.SetFont(font, color) (w, h, d) = self.get_text_width_height_descent(s, prop, ismath) x = int(x) y = int(y - h) if angle == 0.0: gfx_ctx.DrawText(s, x, y) else: rads = math.radians(angle) xo = h * math.sin(rads) yo = h * math.cos(rads) gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads) gc.unselect() def new_gc(self): _log.debug('%s - new_gc()', type(self)) self.gc = GraphicsContextWx(self.bitmap, self) self.gc.select() self.gc.unselect() return self.gc def get_wx_font(self, s, prop): _log.debug('%s - get_wx_font()', type(self)) key = hash(prop) font = self.fontd.get(key) if font is not None: return font size = self.points_to_pixels(prop.get_size_in_points()) self.fontd[key] = font = wx.Font(pointSize=round(size), family=self.fontnames.get(prop.get_name(), wx.ROMAN), style=self.fontangles[prop.get_style()], weight=self.fontweights[prop.get_weight()]) return font def points_to_pixels(self, points): return points * (PIXELS_PER_INCH / 72.0 * self.dpi / 72.0) class GraphicsContextWx(GraphicsContextBase): _capd = {'butt': wx.CAP_BUTT, 'projecting': wx.CAP_PROJECTING, 'round': wx.CAP_ROUND} _joind = {'bevel': wx.JOIN_BEVEL, 'miter': wx.JOIN_MITER, 'round': wx.JOIN_ROUND} _cache = weakref.WeakKeyDictionary() def __init__(self, bitmap, renderer): super().__init__() _log.debug('%s - __init__(): %s', type(self), bitmap) (dc, gfx_ctx) = self._cache.get(bitmap, (None, None)) if dc is None: dc = wx.MemoryDC(bitmap) gfx_ctx = wx.GraphicsContext.Create(dc) gfx_ctx._lastcliprect = None self._cache[bitmap] = (dc, gfx_ctx) self.bitmap = bitmap self.dc = dc self.gfx_ctx = gfx_ctx self._pen = wx.Pen('BLACK', 1, wx.SOLID) gfx_ctx.SetPen(self._pen) self.renderer = renderer def select(self): if sys.platform == 'win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True def unselect(self): if sys.platform == 'win32': self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False def set_foreground(self, fg, isRGBA=None): _log.debug('%s - set_foreground()', type(self)) self.select() super().set_foreground(fg, isRGBA) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_linewidth(self, w): w = float(w) _log.debug('%s - set_linewidth()', type(self)) self.select() if 0 < w < 1: w = 1 super().set_linewidth(w) lw = int(self.renderer.points_to_pixels(self._linewidth)) if lw == 0: lw = 1 self._pen.SetWidth(lw) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_capstyle(self, cs): _log.debug('%s - set_capstyle()', type(self)) self.select() super().set_capstyle(cs) self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_joinstyle(self, js): _log.debug('%s - set_joinstyle()', type(self)) self.select() super().set_joinstyle(js) self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def get_wxcolour(self, color): _log.debug('%s - get_wx_color()', type(self)) return wx.Colour(*[int(255 * x) for x in color]) class _FigureCanvasWxBase(FigureCanvasBase, wx.Panel): required_interactive_framework = 'wx' _timer_cls = TimerWx manager_class = _api.classproperty(lambda cls: FigureManagerWx) keyvald = {wx.WXK_CONTROL: 'control', wx.WXK_SHIFT: 'shift', wx.WXK_ALT: 'alt', wx.WXK_CAPITAL: 'caps_lock', wx.WXK_LEFT: 'left', wx.WXK_UP: 'up', wx.WXK_RIGHT: 'right', wx.WXK_DOWN: 'down', wx.WXK_ESCAPE: 'escape', wx.WXK_F1: 'f1', wx.WXK_F2: 'f2', wx.WXK_F3: 'f3', wx.WXK_F4: 'f4', wx.WXK_F5: 'f5', wx.WXK_F6: 'f6', wx.WXK_F7: 'f7', wx.WXK_F8: 'f8', wx.WXK_F9: 'f9', wx.WXK_F10: 'f10', wx.WXK_F11: 'f11', wx.WXK_F12: 'f12', wx.WXK_SCROLL: 'scroll_lock', wx.WXK_PAUSE: 'break', wx.WXK_BACK: 'backspace', wx.WXK_RETURN: 'enter', wx.WXK_INSERT: 'insert', wx.WXK_DELETE: 'delete', wx.WXK_HOME: 'home', wx.WXK_END: 'end', wx.WXK_PAGEUP: 'pageup', wx.WXK_PAGEDOWN: 'pagedown', wx.WXK_NUMPAD0: '0', wx.WXK_NUMPAD1: '1', wx.WXK_NUMPAD2: '2', wx.WXK_NUMPAD3: '3', wx.WXK_NUMPAD4: '4', wx.WXK_NUMPAD5: '5', wx.WXK_NUMPAD6: '6', wx.WXK_NUMPAD7: '7', wx.WXK_NUMPAD8: '8', wx.WXK_NUMPAD9: '9', wx.WXK_NUMPAD_ADD: '+', wx.WXK_NUMPAD_SUBTRACT: '-', wx.WXK_NUMPAD_MULTIPLY: '*', wx.WXK_NUMPAD_DIVIDE: '/', wx.WXK_NUMPAD_DECIMAL: 'dec', wx.WXK_NUMPAD_ENTER: 'enter', wx.WXK_NUMPAD_UP: 'up', wx.WXK_NUMPAD_RIGHT: 'right', wx.WXK_NUMPAD_DOWN: 'down', wx.WXK_NUMPAD_LEFT: 'left', wx.WXK_NUMPAD_PAGEUP: 'pageup', wx.WXK_NUMPAD_PAGEDOWN: 'pagedown', wx.WXK_NUMPAD_HOME: 'home', wx.WXK_NUMPAD_END: 'end', wx.WXK_NUMPAD_INSERT: 'insert', wx.WXK_NUMPAD_DELETE: 'delete'} def __init__(self, parent, id, figure=None): FigureCanvasBase.__init__(self, figure) size = wx.Size(*map(math.ceil, self.figure.bbox.size)) if wx.Platform != '__WXMSW__': size = parent.FromDIP(size) wx.Panel.__init__(self, parent, id, size=size) self.bitmap = None self._isDrawn = False self._rubberband_rect = None self._rubberband_pen_black = wx.Pen('BLACK', 1, wx.PENSTYLE_SHORT_DASH) self._rubberband_pen_white = wx.Pen('WHITE', 1, wx.PENSTYLE_SOLID) self.Bind(wx.EVT_SIZE, self._on_size) self.Bind(wx.EVT_PAINT, self._on_paint) self.Bind(wx.EVT_CHAR_HOOK, self._on_key_down) self.Bind(wx.EVT_KEY_UP, self._on_key_up) self.Bind(wx.EVT_LEFT_DOWN, self._on_mouse_button) self.Bind(wx.EVT_LEFT_DCLICK, self._on_mouse_button) self.Bind(wx.EVT_LEFT_UP, self._on_mouse_button) self.Bind(wx.EVT_MIDDLE_DOWN, self._on_mouse_button) self.Bind(wx.EVT_MIDDLE_DCLICK, self._on_mouse_button) self.Bind(wx.EVT_MIDDLE_UP, self._on_mouse_button) self.Bind(wx.EVT_RIGHT_DOWN, self._on_mouse_button) self.Bind(wx.EVT_RIGHT_DCLICK, self._on_mouse_button) self.Bind(wx.EVT_RIGHT_UP, self._on_mouse_button) self.Bind(wx.EVT_MOUSE_AUX1_DOWN, self._on_mouse_button) self.Bind(wx.EVT_MOUSE_AUX1_UP, self._on_mouse_button) self.Bind(wx.EVT_MOUSE_AUX2_DOWN, self._on_mouse_button) self.Bind(wx.EVT_MOUSE_AUX2_UP, self._on_mouse_button) self.Bind(wx.EVT_MOUSE_AUX1_DCLICK, self._on_mouse_button) self.Bind(wx.EVT_MOUSE_AUX2_DCLICK, self._on_mouse_button) self.Bind(wx.EVT_MOUSEWHEEL, self._on_mouse_wheel) self.Bind(wx.EVT_MOTION, self._on_motion) self.Bind(wx.EVT_ENTER_WINDOW, self._on_enter) self.Bind(wx.EVT_LEAVE_WINDOW, self._on_leave) self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self._on_capture_lost) self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self._on_capture_lost) self.SetBackgroundStyle(wx.BG_STYLE_PAINT) self.SetBackgroundColour(wx.WHITE) if wx.Platform == '__WXMAC__': dpiScale = self.GetDPIScaleFactor() self.SetInitialSize(self.GetSize() * (1 / dpiScale)) self._set_device_pixel_ratio(dpiScale) def Copy_to_Clipboard(self, event=None): bmp_obj = wx.BitmapDataObject() bmp_obj.SetBitmap(self.bitmap) if not wx.TheClipboard.IsOpened(): open_success = wx.TheClipboard.Open() if open_success: wx.TheClipboard.SetData(bmp_obj) wx.TheClipboard.Flush() wx.TheClipboard.Close() def _update_device_pixel_ratio(self, *args, **kwargs): if self._set_device_pixel_ratio(self.GetDPIScaleFactor()): self.draw() def draw_idle(self): _log.debug('%s - draw_idle()', type(self)) self._isDrawn = False self.Refresh(eraseBackground=False) def flush_events(self): wx.Yield() def start_event_loop(self, timeout=0): if hasattr(self, '_event_loop'): raise RuntimeError('Event loop already running') timer = wx.Timer(self, id=wx.ID_ANY) if timeout > 0: timer.Start(int(timeout * 1000), oneShot=True) self.Bind(wx.EVT_TIMER, self.stop_event_loop, id=timer.GetId()) self._event_loop = wx.GUIEventLoop() self._event_loop.Run() timer.Stop() def stop_event_loop(self, event=None): if hasattr(self, '_event_loop'): if self._event_loop.IsRunning(): self._event_loop.Exit() del self._event_loop def _get_imagesave_wildcards(self): default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = sorted(filetypes.items()) wildcards = [] extensions = [] filter_index = 0 for (i, (name, exts)) in enumerate(sorted_filetypes): ext_list = ';'.join(['*.%s' % ext for ext in exts]) extensions.append(exts[0]) wildcard = f'{name} ({ext_list})|{ext_list}' if default_filetype in exts: filter_index = i wildcards.append(wildcard) wildcards = '|'.join(wildcards) return (wildcards, extensions, filter_index) def gui_repaint(self, drawDC=None): _log.debug('%s - gui_repaint()', type(self)) if not (self and self.IsShownOnScreen()): return if not drawDC: drawDC = wx.ClientDC(self) bmp = self.bitmap.ConvertToImage().ConvertToBitmap() if wx.Platform == '__WXMSW__' and isinstance(self.figure.canvas.get_renderer(), RendererWx) else self.bitmap drawDC.DrawBitmap(bmp, 0, 0) if self._rubberband_rect is not None: (x0, y0, x1, y1) = map(round, self._rubberband_rect) rect = [(x0, y0, x1, y0), (x1, y0, x1, y1), (x0, y0, x0, y1), (x0, y1, x1, y1)] drawDC.DrawLineList(rect, self._rubberband_pen_white) drawDC.DrawLineList(rect, self._rubberband_pen_black) filetypes = {**FigureCanvasBase.filetypes, 'bmp': 'Windows bitmap', 'jpeg': 'JPEG', 'jpg': 'JPEG', 'pcx': 'PCX', 'png': 'Portable Network Graphics', 'tif': 'Tagged Image Format File', 'tiff': 'Tagged Image Format File', 'xpm': 'X pixmap'} def _on_paint(self, event): _log.debug('%s - _on_paint()', type(self)) drawDC = wx.PaintDC(self) if not self._isDrawn: self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) drawDC.Destroy() def _on_size(self, event): self._update_device_pixel_ratio() _log.debug('%s - _on_size()', type(self)) sz = self.GetParent().GetSizer() if sz: si = sz.GetItem(self) if sz and si and (not si.Proportion) and (not si.Flag & wx.EXPAND): size = self.GetMinSize() else: size = self.GetClientSize() size.IncTo(self.GetMinSize()) if getattr(self, '_width', None): if size == (self._width, self._height): return (self._width, self._height) = size self._isDrawn = False if self._width <= 1 or self._height <= 1: return dpival = self.figure.dpi if not wx.Platform == '__WXMSW__': scale = self.GetDPIScaleFactor() dpival /= scale winch = self._width / dpival hinch = self._height / dpival self.figure.set_size_inches(winch, hinch, forward=False) self.Refresh(eraseBackground=False) ResizeEvent('resize_event', self)._process() self.draw_idle() @staticmethod def _mpl_modifiers(event=None, *, exclude=None): mod_table = [('ctrl', wx.MOD_CONTROL, wx.WXK_CONTROL), ('alt', wx.MOD_ALT, wx.WXK_ALT), ('shift', wx.MOD_SHIFT, wx.WXK_SHIFT)] if event is not None: modifiers = event.GetModifiers() return [name for (name, mod, key) in mod_table if modifiers & mod and exclude != key] else: return [name for (name, mod, key) in mod_table if wx.GetKeyState(key)] def _get_key(self, event): keyval = event.KeyCode if keyval in self.keyvald: key = self.keyvald[keyval] elif keyval < 256: key = chr(keyval) if not event.ShiftDown(): key = key.lower() else: return None mods = self._mpl_modifiers(event, exclude=keyval) if 'shift' in mods and key.isupper(): mods.remove('shift') return '+'.join([*mods, key]) def _mpl_coords(self, pos=None): if pos is None: pos = wx.GetMouseState() (x, y) = self.ScreenToClient(pos.X, pos.Y) else: (x, y) = (pos.X, pos.Y) if not wx.Platform == '__WXMSW__': scale = self.GetDPIScaleFactor() return (x * scale, self.figure.bbox.height - y * scale) else: return (x, self.figure.bbox.height - y) def _on_key_down(self, event): KeyEvent('key_press_event', self, self._get_key(event), *self._mpl_coords(), guiEvent=event)._process() if self: event.Skip() def _on_key_up(self, event): KeyEvent('key_release_event', self, self._get_key(event), *self._mpl_coords(), guiEvent=event)._process() if self: event.Skip() def set_cursor(self, cursor): cursor = wx.Cursor(_api.check_getitem({cursors.MOVE: wx.CURSOR_HAND, cursors.HAND: wx.CURSOR_HAND, cursors.POINTER: wx.CURSOR_ARROW, cursors.SELECT_REGION: wx.CURSOR_CROSS, cursors.WAIT: wx.CURSOR_WAIT, cursors.RESIZE_HORIZONTAL: wx.CURSOR_SIZEWE, cursors.RESIZE_VERTICAL: wx.CURSOR_SIZENS}, cursor=cursor)) self.SetCursor(cursor) self.Refresh() def _set_capture(self, capture=True): if self.HasCapture(): self.ReleaseMouse() if capture: self.CaptureMouse() def _on_capture_lost(self, event): self._set_capture(False) def _on_mouse_button(self, event): event.Skip() self._set_capture(event.ButtonDown() or event.ButtonDClick()) (x, y) = self._mpl_coords(event) button_map = {wx.MOUSE_BTN_LEFT: MouseButton.LEFT, wx.MOUSE_BTN_MIDDLE: MouseButton.MIDDLE, wx.MOUSE_BTN_RIGHT: MouseButton.RIGHT, wx.MOUSE_BTN_AUX1: MouseButton.BACK, wx.MOUSE_BTN_AUX2: MouseButton.FORWARD} button = event.GetButton() button = button_map.get(button, button) modifiers = self._mpl_modifiers(event) if event.ButtonDown(): MouseEvent('button_press_event', self, x, y, button, modifiers=modifiers, guiEvent=event)._process() elif event.ButtonDClick(): MouseEvent('button_press_event', self, x, y, button, dblclick=True, modifiers=modifiers, guiEvent=event)._process() elif event.ButtonUp(): MouseEvent('button_release_event', self, x, y, button, modifiers=modifiers, guiEvent=event)._process() def _on_mouse_wheel(self, event): (x, y) = self._mpl_coords(event) step = event.LinesPerAction * event.WheelRotation / event.WheelDelta event.Skip() if wx.Platform == '__WXMAC__': if not hasattr(self, '_skipwheelevent'): self._skipwheelevent = True elif self._skipwheelevent: self._skipwheelevent = False return else: self._skipwheelevent = True MouseEvent('scroll_event', self, x, y, step=step, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def _on_motion(self, event): event.Skip() MouseEvent('motion_notify_event', self, *self._mpl_coords(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def _on_enter(self, event): event.Skip() LocationEvent('figure_enter_event', self, *self._mpl_coords(event), modifiers=self._mpl_modifiers(), guiEvent=event)._process() def _on_leave(self, event): event.Skip() LocationEvent('figure_leave_event', self, *self._mpl_coords(event), modifiers=self._mpl_modifiers(), guiEvent=event)._process() class FigureCanvasWx(_FigureCanvasWxBase): def draw(self, drawDC=None): _log.debug('%s - draw()', type(self)) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.renderer) self._isDrawn = True self.gui_repaint(drawDC=drawDC) def _print_image(self, filetype, filename): bitmap = wx.Bitmap(math.ceil(self.figure.bbox.width), math.ceil(self.figure.bbox.height)) self.figure.draw(RendererWx(bitmap, self.figure.dpi)) saved_obj = bitmap.ConvertToImage() if cbook.is_writable_file_like(filename) else bitmap if not saved_obj.SaveFile(filename, filetype): raise RuntimeError(f'Could not save figure to {filename}') if self._isDrawn: self.draw() if self: self.Refresh() print_bmp = functools.partialmethod(_print_image, wx.BITMAP_TYPE_BMP) print_jpeg = print_jpg = functools.partialmethod(_print_image, wx.BITMAP_TYPE_JPEG) print_pcx = functools.partialmethod(_print_image, wx.BITMAP_TYPE_PCX) print_png = functools.partialmethod(_print_image, wx.BITMAP_TYPE_PNG) print_tiff = print_tif = functools.partialmethod(_print_image, wx.BITMAP_TYPE_TIF) print_xpm = functools.partialmethod(_print_image, wx.BITMAP_TYPE_XPM) class FigureFrameWx(wx.Frame): def __init__(self, num, fig, *, canvas_class): if wx.Platform == '__WXMSW__': pos = wx.DefaultPosition else: pos = wx.Point(20, 20) super().__init__(parent=None, id=-1, pos=pos) _log.debug('%s - __init__()', type(self)) _set_frame_icon(self) self.canvas = canvas_class(self, -1, fig) manager = FigureManagerWx(self.canvas, num, self) toolbar = self.canvas.manager.toolbar if toolbar is not None: self.SetToolBar(toolbar) (w, h) = map(math.ceil, fig.bbox.size) self.canvas.SetInitialSize(self.FromDIP(wx.Size(w, h))) self.canvas.SetMinSize(self.FromDIP(wx.Size(2, 2))) self.canvas.SetFocus() self.Fit() self.Bind(wx.EVT_CLOSE, self._on_close) def _on_close(self, event): _log.debug('%s - on_close()', type(self)) CloseEvent('close_event', self.canvas)._process() self.canvas.stop_event_loop() self.canvas.manager.frame = None Gcf.destroy(self.canvas.manager) try: self.canvas.mpl_disconnect(self.canvas.toolbar._id_drag) except AttributeError: pass event.Skip() class FigureManagerWx(FigureManagerBase): def __init__(self, canvas, num, frame): _log.debug('%s - __init__()', type(self)) self.frame = self.window = frame super().__init__(canvas, num) @classmethod def create_with_canvas(cls, canvas_class, figure, num): wxapp = wx.GetApp() or _create_wxapp() frame = FigureFrameWx(num, figure, canvas_class=canvas_class) manager = figure.canvas.manager if mpl.is_interactive(): manager.frame.Show() figure.canvas.draw_idle() return manager @classmethod def start_main_loop(cls): if not wx.App.IsMainLoopRunning(): wxapp = wx.GetApp() if wxapp is not None: wxapp.MainLoop() def show(self): self.frame.Show() self.canvas.draw() if mpl.rcParams['figure.raise_window']: self.frame.Raise() def destroy(self, *args): _log.debug('%s - destroy()', type(self)) frame = self.frame if frame: wx.CallAfter(frame.Close) def full_screen_toggle(self): self.frame.ShowFullScreen(not self.frame.IsFullScreen()) def get_window_title(self): return self.window.GetTitle() def set_window_title(self, title): self.window.SetTitle(title) def resize(self, width, height): self.window.SetSize(self.window.ClientToWindowSize(wx.Size(math.ceil(width), math.ceil(height)))) def _load_bitmap(filename): return wx.Bitmap(str(cbook._get_data_path('images', filename))) def _set_frame_icon(frame): bundle = wx.IconBundle() for image in ('matplotlib.png', 'matplotlib_large.png'): icon = wx.Icon(_load_bitmap(image)) if not icon.IsOk(): return bundle.AddIcon(icon) frame.SetIcons(bundle) class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): def __init__(self, canvas, coordinates=True, *, style=wx.TB_BOTTOM): wx.ToolBar.__init__(self, canvas.GetParent(), -1, style=style) if wx.Platform == '__WXMAC__': self.SetToolBitmapSize(self.GetToolBitmapSize() * self.GetDPIScaleFactor()) self.wx_ids = {} for (text, tooltip_text, image_file, callback) in self.toolitems: if text is None: self.AddSeparator() continue self.wx_ids[text] = self.AddTool(-1, bitmap=self._icon(f'{image_file}.svg'), bmpDisabled=wx.NullBitmap, label=text, shortHelp=tooltip_text, kind=wx.ITEM_CHECK if text in ['Pan', 'Zoom'] else wx.ITEM_NORMAL).Id self.Bind(wx.EVT_TOOL, getattr(self, callback), id=self.wx_ids[text]) self._coordinates = coordinates if self._coordinates: self.AddStretchableSpace() self._label_text = wx.StaticText(self, style=wx.ALIGN_RIGHT) self.AddControl(self._label_text) self.Realize() NavigationToolbar2.__init__(self, canvas) @staticmethod def _icon(name): try: dark = wx.SystemSettings.GetAppearance().IsDark() except AttributeError: bg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) bg_lum = (0.299 * bg.red + 0.587 * bg.green + 0.114 * bg.blue) / 255 fg_lum = (0.299 * fg.red + 0.587 * fg.green + 0.114 * fg.blue) / 255 dark = fg_lum - bg_lum > 0.2 path = cbook._get_data_path('images', name) if path.suffix == '.svg': svg = path.read_bytes() if dark: svg = svg.replace(b'fill:black;', b'fill:white;') toolbarIconSize = wx.ArtProvider().GetDIPSizeHint(wx.ART_TOOLBAR) return wx.BitmapBundle.FromSVG(svg, toolbarIconSize) else: pilimg = PIL.Image.open(path) image = np.array(pilimg.convert('RGBA')) if dark: fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) black_mask = (image[..., :3] == 0).all(axis=-1) image[black_mask, :3] = (fg.Red(), fg.Green(), fg.Blue()) return wx.Bitmap.FromBufferRGBA(image.shape[1], image.shape[0], image.tobytes()) def _update_buttons_checked(self): if 'Pan' in self.wx_ids: self.ToggleTool(self.wx_ids['Pan'], self.mode.name == 'PAN') if 'Zoom' in self.wx_ids: self.ToggleTool(self.wx_ids['Zoom'], self.mode.name == 'ZOOM') def zoom(self, *args): super().zoom(*args) self._update_buttons_checked() def pan(self, *args): super().pan(*args) self._update_buttons_checked() def save_figure(self, *args): (filetypes, exts, filter_index) = self.canvas._get_imagesave_wildcards() default_file = self.canvas.get_default_filename() dialog = wx.FileDialog(self.canvas.GetParent(), 'Save to file', mpl.rcParams['savefig.directory'], default_file, filetypes, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) dialog.SetFilterIndex(filter_index) if dialog.ShowModal() == wx.ID_OK: path = pathlib.Path(dialog.GetPath()) _log.debug('%s - Save file path: %s', type(self), path) fmt = exts[dialog.GetFilterIndex()] ext = path.suffix[1:] if ext in self.canvas.get_supported_filetypes() and fmt != ext: _log.warning('extension %s did not match the selected image type %s; going with %s', ext, fmt, ext) fmt = ext if mpl.rcParams['savefig.directory']: mpl.rcParams['savefig.directory'] = str(path.parent) try: self.canvas.figure.savefig(path, format=fmt) except Exception as e: dialog = wx.MessageDialog(parent=self.canvas.GetParent(), message=str(e), caption='Matplotlib error') dialog.ShowModal() dialog.Destroy() def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height sf = 1 if wx.Platform == '__WXMSW__' else self.canvas.GetDPIScaleFactor() self.canvas._rubberband_rect = (x0 / sf, (height - y0) / sf, x1 / sf, (height - y1) / sf) self.canvas.Refresh() def remove_rubberband(self): self.canvas._rubberband_rect = None self.canvas.Refresh() def set_message(self, s): if self._coordinates: self._label_text.SetLabel(s) def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack) - 1 if 'Back' in self.wx_ids: self.EnableTool(self.wx_ids['Back'], can_backward) if 'Forward' in self.wx_ids: self.EnableTool(self.wx_ids['Forward'], can_forward) class ToolbarWx(ToolContainerBase, wx.ToolBar): _icon_extension = '.svg' def __init__(self, toolmanager, parent=None, style=wx.TB_BOTTOM): if parent is None: parent = toolmanager.canvas.GetParent() ToolContainerBase.__init__(self, toolmanager) wx.ToolBar.__init__(self, parent, -1, style=style) self._space = self.AddStretchableSpace() self._label_text = wx.StaticText(self, style=wx.ALIGN_RIGHT) self.AddControl(self._label_text) self._toolitems = {} self._groups = {} def _get_tool_pos(self, tool): (pos,) = (pos for pos in range(self.ToolsCount) if self.GetToolByPos(pos) == tool) return pos def add_toolitem(self, name, group, position, image_file, description, toggle): if group not in self._groups: self._groups[group] = self.InsertSeparator(self._get_tool_pos(self._space)) sep = self._groups[group] seps = [t for t in map(self.GetToolByPos, range(self.ToolsCount)) if t.IsSeparator() and (not t.IsStretchableSpace())] if position >= 0: start = 0 if sep == seps[0] else self._get_tool_pos(seps[seps.index(sep) - 1]) + 1 else: start = self._get_tool_pos(sep) + 1 idx = start + position if image_file: bmp = NavigationToolbar2Wx._icon(image_file) kind = wx.ITEM_NORMAL if not toggle else wx.ITEM_CHECK tool = self.InsertTool(idx, -1, name, bmp, wx.NullBitmap, kind, description or '') else: size = (self.GetTextExtent(name)[0] + 10, -1) if toggle: control = wx.ToggleButton(self, -1, name, size=size) else: control = wx.Button(self, -1, name, size=size) tool = self.InsertControl(idx, control, label=name) self.Realize() def handler(event): self.trigger_tool(name) if image_file: self.Bind(wx.EVT_TOOL, handler, tool) else: control.Bind(wx.EVT_LEFT_DOWN, handler) self._toolitems.setdefault(name, []) self._toolitems[name].append((tool, handler)) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for (tool, handler) in self._toolitems[name]: if not tool.IsControl(): self.ToggleTool(tool.Id, toggled) else: tool.GetControl().SetValue(toggled) self.Refresh() def remove_toolitem(self, name): for (tool, handler) in self._toolitems.pop(name, []): self.DeleteTool(tool.Id) def set_message(self, s): self._label_text.SetLabel(s) @backend_tools._register_tool_class(_FigureCanvasWxBase) class ConfigureSubplotsWx(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): NavigationToolbar2Wx.configure_subplots(self) @backend_tools._register_tool_class(_FigureCanvasWxBase) class SaveFigureWx(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2Wx.save_figure(self._make_classic_style_pseudo_toolbar()) @backend_tools._register_tool_class(_FigureCanvasWxBase) class RubberbandWx(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): NavigationToolbar2Wx.draw_rubberband(self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): NavigationToolbar2Wx.remove_rubberband(self._make_classic_style_pseudo_toolbar()) class _HelpDialog(wx.Dialog): _instance = None headers = [('Action', 'Shortcuts', 'Description')] widths = [100, 140, 300] def __init__(self, parent, help_entries): super().__init__(parent, title='Help', style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) sizer = wx.BoxSizer(wx.VERTICAL) grid_sizer = wx.FlexGridSizer(0, 3, 8, 6) bold = self.GetFont().MakeBold() for (r, row) in enumerate(self.headers + help_entries): for (col, width) in zip(row, self.widths): label = wx.StaticText(self, label=col) if r == 0: label.SetFont(bold) label.Wrap(width) grid_sizer.Add(label, 0, 0, 0) sizer.Add(grid_sizer, 0, wx.ALL, 6) ok = wx.Button(self, wx.ID_OK) sizer.Add(ok, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 8) self.SetSizer(sizer) sizer.Fit(self) self.Layout() self.Bind(wx.EVT_CLOSE, self._on_close) ok.Bind(wx.EVT_BUTTON, self._on_close) def _on_close(self, event): _HelpDialog._instance = None self.DestroyLater() event.Skip() @classmethod def show(cls, parent, help_entries): if cls._instance: cls._instance.Raise() return cls._instance = cls(parent, help_entries) cls._instance.Show() @backend_tools._register_tool_class(_FigureCanvasWxBase) class HelpWx(backend_tools.ToolHelpBase): def trigger(self, *args): _HelpDialog.show(self.figure.canvas.GetTopLevelParent(), self._get_help_entries()) @backend_tools._register_tool_class(_FigureCanvasWxBase) class ToolCopyToClipboardWx(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): if not self.canvas._isDrawn: self.canvas.draw() if not self.canvas.bitmap.IsOk() or not wx.TheClipboard.Open(): return try: wx.TheClipboard.SetData(wx.BitmapDataObject(self.canvas.bitmap)) finally: wx.TheClipboard.Close() FigureManagerWx._toolbar2_class = NavigationToolbar2Wx FigureManagerWx._toolmanager_toolbar_class = ToolbarWx @_Backend.export class _BackendWx(_Backend): FigureCanvas = FigureCanvasWx FigureManager = FigureManagerWx mainloop = FigureManagerWx.start_main_loop # File: matplotlib-main/lib/matplotlib/backends/backend_wxagg.py import wx from .backend_agg import FigureCanvasAgg from .backend_wx import _BackendWx, _FigureCanvasWxBase from .backend_wx import NavigationToolbar2Wx as NavigationToolbar2WxAgg class FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase): def draw(self, drawDC=None): FigureCanvasAgg.draw(self) self.bitmap = self._create_bitmap() self._isDrawn = True self.gui_repaint(drawDC=drawDC) def blit(self, bbox=None): bitmap = self._create_bitmap() if bbox is None: self.bitmap = bitmap else: srcDC = wx.MemoryDC(bitmap) destDC = wx.MemoryDC(self.bitmap) x = int(bbox.x0) y = int(self.bitmap.GetHeight() - bbox.y1) destDC.Blit(x, y, int(bbox.width), int(bbox.height), srcDC, x, y) destDC.SelectObject(wx.NullBitmap) srcDC.SelectObject(wx.NullBitmap) self.gui_repaint() def _create_bitmap(self): rgba = self.get_renderer().buffer_rgba() (h, w, _) = rgba.shape bitmap = wx.Bitmap.FromBufferRGBA(w, h, rgba) bitmap.SetScaleFactor(self.GetDPIScaleFactor()) return bitmap @_BackendWx.export class _BackendWxAgg(_BackendWx): FigureCanvas = FigureCanvasWxAgg # File: matplotlib-main/lib/matplotlib/backends/backend_wxcairo.py import wx.lib.wxcairo as wxcairo from .backend_cairo import cairo, FigureCanvasCairo from .backend_wx import _BackendWx, _FigureCanvasWxBase from .backend_wx import NavigationToolbar2Wx as NavigationToolbar2WxCairo class FigureCanvasWxCairo(FigureCanvasCairo, _FigureCanvasWxBase): def draw(self, drawDC=None): size = self.figure.bbox.size.astype(int) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size) self._renderer.set_context(cairo.Context(surface)) self._renderer.dpi = self.figure.dpi self.figure.draw(self._renderer) self.bitmap = wxcairo.BitmapFromImageSurface(surface) self._isDrawn = True self.gui_repaint(drawDC=drawDC) @_BackendWx.export class _BackendWxCairo(_BackendWx): FigureCanvas = FigureCanvasWxCairo # File: matplotlib-main/lib/matplotlib/backends/qt_compat.py """""" import operator import os import platform import sys from packaging.version import parse as parse_version import matplotlib as mpl from . import _QT_FORCE_QT5_BINDING QT_API_PYQT6 = 'PyQt6' QT_API_PYSIDE6 = 'PySide6' QT_API_PYQT5 = 'PyQt5' QT_API_PYSIDE2 = 'PySide2' QT_API_ENV = os.environ.get('QT_API') if QT_API_ENV is not None: QT_API_ENV = QT_API_ENV.lower() _ETS = {'pyqt6': QT_API_PYQT6, 'pyside6': QT_API_PYSIDE6, 'pyqt5': QT_API_PYQT5, 'pyside2': QT_API_PYSIDE2} if sys.modules.get('PyQt6.QtCore'): QT_API = QT_API_PYQT6 elif sys.modules.get('PySide6.QtCore'): QT_API = QT_API_PYSIDE6 elif sys.modules.get('PyQt5.QtCore'): QT_API = QT_API_PYQT5 elif sys.modules.get('PySide2.QtCore'): QT_API = QT_API_PYSIDE2 elif (mpl.rcParams._get_backend_or_none() or '').lower().startswith('qt5'): if QT_API_ENV in ['pyqt5', 'pyside2']: QT_API = _ETS[QT_API_ENV] else: _QT_FORCE_QT5_BINDING = True QT_API = None elif QT_API_ENV is None: QT_API = None elif QT_API_ENV in _ETS: QT_API = _ETS[QT_API_ENV] else: raise RuntimeError('The environment variable QT_API has the unrecognized value {!r}; valid values are {}'.format(QT_API_ENV, ', '.join(_ETS))) def _setup_pyqt5plus(): global QtCore, QtGui, QtWidgets, __version__ global _isdeleted, _to_int if QT_API == QT_API_PYQT6: from PyQt6 import QtCore, QtGui, QtWidgets, sip __version__ = QtCore.PYQT_VERSION_STR QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot QtCore.Property = QtCore.pyqtProperty _isdeleted = sip.isdeleted _to_int = operator.attrgetter('value') elif QT_API == QT_API_PYSIDE6: from PySide6 import QtCore, QtGui, QtWidgets, __version__ import shiboken6 def _isdeleted(obj): return not shiboken6.isValid(obj) if parse_version(__version__) >= parse_version('6.4'): _to_int = operator.attrgetter('value') else: _to_int = int elif QT_API == QT_API_PYQT5: from PyQt5 import QtCore, QtGui, QtWidgets import sip __version__ = QtCore.PYQT_VERSION_STR QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot QtCore.Property = QtCore.pyqtProperty _isdeleted = sip.isdeleted _to_int = int elif QT_API == QT_API_PYSIDE2: from PySide2 import QtCore, QtGui, QtWidgets, __version__ try: from PySide2 import shiboken2 except ImportError: import shiboken2 def _isdeleted(obj): return not shiboken2.isValid(obj) _to_int = int else: raise AssertionError(f'Unexpected QT_API: {QT_API}') if QT_API in [QT_API_PYQT6, QT_API_PYQT5, QT_API_PYSIDE6, QT_API_PYSIDE2]: _setup_pyqt5plus() elif QT_API is None: if _QT_FORCE_QT5_BINDING: _candidates = [(_setup_pyqt5plus, QT_API_PYQT5), (_setup_pyqt5plus, QT_API_PYSIDE2)] else: _candidates = [(_setup_pyqt5plus, QT_API_PYQT6), (_setup_pyqt5plus, QT_API_PYSIDE6), (_setup_pyqt5plus, QT_API_PYQT5), (_setup_pyqt5plus, QT_API_PYSIDE2)] for (_setup, QT_API) in _candidates: try: _setup() except ImportError: continue break else: raise ImportError('Failed to import any of the following Qt binding modules: {}'.format(', '.join([QT_API for (_, QT_API) in _candidates]))) else: raise AssertionError(f'Unexpected QT_API: {QT_API}') _version_info = tuple(QtCore.QLibraryInfo.version().segments()) if _version_info < (5, 12): raise ImportError(f'The Qt version imported is {QtCore.QLibraryInfo.version().toString()} but Matplotlib requires Qt>=5.12') if sys.platform == 'darwin' and parse_version(platform.mac_ver()[0]) >= parse_version('10.16') and (_version_info < (5, 15, 2)): os.environ.setdefault('QT_MAC_WANTS_LAYER', '1') def _exec(obj): obj.exec() if hasattr(obj, 'exec') else obj.exec_() # File: matplotlib-main/lib/matplotlib/backends/qt_editor/_formlayout.py """""" __version__ = '1.0.10' __license__ = __doc__ from ast import literal_eval import copy import datetime import logging from numbers import Integral, Real from matplotlib import _api, colors as mcolors from matplotlib.backends.qt_compat import _to_int, QtGui, QtWidgets, QtCore _log = logging.getLogger(__name__) BLACKLIST = {'title', 'label'} class ColorButton(QtWidgets.QPushButton): colorChanged = QtCore.Signal(QtGui.QColor) def __init__(self, parent=None): super().__init__(parent) self.setFixedSize(20, 20) self.setIconSize(QtCore.QSize(12, 12)) self.clicked.connect(self.choose_color) self._color = QtGui.QColor() def choose_color(self): color = QtWidgets.QColorDialog.getColor(self._color, self.parentWidget(), '', QtWidgets.QColorDialog.ColorDialogOption.ShowAlphaChannel) if color.isValid(): self.set_color(color) def get_color(self): return self._color @QtCore.Slot(QtGui.QColor) def set_color(self, color): if color != self._color: self._color = color self.colorChanged.emit(self._color) pixmap = QtGui.QPixmap(self.iconSize()) pixmap.fill(color) self.setIcon(QtGui.QIcon(pixmap)) color = QtCore.Property(QtGui.QColor, get_color, set_color) def to_qcolor(color): qcolor = QtGui.QColor() try: rgba = mcolors.to_rgba(color) except ValueError: _api.warn_external(f'Ignoring invalid color {color!r}') return qcolor qcolor.setRgbF(*rgba) return qcolor class ColorLayout(QtWidgets.QHBoxLayout): def __init__(self, color, parent=None): super().__init__() assert isinstance(color, QtGui.QColor) self.lineedit = QtWidgets.QLineEdit(mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent) self.lineedit.editingFinished.connect(self.update_color) self.addWidget(self.lineedit) self.colorbtn = ColorButton(parent) self.colorbtn.color = color self.colorbtn.colorChanged.connect(self.update_text) self.addWidget(self.colorbtn) def update_color(self): color = self.text() qcolor = to_qcolor(color) self.colorbtn.color = qcolor def update_text(self, color): self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) def text(self): return self.lineedit.text() def font_is_installed(font): return [fam for fam in QtGui.QFontDatabase().families() if str(fam) == font] def tuple_to_qfont(tup): if not (isinstance(tup, tuple) and len(tup) == 4 and font_is_installed(tup[0]) and isinstance(tup[1], Integral) and isinstance(tup[2], bool) and isinstance(tup[3], bool)): return None font = QtGui.QFont() (family, size, italic, bold) = tup font.setFamily(family) font.setPointSize(size) font.setItalic(italic) font.setBold(bold) return font def qfont_to_tuple(font): return (str(font.family()), int(font.pointSize()), font.italic(), font.bold()) class FontLayout(QtWidgets.QGridLayout): def __init__(self, value, parent=None): super().__init__() font = tuple_to_qfont(value) assert font is not None self.family = QtWidgets.QFontComboBox(parent) self.family.setCurrentFont(font) self.addWidget(self.family, 0, 0, 1, -1) self.size = QtWidgets.QComboBox(parent) self.size.setEditable(True) sizelist = [*range(6, 12), *range(12, 30, 2), 36, 48, 72] size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.size.setCurrentIndex(sizelist.index(size)) self.addWidget(self.size, 1, 0) self.italic = QtWidgets.QCheckBox(self.tr('Italic'), parent) self.italic.setChecked(font.italic()) self.addWidget(self.italic, 1, 1) self.bold = QtWidgets.QCheckBox(self.tr('Bold'), parent) self.bold.setChecked(font.bold()) self.addWidget(self.bold, 1, 2) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font) def is_edit_valid(edit): text = edit.text() state = edit.validator().validate(text, 0)[0] return state == QtGui.QDoubleValidator.State.Acceptable class FormWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, data, comment='', with_margin=False, parent=None): super().__init__(parent) self.data = copy.deepcopy(data) self.widgets = [] self.formlayout = QtWidgets.QFormLayout(self) if not with_margin: self.formlayout.setContentsMargins(0, 0, 0, 0) if comment: self.formlayout.addRow(QtWidgets.QLabel(comment)) self.formlayout.addRow(QtWidgets.QLabel(' ')) def get_dialog(self): dialog = self.parent() while not isinstance(dialog, QtWidgets.QDialog): dialog = dialog.parent() return dialog def setup(self): for (label, value) in self.data: if label is None and value is None: self.formlayout.addRow(QtWidgets.QLabel(' '), QtWidgets.QLabel(' ')) self.widgets.append(None) continue elif label is None: self.formlayout.addRow(QtWidgets.QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif label.lower() not in BLACKLIST and mcolors.is_color_like(value): field = ColorLayout(to_qcolor(value), self) elif isinstance(value, str): field = QtWidgets.QLineEdit(value, self) elif isinstance(value, (list, tuple)): if isinstance(value, tuple): value = list(value) selindex = value.pop(0) field = QtWidgets.QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [key for (key, _val) in value] value = [val for (_key, val) in value] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, Integral): _log.warning("index '%s' is invalid (label: %s, value: %s)", selindex, label, value) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QtWidgets.QCheckBox(self) field.setChecked(value) elif isinstance(value, Integral): field = QtWidgets.QSpinBox(self) field.setRange(-10 ** 9, 10 ** 9) field.setValue(value) elif isinstance(value, Real): field = QtWidgets.QLineEdit(repr(value), self) field.setCursorPosition(0) field.setValidator(QtGui.QDoubleValidator(field)) field.validator().setLocale(QtCore.QLocale('C')) dialog = self.get_dialog() dialog.register_float_field(field) field.textChanged.connect(lambda text: dialog.update_buttons()) elif isinstance(value, datetime.datetime): field = QtWidgets.QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QtWidgets.QDateEdit(self) field.setDate(value) else: field = QtWidgets.QLineEdit(repr(value), self) self.formlayout.addRow(label, field) self.widgets.append(field) def get(self): valuelist = [] for (index, (label, value)) in enumerate(self.data): field = self.widgets[index] if label is None: continue elif tuple_to_qfont(value) is not None: value = field.get_font() elif isinstance(value, str) or mcolors.is_color_like(value): value = str(field.text()) elif isinstance(value, (list, tuple)): index = int(field.currentIndex()) if isinstance(value[0], (list, tuple)): value = value[index][0] else: value = value[index] elif isinstance(value, bool): value = field.isChecked() elif isinstance(value, Integral): value = int(field.value()) elif isinstance(value, Real): value = float(str(field.text())) elif isinstance(value, datetime.datetime): datetime_ = field.dateTime() if hasattr(datetime_, 'toPyDateTime'): value = datetime_.toPyDateTime() else: value = datetime_.toPython() elif isinstance(value, datetime.date): date_ = field.date() if hasattr(date_, 'toPyDate'): value = date_.toPyDate() else: value = date_.toPython() else: value = literal_eval(str(field.text())) valuelist.append(value) return valuelist class FormComboWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, datalist, comment='', parent=None): super().__init__(parent) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.combobox = QtWidgets.QComboBox() layout.addWidget(self.combobox) self.stackwidget = QtWidgets.QStackedWidget(self) layout.addWidget(self.stackwidget) self.combobox.currentIndexChanged.connect(self.stackwidget.setCurrentIndex) self.widgetlist = [] for (data, title, comment) in datalist: self.combobox.addItem(title) widget = FormWidget(data, comment=comment, parent=self) self.stackwidget.addWidget(widget) self.widgetlist.append(widget) def setup(self): for widget in self.widgetlist: widget.setup() def get(self): return [widget.get() for widget in self.widgetlist] class FormTabWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, datalist, comment='', parent=None): super().__init__(parent) layout = QtWidgets.QVBoxLayout() self.tabwidget = QtWidgets.QTabWidget() layout.addWidget(self.tabwidget) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.widgetlist = [] for (data, title, comment) in datalist: if len(data[0]) == 3: widget = FormComboWidget(data, comment=comment, parent=self) else: widget = FormWidget(data, with_margin=True, comment=comment, parent=self) index = self.tabwidget.addTab(widget, title) self.tabwidget.setTabToolTip(index, comment) self.widgetlist.append(widget) def setup(self): for widget in self.widgetlist: widget.setup() def get(self): return [widget.get() for widget in self.widgetlist] class FormDialog(QtWidgets.QDialog): def __init__(self, data, title='', comment='', icon=None, parent=None, apply=None): super().__init__(parent) self.apply_callback = apply if isinstance(data[0][0], (list, tuple)): self.formwidget = FormTabWidget(data, comment=comment, parent=self) elif len(data[0]) == 3: self.formwidget = FormComboWidget(data, comment=comment, parent=self) else: self.formwidget = FormWidget(data, comment=comment, parent=self) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.formwidget) self.float_fields = [] self.formwidget.setup() self.bbox = bbox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton(_to_int(QtWidgets.QDialogButtonBox.StandardButton.Ok) | _to_int(QtWidgets.QDialogButtonBox.StandardButton.Cancel))) self.formwidget.update_buttons.connect(self.update_buttons) if self.apply_callback is not None: apply_btn = bbox.addButton(QtWidgets.QDialogButtonBox.StandardButton.Apply) apply_btn.clicked.connect(self.apply) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) layout.addWidget(bbox) self.setLayout(layout) self.setWindowTitle(title) if not isinstance(icon, QtGui.QIcon): icon = QtWidgets.QWidget().style().standardIcon(QtWidgets.QStyle.SP_MessageBoxQuestion) self.setWindowIcon(icon) def register_float_field(self, field): self.float_fields.append(field) def update_buttons(self): valid = True for field in self.float_fields: if not is_edit_valid(field): valid = False for btn_type in ['Ok', 'Apply']: btn = self.bbox.button(getattr(QtWidgets.QDialogButtonBox.StandardButton, btn_type)) if btn is not None: btn.setEnabled(valid) def accept(self): self.data = self.formwidget.get() self.apply_callback(self.data) super().accept() def reject(self): self.data = None super().reject() def apply(self): self.apply_callback(self.formwidget.get()) def get(self): return self.data def fedit(data, title='', comment='', icon=None, parent=None, apply=None): if QtWidgets.QApplication.startingUp(): _app = QtWidgets.QApplication([]) dialog = FormDialog(data, title, comment, icon, parent, apply) if parent is not None: if hasattr(parent, '_fedit_dialog'): parent._fedit_dialog.close() parent._fedit_dialog = dialog dialog.show() if __name__ == '__main__': _app = QtWidgets.QApplication([]) def create_datalist_example(): return [('str', 'this is a string'), ('list', [0, '1', '3', '4']), ('list2', ['--', ('none', 'None'), ('--', 'Dashed'), ('-.', 'DashDot'), ('-', 'Solid'), ('steps', 'Steps'), (':', 'Dotted')]), ('float', 1.2), (None, 'Other:'), ('int', 12), ('font', ('Arial', 10, False, True)), ('color', '#123409'), ('bool', True), ('date', datetime.date(2010, 10, 10)), ('datetime', datetime.datetime(2010, 10, 10))] def create_datagroup_example(): datalist = create_datalist_example() return ((datalist, 'Category 1', 'Category 1 comment'), (datalist, 'Category 2', 'Category 2 comment'), (datalist, 'Category 3', 'Category 3 comment')) datalist = create_datalist_example() def apply_test(data): print('data:', data) fedit(datalist, title='Example', comment='This is just an example.', apply=apply_test) _app.exec() datagroup = create_datagroup_example() fedit(datagroup, 'Global title', apply=apply_test) _app.exec() datalist = create_datalist_example() datagroup = create_datagroup_example() fedit(((datagroup, 'Title 1', 'Tab 1 comment'), (datalist, 'Title 2', 'Tab 2 comment'), (datalist, 'Title 3', 'Tab 3 comment')), 'Global title', apply=apply_test) _app.exec() # File: matplotlib-main/lib/matplotlib/backends/qt_editor/figureoptions.py """""" from itertools import chain from matplotlib import cbook, cm, colors as mcolors, markers, image as mimage from matplotlib.backends.qt_compat import QtGui from matplotlib.backends.qt_editor import _formlayout from matplotlib.dates import DateConverter, num2date LINESTYLES = {'-': 'Solid', '--': 'Dashed', '-.': 'DashDot', ':': 'Dotted', 'None': 'None'} DRAWSTYLES = {'default': 'Default', 'steps-pre': 'Steps (Pre)', 'steps': 'Steps (Pre)', 'steps-mid': 'Steps (Mid)', 'steps-post': 'Steps (Post)'} MARKERS = markers.MarkerStyle.markers def figure_edit(axes, parent=None): sep = (None, None) def convert_limits(lim, converter): if isinstance(converter, DateConverter): return map(num2date, lim) return map(float, lim) axis_map = axes._axis_map axis_limits = {name: tuple(convert_limits(getattr(axes, f'get_{name}lim')(), axis.converter)) for (name, axis) in axis_map.items()} general = [('Title', axes.get_title()), sep, *chain.from_iterable([((None, f'{name.title()}-Axis'), ('Min', axis_limits[name][0]), ('Max', axis_limits[name][1]), ('Label', axis.get_label().get_text()), ('Scale', [axis.get_scale(), 'linear', 'log', 'symlog', 'logit']), sep) for (name, axis) in axis_map.items()]), ('(Re-)Generate automatic legend', False)] axis_converter = {name: axis.converter for (name, axis) in axis_map.items()} axis_units = {name: axis.get_units() for (name, axis) in axis_map.items()} labeled_lines = [] for line in axes.get_lines(): label = line.get_label() if label == '_nolegend_': continue labeled_lines.append((label, line)) curves = [] def prepare_data(d, init): if init not in d: d = {**d, init: str(init)} name2short = {name: short for (short, name) in d.items()} short2name = {short: name for (name, short) in name2short.items()} canonical_init = name2short[d[init]] return [canonical_init] + sorted(short2name.items(), key=lambda short_and_name: short_and_name[1]) for (label, line) in labeled_lines: color = mcolors.to_hex(mcolors.to_rgba(line.get_color(), line.get_alpha()), keep_alpha=True) ec = mcolors.to_hex(mcolors.to_rgba(line.get_markeredgecolor(), line.get_alpha()), keep_alpha=True) fc = mcolors.to_hex(mcolors.to_rgba(line.get_markerfacecolor(), line.get_alpha()), keep_alpha=True) curvedata = [('Label', label), sep, (None, 'Line'), ('Line style', prepare_data(LINESTYLES, line.get_linestyle())), ('Draw style', prepare_data(DRAWSTYLES, line.get_drawstyle())), ('Width', line.get_linewidth()), ('Color (RGBA)', color), sep, (None, 'Marker'), ('Style', prepare_data(MARKERS, line.get_marker())), ('Size', line.get_markersize()), ('Face color (RGBA)', fc), ('Edge color (RGBA)', ec)] curves.append([curvedata, label, '']) has_curve = bool(curves) labeled_mappables = [] for mappable in [*axes.images, *axes.collections]: label = mappable.get_label() if label == '_nolegend_' or mappable.get_array() is None: continue labeled_mappables.append((label, mappable)) mappables = [] cmaps = [(cmap, name) for (name, cmap) in sorted(cm._colormaps.items())] for (label, mappable) in labeled_mappables: cmap = mappable.get_cmap() if cmap not in cm._colormaps.values(): cmaps = [(cmap, cmap.name), *cmaps] (low, high) = mappable.get_clim() mappabledata = [('Label', label), ('Colormap', [cmap.name] + cmaps), ('Min. value', low), ('Max. value', high)] if hasattr(mappable, 'get_interpolation'): interpolations = [(name, name) for name in sorted(mimage.interpolations_names)] mappabledata.append(('Interpolation', [mappable.get_interpolation(), *interpolations])) interpolation_stages = ['data', 'rgba', 'auto'] mappabledata.append(('Interpolation stage', [mappable.get_interpolation_stage(), *interpolation_stages])) mappables.append([mappabledata, label, '']) has_sm = bool(mappables) datalist = [(general, 'Axes', '')] if curves: datalist.append((curves, 'Curves', '')) if mappables: datalist.append((mappables, 'Images, etc.', '')) def apply_callback(data): orig_limits = {name: getattr(axes, f'get_{name}lim')() for name in axis_map} general = data.pop(0) curves = data.pop(0) if has_curve else [] mappables = data.pop(0) if has_sm else [] if data: raise ValueError('Unexpected field') title = general.pop(0) axes.set_title(title) generate_legend = general.pop() for (i, (name, axis)) in enumerate(axis_map.items()): axis_min = general[4 * i] axis_max = general[4 * i + 1] axis_label = general[4 * i + 2] axis_scale = general[4 * i + 3] if axis.get_scale() != axis_scale: getattr(axes, f'set_{name}scale')(axis_scale) axis._set_lim(axis_min, axis_max, auto=False) axis.set_label_text(axis_label) axis.converter = axis_converter[name] axis.set_units(axis_units[name]) for (index, curve) in enumerate(curves): line = labeled_lines[index][1] (label, linestyle, drawstyle, linewidth, color, marker, markersize, markerfacecolor, markeredgecolor) = curve line.set_label(label) line.set_linestyle(linestyle) line.set_drawstyle(drawstyle) line.set_linewidth(linewidth) rgba = mcolors.to_rgba(color) line.set_alpha(None) line.set_color(rgba) if marker != 'none': line.set_marker(marker) line.set_markersize(markersize) line.set_markerfacecolor(markerfacecolor) line.set_markeredgecolor(markeredgecolor) for (index, mappable_settings) in enumerate(mappables): mappable = labeled_mappables[index][1] if len(mappable_settings) == 6: (label, cmap, low, high, interpolation, interpolation_stage) = mappable_settings mappable.set_interpolation(interpolation) mappable.set_interpolation_stage(interpolation_stage) elif len(mappable_settings) == 4: (label, cmap, low, high) = mappable_settings mappable.set_label(label) mappable.set_cmap(cmap) mappable.set_clim(*sorted([low, high])) if generate_legend: draggable = None ncols = 1 if axes.legend_ is not None: old_legend = axes.get_legend() draggable = old_legend._draggable is not None ncols = old_legend._ncols new_legend = axes.legend(ncols=ncols) if new_legend: new_legend.set_draggable(draggable) figure = axes.get_figure() figure.canvas.draw() for name in axis_map: if getattr(axes, f'get_{name}lim')() != orig_limits[name]: figure.canvas.toolbar.push_current() break _formlayout.fedit(datalist, title='Figure options', parent=parent, icon=QtGui.QIcon(str(cbook._get_data_path('images', 'qt4_editor_options.svg'))), apply=apply_callback) # File: matplotlib-main/lib/matplotlib/backends/registry.py from enum import Enum import importlib class BackendFilter(Enum): INTERACTIVE = 0 NON_INTERACTIVE = 1 class BackendRegistry: _BUILTIN_BACKEND_TO_GUI_FRAMEWORK = {'gtk3agg': 'gtk3', 'gtk3cairo': 'gtk3', 'gtk4agg': 'gtk4', 'gtk4cairo': 'gtk4', 'macosx': 'macosx', 'nbagg': 'nbagg', 'notebook': 'nbagg', 'qtagg': 'qt', 'qtcairo': 'qt', 'qt5agg': 'qt5', 'qt5cairo': 'qt5', 'tkagg': 'tk', 'tkcairo': 'tk', 'webagg': 'webagg', 'wx': 'wx', 'wxagg': 'wx', 'wxcairo': 'wx', 'agg': 'headless', 'cairo': 'headless', 'pdf': 'headless', 'pgf': 'headless', 'ps': 'headless', 'svg': 'headless', 'template': 'headless'} _GUI_FRAMEWORK_TO_BACKEND = {'gtk3': 'gtk3agg', 'gtk4': 'gtk4agg', 'headless': 'agg', 'macosx': 'macosx', 'qt': 'qtagg', 'qt5': 'qt5agg', 'qt6': 'qtagg', 'tk': 'tkagg', 'wx': 'wxagg'} def __init__(self): self._loaded_entry_points = False self._backend_to_gui_framework = {} self._name_to_module = {'notebook': 'nbagg'} def _backend_module_name(self, backend): if backend.startswith('module://'): return backend[9:] backend = backend.lower() backend = self._name_to_module.get(backend, backend) return backend[9:] if backend.startswith('module://') else f'matplotlib.backends.backend_{backend}' def _clear(self): self.__init__() def _ensure_entry_points_loaded(self): if not self._loaded_entry_points: entries = self._read_entry_points() self._validate_and_store_entry_points(entries) self._loaded_entry_points = True def _get_gui_framework_by_loading(self, backend): module = self.load_backend_module(backend) canvas_class = module.FigureCanvas return canvas_class.required_interactive_framework or 'headless' def _read_entry_points(self): import importlib.metadata as im entry_points = im.entry_points(group='matplotlib.backend') entries = [(entry.name, entry.value) for entry in entry_points] def backward_compatible_entry_points(entries, module_name, threshold_version, names, target): from matplotlib import _parse_to_version_info try: module_version = im.version(module_name) if _parse_to_version_info(module_version) < threshold_version: for name in names: entries.append((name, target)) except im.PackageNotFoundError: pass names = [entry[0] for entry in entries] if 'inline' not in names: backward_compatible_entry_points(entries, 'matplotlib_inline', (0, 1, 7), ['inline'], 'matplotlib_inline.backend_inline') if 'ipympl' not in names: backward_compatible_entry_points(entries, 'ipympl', (0, 9, 4), ['ipympl', 'widget'], 'ipympl.backend_nbagg') return entries def _validate_and_store_entry_points(self, entries): for (name, module) in set(entries): name = name.lower() if name.startswith('module://'): raise RuntimeError(f"Entry point name '{name}' cannot start with 'module://'") if name in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK: raise RuntimeError(f"Entry point name '{name}' is a built-in backend") if name in self._backend_to_gui_framework: raise RuntimeError(f"Entry point name '{name}' duplicated") self._name_to_module[name] = 'module://' + module self._backend_to_gui_framework[name] = 'unknown' def backend_for_gui_framework(self, framework): return self._GUI_FRAMEWORK_TO_BACKEND.get(framework.lower()) def is_valid_backend(self, backend): if not backend.startswith('module://'): backend = backend.lower() backwards_compat = {'module://ipympl.backend_nbagg': 'widget', 'module://matplotlib_inline.backend_inline': 'inline'} backend = backwards_compat.get(backend, backend) if backend in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK or backend in self._backend_to_gui_framework: return True if backend.startswith('module://'): self._backend_to_gui_framework[backend] = 'unknown' return True self._ensure_entry_points_loaded() if backend in self._backend_to_gui_framework: return True return False def list_all(self): self._ensure_entry_points_loaded() return [*self.list_builtin(), *self._backend_to_gui_framework] def list_builtin(self, filter_=None): if filter_ == BackendFilter.INTERACTIVE: return [k for (k, v) in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() if v != 'headless'] elif filter_ == BackendFilter.NON_INTERACTIVE: return [k for (k, v) in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items() if v == 'headless'] return [*self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK] def list_gui_frameworks(self): return [k for k in self._GUI_FRAMEWORK_TO_BACKEND if k != 'headless'] def load_backend_module(self, backend): module_name = self._backend_module_name(backend) return importlib.import_module(module_name) def resolve_backend(self, backend): if isinstance(backend, str): if not backend.startswith('module://'): backend = backend.lower() else: from matplotlib import get_backend backend = get_backend() gui = self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.get(backend) or self._backend_to_gui_framework.get(backend) if gui is None and isinstance(backend, str) and backend.startswith('module://'): gui = 'unknown' if gui is None and (not self._loaded_entry_points): self._ensure_entry_points_loaded() gui = self._backend_to_gui_framework.get(backend) if gui == 'unknown': gui = self._get_gui_framework_by_loading(backend) self._backend_to_gui_framework[backend] = gui if gui is None: raise RuntimeError(f"'{backend}' is not a recognised backend name") return (backend, gui if gui != 'headless' else None) def resolve_gui_or_backend(self, gui_or_backend): if not gui_or_backend.startswith('module://'): gui_or_backend = gui_or_backend.lower() backend = self.backend_for_gui_framework(gui_or_backend) if backend is not None: return (backend, gui_or_backend if gui_or_backend != 'headless' else None) try: return self.resolve_backend(gui_or_backend) except Exception: raise RuntimeError(f"'{gui_or_backend} is not a recognised GUI loop or backend name") backend_registry = BackendRegistry() # File: matplotlib-main/lib/matplotlib/bezier.py """""" from functools import lru_cache import math import warnings import numpy as np from matplotlib import _api @np.vectorize @lru_cache(maxsize=128) def _comb(n, k): if k > n: return 0 k = min(k, n - k) i = np.arange(1, k + 1) return np.prod((n + 1 - i) / i).astype(int) class NonIntersectingPathException(ValueError): pass def get_intersection(cx1, cy1, cos_t1, sin_t1, cx2, cy2, cos_t2, sin_t2): line1_rhs = sin_t1 * cx1 - cos_t1 * cy1 line2_rhs = sin_t2 * cx2 - cos_t2 * cy2 (a, b) = (sin_t1, -cos_t1) (c, d) = (sin_t2, -cos_t2) ad_bc = a * d - b * c if abs(ad_bc) < 1e-12: raise ValueError('Given lines do not intersect. Please verify that the angles are not equal or differ by 180 degrees.') (a_, b_) = (d, -b) (c_, d_) = (-c, a) (a_, b_, c_, d_) = (k / ad_bc for k in [a_, b_, c_, d_]) x = a_ * line1_rhs + b_ * line2_rhs y = c_ * line1_rhs + d_ * line2_rhs return (x, y) def get_normal_points(cx, cy, cos_t, sin_t, length): if length == 0.0: return (cx, cy, cx, cy) (cos_t1, sin_t1) = (sin_t, -cos_t) (cos_t2, sin_t2) = (-sin_t, cos_t) (x1, y1) = (length * cos_t1 + cx, length * sin_t1 + cy) (x2, y2) = (length * cos_t2 + cx, length * sin_t2 + cy) return (x1, y1, x2, y2) def _de_casteljau1(beta, t): next_beta = beta[:-1] * (1 - t) + beta[1:] * t return next_beta def split_de_casteljau(beta, t): beta = np.asarray(beta) beta_list = [beta] while True: beta = _de_casteljau1(beta, t) beta_list.append(beta) if len(beta) == 1: break left_beta = [beta[0] for beta in beta_list] right_beta = [beta[-1] for beta in reversed(beta_list)] return (left_beta, right_beta) def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, inside_closedpath, t0=0.0, t1=1.0, tolerance=0.01): start = bezier_point_at_t(t0) end = bezier_point_at_t(t1) start_inside = inside_closedpath(start) end_inside = inside_closedpath(end) if start_inside == end_inside and start != end: raise NonIntersectingPathException('Both points are on the same side of the closed path') while True: if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance: return (t0, t1) middle_t = 0.5 * (t0 + t1) middle = bezier_point_at_t(middle_t) middle_inside = inside_closedpath(middle) if start_inside ^ middle_inside: t1 = middle_t if end == middle: return (t0, t1) end = middle else: t0 = middle_t if start == middle: return (t0, t1) start = middle start_inside = middle_inside class BezierSegment: def __init__(self, control_points): self._cpoints = np.asarray(control_points) (self._N, self._d) = self._cpoints.shape self._orders = np.arange(self._N) coeff = [math.factorial(self._N - 1) // (math.factorial(i) * math.factorial(self._N - 1 - i)) for i in range(self._N)] self._px = (self._cpoints.T * coeff).T def __call__(self, t): t = np.asarray(t) return np.power.outer(1 - t, self._orders[::-1]) * np.power.outer(t, self._orders) @ self._px def point_at_t(self, t): return tuple(self(t)) @property def control_points(self): return self._cpoints @property def dimension(self): return self._d @property def degree(self): return self._N - 1 @property def polynomial_coefficients(self): n = self.degree if n > 10: warnings.warn('Polynomial coefficients formula unstable for high order Bezier curves!', RuntimeWarning) P = self.control_points j = np.arange(n + 1)[:, None] i = np.arange(n + 1)[None, :] prefactor = (-1) ** (i + j) * _comb(j, i) return _comb(n, j) * prefactor @ P def axis_aligned_extrema(self): n = self.degree if n <= 1: return (np.array([]), np.array([])) Cj = self.polynomial_coefficients dCj = np.arange(1, n + 1)[:, None] * Cj[1:] dims = [] roots = [] for (i, pi) in enumerate(dCj.T): r = np.roots(pi[::-1]) roots.append(r) dims.append(np.full_like(r, i)) roots = np.concatenate(roots) dims = np.concatenate(dims) in_range = np.isreal(roots) & (roots >= 0) & (roots <= 1) return (dims[in_range], np.real(roots)[in_range]) def split_bezier_intersecting_with_closedpath(bezier, inside_closedpath, tolerance=0.01): bz = BezierSegment(bezier) bezier_point_at_t = bz.point_at_t (t0, t1) = find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, inside_closedpath, tolerance=tolerance) (_left, _right) = split_de_casteljau(bezier, (t0 + t1) / 2.0) return (_left, _right) def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False): from .path import Path path_iter = path.iter_segments() (ctl_points, command) = next(path_iter) begin_inside = inside(ctl_points[-2:]) ctl_points_old = ctl_points iold = 0 i = 1 for (ctl_points, command) in path_iter: iold = i i += len(ctl_points) // 2 if inside(ctl_points[-2:]) != begin_inside: bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points]) break ctl_points_old = ctl_points else: raise ValueError('The path does not intersect with the patch') bp = bezier_path.reshape((-1, 2)) (left, right) = split_bezier_intersecting_with_closedpath(bp, inside, tolerance) if len(left) == 2: codes_left = [Path.LINETO] codes_right = [Path.MOVETO, Path.LINETO] elif len(left) == 3: codes_left = [Path.CURVE3, Path.CURVE3] codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3] elif len(left) == 4: codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4] codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4] else: raise AssertionError('This should never be reached') verts_left = left[1:] verts_right = right[:] if path.codes is None: path_in = Path(np.concatenate([path.vertices[:i], verts_left])) path_out = Path(np.concatenate([verts_right, path.vertices[i:]])) else: path_in = Path(np.concatenate([path.vertices[:iold], verts_left]), np.concatenate([path.codes[:iold], codes_left])) path_out = Path(np.concatenate([verts_right, path.vertices[i:]]), np.concatenate([codes_right, path.codes[i:]])) if reorder_inout and (not begin_inside): (path_in, path_out) = (path_out, path_in) return (path_in, path_out) def inside_circle(cx, cy, r): r2 = r ** 2 def _f(xy): (x, y) = xy return (x - cx) ** 2 + (y - cy) ** 2 < r2 return _f def get_cos_sin(x0, y0, x1, y1): (dx, dy) = (x1 - x0, y1 - y0) d = (dx * dx + dy * dy) ** 0.5 if d == 0: return (0.0, 0.0) return (dx / d, dy / d) def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1e-05): theta1 = np.arctan2(dx1, dy1) theta2 = np.arctan2(dx2, dy2) dtheta = abs(theta1 - theta2) if dtheta < tolerance: return 1 elif abs(dtheta - np.pi) < tolerance: return -1 else: return False def get_parallels(bezier2, width): (c1x, c1y) = bezier2[0] (cmx, cmy) = bezier2[1] (c2x, c2y) = bezier2[2] parallel_test = check_if_parallel(c1x - cmx, c1y - cmy, cmx - c2x, cmy - c2y) if parallel_test == -1: _api.warn_external('Lines do not intersect. A straight line is used instead.') (cos_t1, sin_t1) = get_cos_sin(c1x, c1y, c2x, c2y) (cos_t2, sin_t2) = (cos_t1, sin_t1) else: (cos_t1, sin_t1) = get_cos_sin(c1x, c1y, cmx, cmy) (cos_t2, sin_t2) = get_cos_sin(cmx, cmy, c2x, c2y) (c1x_left, c1y_left, c1x_right, c1y_right) = get_normal_points(c1x, c1y, cos_t1, sin_t1, width) (c2x_left, c2y_left, c2x_right, c2y_right) = get_normal_points(c2x, c2y, cos_t2, sin_t2, width) try: (cmx_left, cmy_left) = get_intersection(c1x_left, c1y_left, cos_t1, sin_t1, c2x_left, c2y_left, cos_t2, sin_t2) (cmx_right, cmy_right) = get_intersection(c1x_right, c1y_right, cos_t1, sin_t1, c2x_right, c2y_right, cos_t2, sin_t2) except ValueError: (cmx_left, cmy_left) = (0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)) (cmx_right, cmy_right) = (0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)) path_left = [(c1x_left, c1y_left), (cmx_left, cmy_left), (c2x_left, c2y_left)] path_right = [(c1x_right, c1y_right), (cmx_right, cmy_right), (c2x_right, c2y_right)] return (path_left, path_right) def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y): cmx = 0.5 * (4 * mmx - (c1x + c2x)) cmy = 0.5 * (4 * mmy - (c1y + c2y)) return [(c1x, c1y), (cmx, cmy), (c2x, c2y)] def make_wedged_bezier2(bezier2, width, w1=1.0, wm=0.5, w2=0.0): (c1x, c1y) = bezier2[0] (cmx, cmy) = bezier2[1] (c3x, c3y) = bezier2[2] (cos_t1, sin_t1) = get_cos_sin(c1x, c1y, cmx, cmy) (cos_t2, sin_t2) = get_cos_sin(cmx, cmy, c3x, c3y) (c1x_left, c1y_left, c1x_right, c1y_right) = get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1) (c3x_left, c3y_left, c3x_right, c3y_right) = get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2) (c12x, c12y) = ((c1x + cmx) * 0.5, (c1y + cmy) * 0.5) (c23x, c23y) = ((cmx + c3x) * 0.5, (cmy + c3y) * 0.5) (c123x, c123y) = ((c12x + c23x) * 0.5, (c12y + c23y) * 0.5) (cos_t123, sin_t123) = get_cos_sin(c12x, c12y, c23x, c23y) (c123x_left, c123y_left, c123x_right, c123y_right) = get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm) path_left = find_control_points(c1x_left, c1y_left, c123x_left, c123y_left, c3x_left, c3y_left) path_right = find_control_points(c1x_right, c1y_right, c123x_right, c123y_right, c3x_right, c3y_right) return (path_left, path_right) # File: matplotlib-main/lib/matplotlib/category.py """""" from collections import OrderedDict import dateutil.parser import itertools import logging import numpy as np from matplotlib import _api, ticker, units _log = logging.getLogger(__name__) class StrCategoryConverter(units.ConversionInterface): @staticmethod def convert(value, unit, axis): if unit is None: raise ValueError('Missing category information for StrCategoryConverter; this might be caused by unintendedly mixing categorical and numeric data') StrCategoryConverter._validate_unit(unit) values = np.atleast_1d(np.array(value, dtype=object)) unit.update(values) return np.vectorize(unit._mapping.__getitem__, otypes=[float])(values) @staticmethod def axisinfo(unit, axis): StrCategoryConverter._validate_unit(unit) majloc = StrCategoryLocator(unit._mapping) majfmt = StrCategoryFormatter(unit._mapping) return units.AxisInfo(majloc=majloc, majfmt=majfmt) @staticmethod def default_units(data, axis): if axis.units is None: axis.set_units(UnitData(data)) else: axis.units.update(data) return axis.units @staticmethod def _validate_unit(unit): if not hasattr(unit, '_mapping'): raise ValueError(f'Provided unit "{unit}" is not valid for a categorical converter, as it does not have a _mapping attribute.') class StrCategoryLocator(ticker.Locator): def __init__(self, units_mapping): self._units = units_mapping def __call__(self): return list(self._units.values()) def tick_values(self, vmin, vmax): return self() class StrCategoryFormatter(ticker.Formatter): def __init__(self, units_mapping): self._units = units_mapping def __call__(self, x, pos=None): return self.format_ticks([x])[0] def format_ticks(self, values): r_mapping = {v: self._text(k) for (k, v) in self._units.items()} return [r_mapping.get(round(val), '') for val in values] @staticmethod def _text(value): if isinstance(value, bytes): value = value.decode(encoding='utf-8') elif not isinstance(value, str): value = str(value) return value class UnitData: def __init__(self, data=None): self._mapping = OrderedDict() self._counter = itertools.count() if data is not None: self.update(data) @staticmethod def _str_is_convertible(val): try: float(val) except ValueError: try: dateutil.parser.parse(val) except (ValueError, TypeError): return False return True def update(self, data): data = np.atleast_1d(np.array(data, dtype=object)) convertible = True for val in OrderedDict.fromkeys(data): _api.check_isinstance((str, bytes), value=val) if convertible: convertible = self._str_is_convertible(val) if val not in self._mapping: self._mapping[val] = next(self._counter) if data.size and convertible: _log.info('Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.') units.registry[str] = StrCategoryConverter() units.registry[np.str_] = StrCategoryConverter() units.registry[bytes] = StrCategoryConverter() units.registry[np.bytes_] = StrCategoryConverter() # File: matplotlib-main/lib/matplotlib/cbook.py """""" import collections import collections.abc import contextlib import functools import gzip import itertools import math import operator import os from pathlib import Path import shlex import subprocess import sys import time import traceback import types import weakref import numpy as np try: from numpy.exceptions import VisibleDeprecationWarning except ImportError: from numpy import VisibleDeprecationWarning import matplotlib from matplotlib import _api, _c_internal_utils def _get_running_interactive_framework(): QtWidgets = sys.modules.get('PyQt6.QtWidgets') or sys.modules.get('PySide6.QtWidgets') or sys.modules.get('PyQt5.QtWidgets') or sys.modules.get('PySide2.QtWidgets') if QtWidgets and QtWidgets.QApplication.instance(): return 'qt' Gtk = sys.modules.get('gi.repository.Gtk') if Gtk: if Gtk.MAJOR_VERSION == 4: from gi.repository import GLib if GLib.main_depth(): return 'gtk4' if Gtk.MAJOR_VERSION == 3 and Gtk.main_level(): return 'gtk3' wx = sys.modules.get('wx') if wx and wx.GetApp(): return 'wx' tkinter = sys.modules.get('tkinter') if tkinter: codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__} for frame in sys._current_frames().values(): while frame: if frame.f_code in codes: return 'tk' frame = frame.f_back del frame macosx = sys.modules.get('matplotlib.backends._macosx') if macosx and macosx.event_loop_is_running(): return 'macosx' if not _c_internal_utils.display_is_valid(): return 'headless' return None def _exception_printer(exc): if _get_running_interactive_framework() in ['headless', None]: raise exc else: traceback.print_exc() class _StrongRef: def __init__(self, obj): self._obj = obj def __call__(self): return self._obj def __eq__(self, other): return isinstance(other, _StrongRef) and self._obj == other._obj def __hash__(self): return hash(self._obj) def _weak_or_strong_ref(func, callback): try: return weakref.WeakMethod(func, callback) except TypeError: return _StrongRef(func) class CallbackRegistry: def __init__(self, exception_handler=_exception_printer, *, signals=None): self._signals = None if signals is None else list(signals) self.exception_handler = exception_handler self.callbacks = {} self._cid_gen = itertools.count() self._func_cid_map = {} self._pickled_cids = set() def __getstate__(self): return {**vars(self), 'callbacks': {s: {cid: proxy() for (cid, proxy) in d.items() if cid in self._pickled_cids} for (s, d) in self.callbacks.items()}, '_func_cid_map': None, '_cid_gen': next(self._cid_gen)} def __setstate__(self, state): cid_count = state.pop('_cid_gen') vars(self).update(state) self.callbacks = {s: {cid: _weak_or_strong_ref(func, self._remove_proxy) for (cid, func) in d.items()} for (s, d) in self.callbacks.items()} self._func_cid_map = {s: {proxy: cid for (cid, proxy) in d.items()} for (s, d) in self.callbacks.items()} self._cid_gen = itertools.count(cid_count) def connect(self, signal, func): if self._signals is not None: _api.check_in_list(self._signals, signal=signal) self._func_cid_map.setdefault(signal, {}) proxy = _weak_or_strong_ref(func, self._remove_proxy) if proxy in self._func_cid_map[signal]: return self._func_cid_map[signal][proxy] cid = next(self._cid_gen) self._func_cid_map[signal][proxy] = cid self.callbacks.setdefault(signal, {}) self.callbacks[signal][cid] = proxy return cid def _connect_picklable(self, signal, func): cid = self.connect(signal, func) self._pickled_cids.add(cid) return cid def _remove_proxy(self, proxy, *, _is_finalizing=sys.is_finalizing): if _is_finalizing(): return for (signal, proxy_to_cid) in list(self._func_cid_map.items()): cid = proxy_to_cid.pop(proxy, None) if cid is not None: del self.callbacks[signal][cid] self._pickled_cids.discard(cid) break else: return if len(self.callbacks[signal]) == 0: del self.callbacks[signal] del self._func_cid_map[signal] def disconnect(self, cid): self._pickled_cids.discard(cid) for (signal, cid_to_proxy) in list(self.callbacks.items()): proxy = cid_to_proxy.pop(cid, None) if proxy is not None: break else: return proxy_to_cid = self._func_cid_map[signal] for (current_proxy, current_cid) in list(proxy_to_cid.items()): if current_cid == cid: assert proxy is current_proxy del proxy_to_cid[current_proxy] if len(self.callbacks[signal]) == 0: del self.callbacks[signal] del self._func_cid_map[signal] def process(self, s, *args, **kwargs): if self._signals is not None: _api.check_in_list(self._signals, signal=s) for ref in list(self.callbacks.get(s, {}).values()): func = ref() if func is not None: try: func(*args, **kwargs) except Exception as exc: if self.exception_handler is not None: self.exception_handler(exc) else: raise @contextlib.contextmanager def blocked(self, *, signal=None): orig = self.callbacks try: if signal is None: self.callbacks = {} else: self.callbacks = {k: orig[k] for k in orig if k != signal} yield finally: self.callbacks = orig class silent_list(list): def __init__(self, type, seq=None): self.type = type if seq is not None: self.extend(seq) def __repr__(self): if self.type is not None or len(self) != 0: tp = self.type if self.type is not None else type(self[0]).__name__ return f'' else: return '' def _local_over_kwdict(local_var, kwargs, *keys, warning_cls=_api.MatplotlibDeprecationWarning): out = local_var for key in keys: kwarg_val = kwargs.pop(key, None) if kwarg_val is not None: if out is None: out = kwarg_val else: _api.warn_external(f'"{key}" keyword argument will be ignored', warning_cls) return out def strip_math(s): if len(s) >= 2 and s[0] == s[-1] == '$': s = s[1:-1] for (tex, plain) in [('\\times', 'x'), ('\\mathdefault', ''), ('\\rm', ''), ('\\cal', ''), ('\\tt', ''), ('\\it', ''), ('\\', ''), ('{', ''), ('}', '')]: s = s.replace(tex, plain) return s def _strip_comment(s): pos = 0 while True: quote_pos = s.find('"', pos) hash_pos = s.find('#', pos) if quote_pos < 0: without_comment = s if hash_pos < 0 else s[:hash_pos] return without_comment.strip() elif 0 <= hash_pos < quote_pos: return s[:hash_pos].strip() else: closing_quote_pos = s.find('"', quote_pos + 1) if closing_quote_pos < 0: raise ValueError(f'Missing closing quote in: {s!r}. If you need a double-quote inside a string, use escaping: e.g. "the " char"') pos = closing_quote_pos + 1 def is_writable_file_like(obj): return callable(getattr(obj, 'write', None)) def file_requires_unicode(x): try: x.write(b'') except TypeError: return True else: return False def to_filehandle(fname, flag='r', return_opened=False, encoding=None): if isinstance(fname, os.PathLike): fname = os.fspath(fname) if isinstance(fname, str): if fname.endswith('.gz'): fh = gzip.open(fname, flag) elif fname.endswith('.bz2'): import bz2 fh = bz2.BZ2File(fname, flag) else: fh = open(fname, flag, encoding=encoding) opened = True elif hasattr(fname, 'seek'): fh = fname opened = False else: raise ValueError('fname must be a PathLike or file handle') if return_opened: return (fh, opened) return fh def open_file_cm(path_or_file, mode='r', encoding=None): (fh, opened) = to_filehandle(path_or_file, mode, True, encoding) return fh if opened else contextlib.nullcontext(fh) def is_scalar_or_string(val): return isinstance(val, str) or not np.iterable(val) @_api.delete_parameter('3.8', 'np_load', alternative='open(get_sample_data(..., asfileobj=False))') def get_sample_data(fname, asfileobj=True, *, np_load=True): path = _get_data_path('sample_data', fname) if asfileobj: suffix = path.suffix.lower() if suffix == '.gz': return gzip.open(path) elif suffix in ['.npy', '.npz']: if np_load: return np.load(path) else: return path.open('rb') elif suffix in ['.csv', '.xrc', '.txt']: return path.open('r') else: return path.open('rb') else: return str(path) def _get_data_path(*args): return Path(matplotlib.get_data_path(), *args) def flatten(seq, scalarp=is_scalar_or_string): for item in seq: if scalarp(item) or item is None: yield item else: yield from flatten(item, scalarp) @_api.deprecated('3.8') class Stack: def __init__(self, default=None): self.clear() self._default = default def __call__(self): if not self._elements: return self._default else: return self._elements[self._pos] def __len__(self): return len(self._elements) def __getitem__(self, ind): return self._elements[ind] def forward(self): self._pos = min(self._pos + 1, len(self._elements) - 1) return self() def back(self): if self._pos > 0: self._pos -= 1 return self() def push(self, o): self._elements = self._elements[:self._pos + 1] + [o] self._pos = len(self._elements) - 1 return self() def home(self): if not self._elements: return self.push(self._elements[0]) return self() def empty(self): return len(self._elements) == 0 def clear(self): self._pos = -1 self._elements = [] def bubble(self, o): if o not in self._elements: raise ValueError('Given element not contained in the stack') old_elements = self._elements.copy() self.clear() top_elements = [] for elem in old_elements: if elem == o: top_elements.append(elem) else: self.push(elem) for _ in top_elements: self.push(o) return o def remove(self, o): if o not in self._elements: raise ValueError('Given element not contained in the stack') old_elements = self._elements.copy() self.clear() for elem in old_elements: if elem != o: self.push(elem) class _Stack: def __init__(self): self._pos = -1 self._elements = [] def clear(self): self._pos = -1 self._elements = [] def __call__(self): return self._elements[self._pos] if self._elements else None def __len__(self): return len(self._elements) def __getitem__(self, ind): return self._elements[ind] def forward(self): self._pos = min(self._pos + 1, len(self._elements) - 1) return self() def back(self): self._pos = max(self._pos - 1, 0) return self() def push(self, o): self._elements[self._pos + 1:] = [o] self._pos = len(self._elements) - 1 return o def home(self): return self.push(self._elements[0]) if self._elements else None def safe_masked_invalid(x, copy=False): x = np.array(x, subok=True, copy=copy) if not x.dtype.isnative: x = x.byteswap(inplace=copy).view(x.dtype.newbyteorder('N')) try: xm = np.ma.masked_where(~np.isfinite(x), x, copy=False) except TypeError: return x return xm def print_cycles(objects, outstream=sys.stdout, show_progress=False): import gc def print_path(path): for (i, step) in enumerate(path): next = path[(i + 1) % len(path)] outstream.write(' %s -- ' % type(step)) if isinstance(step, dict): for (key, val) in step.items(): if val is next: outstream.write(f'[{key!r}]') break if key is next: outstream.write(f'[key] = {val!r}') break elif isinstance(step, list): outstream.write('[%d]' % step.index(next)) elif isinstance(step, tuple): outstream.write('( tuple )') else: outstream.write(repr(step)) outstream.write(' ->\n') outstream.write('\n') def recurse(obj, start, all, current_path): if show_progress: outstream.write('%d\r' % len(all)) all[id(obj)] = None referents = gc.get_referents(obj) for referent in referents: if referent is start: print_path(current_path) elif referent is objects or isinstance(referent, types.FrameType): continue elif id(referent) not in all: recurse(referent, start, all, current_path + [obj]) for obj in objects: outstream.write(f'Examining: {obj!r}\n') recurse(obj, obj, {}, []) class Grouper: def __init__(self, init=()): self._mapping = weakref.WeakKeyDictionary({x: weakref.WeakSet([x]) for x in init}) self._ordering = weakref.WeakKeyDictionary() for x in init: if x not in self._ordering: self._ordering[x] = len(self._ordering) self._next_order = len(self._ordering) def __getstate__(self): return {**vars(self), '_mapping': {k: set(v) for (k, v) in self._mapping.items()}, '_ordering': {**self._ordering}} def __setstate__(self, state): vars(self).update(state) self._mapping = weakref.WeakKeyDictionary({k: weakref.WeakSet(v) for (k, v) in self._mapping.items()}) self._ordering = weakref.WeakKeyDictionary(self._ordering) def __contains__(self, item): return item in self._mapping @_api.deprecated('3.8', alternative='none, you no longer need to clean a Grouper') def clean(self): def join(self, a, *args): mapping = self._mapping try: set_a = mapping[a] except KeyError: set_a = mapping[a] = weakref.WeakSet([a]) self._ordering[a] = self._next_order self._next_order += 1 for arg in args: try: set_b = mapping[arg] except KeyError: set_b = mapping[arg] = weakref.WeakSet([arg]) self._ordering[arg] = self._next_order self._next_order += 1 if set_b is not set_a: if len(set_b) > len(set_a): (set_a, set_b) = (set_b, set_a) set_a.update(set_b) for elem in set_b: mapping[elem] = set_a def joined(self, a, b): return self._mapping.get(a, object()) is self._mapping.get(b) def remove(self, a): self._mapping.pop(a, {a}).remove(a) self._ordering.pop(a, None) def __iter__(self): unique_groups = {id(group): group for group in self._mapping.values()} for group in unique_groups.values(): yield sorted(group, key=self._ordering.__getitem__) def get_siblings(self, a): siblings = self._mapping.get(a, [a]) return sorted(siblings, key=self._ordering.get) class GrouperView: def __init__(self, grouper): self._grouper = grouper def __contains__(self, item): return item in self._grouper def __iter__(self): return iter(self._grouper) def joined(self, a, b): return self._grouper.joined(a, b) def get_siblings(self, a): return self._grouper.get_siblings(a) def simple_linear_interpolation(a, steps): fps = a.reshape((len(a), -1)) xp = np.arange(len(a)) * steps x = np.arange((len(a) - 1) * steps + 1) return np.column_stack([np.interp(x, xp, fp) for fp in fps.T]).reshape((len(x),) + a.shape[1:]) def delete_masked_points(*args): if not len(args): return () if is_scalar_or_string(args[0]): raise ValueError('First argument must be a sequence') nrecs = len(args[0]) margs = [] seqlist = [False] * len(args) for (i, x) in enumerate(args): if not isinstance(x, str) and np.iterable(x) and (len(x) == nrecs): seqlist[i] = True if isinstance(x, np.ma.MaskedArray): if x.ndim > 1: raise ValueError('Masked arrays must be 1-D') else: x = np.asarray(x) margs.append(x) masks = [] for (i, x) in enumerate(margs): if seqlist[i]: if x.ndim > 1: continue if isinstance(x, np.ma.MaskedArray): masks.append(~np.ma.getmaskarray(x)) xd = x.data else: xd = x try: mask = np.isfinite(xd) if isinstance(mask, np.ndarray): masks.append(mask) except Exception: pass if len(masks): mask = np.logical_and.reduce(masks) igood = mask.nonzero()[0] if len(igood) < nrecs: for (i, x) in enumerate(margs): if seqlist[i]: margs[i] = x[igood] for (i, x) in enumerate(margs): if seqlist[i] and isinstance(x, np.ma.MaskedArray): margs[i] = x.filled() return margs def _combine_masks(*args): if not len(args): return () if is_scalar_or_string(args[0]): raise ValueError('First argument must be a sequence') nrecs = len(args[0]) margs = [] seqlist = [False] * len(args) masks = [] for (i, x) in enumerate(args): if is_scalar_or_string(x) or len(x) != nrecs: margs.append(x) else: if isinstance(x, np.ma.MaskedArray) and x.ndim > 1: raise ValueError('Masked arrays must be 1-D') try: x = np.asanyarray(x) except (VisibleDeprecationWarning, ValueError): x = np.asanyarray(x, dtype=object) if x.ndim == 1: x = safe_masked_invalid(x) seqlist[i] = True if np.ma.is_masked(x): masks.append(np.ma.getmaskarray(x)) margs.append(x) if len(masks): mask = np.logical_or.reduce(masks) for (i, x) in enumerate(margs): if seqlist[i]: margs[i] = np.ma.array(x, mask=mask) return margs def _broadcast_with_masks(*args, compress=False): masks = [k.mask for k in args if isinstance(k, np.ma.MaskedArray)] bcast = np.broadcast_arrays(*args, *masks) inputs = bcast[:len(args)] masks = bcast[len(args):] if masks: mask = np.logical_or.reduce(masks) if compress: inputs = [np.ma.array(k, mask=mask).compressed() for k in inputs] else: inputs = [np.ma.array(k, mask=mask, dtype=float).filled(np.nan).ravel() for k in inputs] else: inputs = [np.ravel(k) for k in inputs] return inputs def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False): def _bootstrap_median(data, N=5000): M = len(data) percentiles = [2.5, 97.5] bs_index = np.random.randint(M, size=(N, M)) bsData = data[bs_index] estimate = np.median(bsData, axis=1, overwrite_input=True) CI = np.percentile(estimate, percentiles) return CI def _compute_conf_interval(data, med, iqr, bootstrap): if bootstrap is not None: CI = _bootstrap_median(data, N=bootstrap) notch_min = CI[0] notch_max = CI[1] else: N = len(data) notch_min = med - 1.57 * iqr / np.sqrt(N) notch_max = med + 1.57 * iqr / np.sqrt(N) return (notch_min, notch_max) bxpstats = [] X = _reshape_2D(X, 'X') ncols = len(X) if labels is None: labels = itertools.repeat(None) elif len(labels) != ncols: raise ValueError('Dimensions of labels and X must be compatible') input_whis = whis for (ii, (x, label)) in enumerate(zip(X, labels)): stats = {} if label is not None: stats['label'] = label whis = input_whis bxpstats.append(stats) if len(x) == 0: stats['fliers'] = np.array([]) stats['mean'] = np.nan stats['med'] = np.nan stats['q1'] = np.nan stats['q3'] = np.nan stats['iqr'] = np.nan stats['cilo'] = np.nan stats['cihi'] = np.nan stats['whislo'] = np.nan stats['whishi'] = np.nan continue x = np.ma.asarray(x) x = x.data[~x.mask].ravel() stats['mean'] = np.mean(x) (q1, med, q3) = np.percentile(x, [25, 50, 75]) stats['iqr'] = q3 - q1 if stats['iqr'] == 0 and autorange: whis = (0, 100) (stats['cilo'], stats['cihi']) = _compute_conf_interval(x, med, stats['iqr'], bootstrap) if np.iterable(whis) and (not isinstance(whis, str)): (loval, hival) = np.percentile(x, whis) elif np.isreal(whis): loval = q1 - whis * stats['iqr'] hival = q3 + whis * stats['iqr'] else: raise ValueError('whis must be a float or list of percentiles') wiskhi = x[x <= hival] if len(wiskhi) == 0 or np.max(wiskhi) < q3: stats['whishi'] = q3 else: stats['whishi'] = np.max(wiskhi) wisklo = x[x >= loval] if len(wisklo) == 0 or np.min(wisklo) > q1: stats['whislo'] = q1 else: stats['whislo'] = np.min(wisklo) stats['fliers'] = np.concatenate([x[x < stats['whislo']], x[x > stats['whishi']]]) (stats['q1'], stats['med'], stats['q3']) = (q1, med, q3) return bxpstats ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'} ls_mapper_r = {v: k for (k, v) in ls_mapper.items()} def contiguous_regions(mask): mask = np.asarray(mask, dtype=bool) if not mask.size: return [] (idx,) = np.nonzero(mask[:-1] != mask[1:]) idx += 1 idx = idx.tolist() if mask[0]: idx = [0] + idx if mask[-1]: idx.append(len(mask)) return list(zip(idx[::2], idx[1::2])) def is_math_text(s): s = str(s) dollar_count = s.count('$') - s.count('\\$') even_dollars = dollar_count > 0 and dollar_count % 2 == 0 return even_dollars def _to_unmasked_float_array(x): if hasattr(x, 'mask'): return np.ma.asarray(x, float).filled(np.nan) else: return np.asarray(x, float) def _check_1d(x): x = _unpack_to_numpy(x) if not hasattr(x, 'shape') or not hasattr(x, 'ndim') or len(x.shape) < 1: return np.atleast_1d(x) else: return x def _reshape_2D(X, name): X = _unpack_to_numpy(X) if isinstance(X, np.ndarray): X = X.T if len(X) == 0: return [[]] elif X.ndim == 1 and np.ndim(X[0]) == 0: return [X] elif X.ndim in [1, 2]: return [np.reshape(x, -1) for x in X] else: raise ValueError(f'{name} must have 2 or fewer dimensions') if len(X) == 0: return [[]] result = [] is_1d = True for xi in X: if not isinstance(xi, str): try: iter(xi) except TypeError: pass else: is_1d = False xi = np.asanyarray(xi) nd = np.ndim(xi) if nd > 1: raise ValueError(f'{name} must have 2 or fewer dimensions') result.append(xi.reshape(-1)) if is_1d: return [np.reshape(result, -1)] else: return result def violin_stats(X, method, points=100, quantiles=None): vpstats = [] X = _reshape_2D(X, 'X') if quantiles is not None and len(quantiles) != 0: quantiles = _reshape_2D(quantiles, 'quantiles') else: quantiles = [[]] * len(X) if len(X) != len(quantiles): raise ValueError('List of violinplot statistics and quantiles values must have the same length') for (x, q) in zip(X, quantiles): stats = {} min_val = np.min(x) max_val = np.max(x) quantile_val = np.percentile(x, 100 * q) coords = np.linspace(min_val, max_val, points) stats['vals'] = method(x, coords) stats['coords'] = coords stats['mean'] = np.mean(x) stats['median'] = np.median(x) stats['min'] = min_val stats['max'] = max_val stats['quantiles'] = np.atleast_1d(quantile_val) vpstats.append(stats) return vpstats def pts_to_prestep(x, *args): steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0))) steps[0, 0::2] = x steps[0, 1::2] = steps[0, 0:-2:2] steps[1:, 0::2] = args steps[1:, 1::2] = steps[1:, 2::2] return steps def pts_to_poststep(x, *args): steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0))) steps[0, 0::2] = x steps[0, 1::2] = steps[0, 2::2] steps[1:, 0::2] = args steps[1:, 1::2] = steps[1:, 0:-2:2] return steps def pts_to_midstep(x, *args): steps = np.zeros((1 + len(args), 2 * len(x))) x = np.asanyarray(x) steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2 steps[0, :1] = x[:1] steps[0, -1:] = x[-1:] steps[1:, 0::2] = args steps[1:, 1::2] = steps[1:, 0::2] return steps STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y), 'steps': pts_to_prestep, 'steps-pre': pts_to_prestep, 'steps-post': pts_to_poststep, 'steps-mid': pts_to_midstep} def index_of(y): try: return (y.index.to_numpy(), y.to_numpy()) except AttributeError: pass try: y = _check_1d(y) except (VisibleDeprecationWarning, ValueError): pass else: return (np.arange(y.shape[0], dtype=float), y) raise ValueError('Input could not be cast to an at-least-1D NumPy array') def safe_first_element(obj): if isinstance(obj, collections.abc.Iterator): try: return obj[0] except TypeError: pass raise RuntimeError('matplotlib does not support generators as input') return next(iter(obj)) def _safe_first_finite(obj): def safe_isfinite(val): if val is None: return False try: return math.isfinite(val) except (TypeError, ValueError): pass try: return np.isfinite(val) if np.isscalar(val) else True except TypeError: return True if isinstance(obj, np.flatiter): return obj[0] elif isinstance(obj, collections.abc.Iterator): raise RuntimeError('matplotlib does not support generators as input') else: for val in obj: if safe_isfinite(val): return val return safe_first_element(obj) def sanitize_sequence(data): return list(data) if isinstance(data, collections.abc.MappingView) else data def normalize_kwargs(kw, alias_mapping=None): from matplotlib.artist import Artist if kw is None: return {} if alias_mapping is None: alias_mapping = {} elif isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist) or isinstance(alias_mapping, Artist): alias_mapping = getattr(alias_mapping, '_alias_map', {}) to_canonical = {alias: canonical for (canonical, alias_list) in alias_mapping.items() for alias in alias_list} canonical_to_seen = {} ret = {} for (k, v) in kw.items(): canonical = to_canonical.get(k, k) if canonical in canonical_to_seen: raise TypeError(f'Got both {canonical_to_seen[canonical]!r} and {k!r}, which are aliases of one another') canonical_to_seen[canonical] = k ret[canonical] = v return ret @contextlib.contextmanager def _lock_path(path): path = Path(path) lock_path = path.with_name(path.name + '.matplotlib-lock') retries = 50 sleeptime = 0.1 for _ in range(retries): try: with lock_path.open('xb'): break except FileExistsError: time.sleep(sleeptime) else: raise TimeoutError('Lock error: Matplotlib failed to acquire the following lock file:\n {}\nThis maybe due to another process holding this lock file. If you are sure no\nother Matplotlib process is running, remove this file and try again.'.format(lock_path)) try: yield finally: lock_path.unlink() def _topmost_artist(artists, _cached_max=functools.partial(max, key=operator.attrgetter('zorder'))): return _cached_max(reversed(artists)) def _str_equal(obj, s): return isinstance(obj, str) and obj == s def _str_lower_equal(obj, s): return isinstance(obj, str) and obj.lower() == s def _array_perimeter(arr): forward = np.s_[0:-1] backward = np.s_[-1:0:-1] return np.concatenate((arr[0, forward], arr[forward, -1], arr[-1, backward], arr[backward, 0])) def _unfold(arr, axis, size, step): new_shape = [*arr.shape, size] new_strides = [*arr.strides, arr.strides[axis]] new_shape[axis] = (new_shape[axis] - size) // step + 1 new_strides[axis] = new_strides[axis] * step return np.lib.stride_tricks.as_strided(arr, shape=new_shape, strides=new_strides, writeable=False) def _array_patch_perimeters(x, rstride, cstride): assert rstride > 0 and cstride > 0 assert (x.shape[0] - 1) % rstride == 0 assert (x.shape[1] - 1) % cstride == 0 top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride) bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1] right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride) left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1] return np.concatenate((top, right, bottom, left), axis=2).reshape(-1, 2 * (rstride + cstride)) @contextlib.contextmanager def _setattr_cm(obj, **kwargs): sentinel = object() origs = {} for attr in kwargs: orig = getattr(obj, attr, sentinel) if attr in obj.__dict__ or orig is sentinel: origs[attr] = orig else: cls_orig = getattr(type(obj), attr) if isinstance(cls_orig, property): origs[attr] = orig else: origs[attr] = sentinel try: for (attr, val) in kwargs.items(): setattr(obj, attr, val) yield finally: for (attr, orig) in origs.items(): if orig is sentinel: delattr(obj, attr) else: setattr(obj, attr, orig) class _OrderedSet(collections.abc.MutableSet): def __init__(self): self._od = collections.OrderedDict() def __contains__(self, key): return key in self._od def __iter__(self): return iter(self._od) def __len__(self): return len(self._od) def add(self, key): self._od.pop(key, None) self._od[key] = None def discard(self, key): self._od.pop(key, None) def _premultiplied_argb32_to_unmultiplied_rgba8888(buf): rgba = np.take(buf, [2, 1, 0, 3] if sys.byteorder == 'little' else [1, 2, 3, 0], axis=2) rgb = rgba[..., :-1] alpha = rgba[..., -1] mask = alpha != 0 for channel in np.rollaxis(rgb, -1): channel[mask] = (channel[mask].astype(int) * 255 + alpha[mask] // 2) // alpha[mask] return rgba def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888): if sys.byteorder == 'little': argb32 = np.take(rgba8888, [2, 1, 0, 3], axis=2) rgb24 = argb32[..., :-1] alpha8 = argb32[..., -1:] else: argb32 = np.take(rgba8888, [3, 0, 1, 2], axis=2) alpha8 = argb32[..., :1] rgb24 = argb32[..., 1:] if alpha8.min() != 255: np.multiply(rgb24, alpha8 / 255, out=rgb24, casting='unsafe') return argb32 def _get_nonzero_slices(buf): (x_nz,) = buf.any(axis=0).nonzero() (y_nz,) = buf.any(axis=1).nonzero() if len(x_nz) and len(y_nz): (l, r) = x_nz[[0, -1]] (b, t) = y_nz[[0, -1]] return (slice(b, t + 1), slice(l, r + 1)) else: return (slice(0, 0), slice(0, 0)) def _pformat_subprocess(command): return command if isinstance(command, str) else ' '.join((shlex.quote(os.fspath(arg)) for arg in command)) def _check_and_log_subprocess(command, logger, **kwargs): logger.debug('%s', _pformat_subprocess(command)) proc = subprocess.run(command, capture_output=True, **kwargs) if proc.returncode: stdout = proc.stdout if isinstance(stdout, bytes): stdout = stdout.decode() stderr = proc.stderr if isinstance(stderr, bytes): stderr = stderr.decode() raise RuntimeError(f'The command\n {_pformat_subprocess(command)}\nfailed and generated the following output:\n{stdout}\nand the following error:\n{stderr}') if proc.stdout: logger.debug('stdout:\n%s', proc.stdout) if proc.stderr: logger.debug('stderr:\n%s', proc.stderr) return proc.stdout def _setup_new_guiapp(): try: _c_internal_utils.Win32_GetCurrentProcessExplicitAppUserModelID() except OSError: _c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID('matplotlib') def _format_approx(number, precision): return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0' def _g_sig_digits(value, delta): if delta == 0: if value == 0: return 3 delta = abs(np.spacing(value)) return max(0, (math.floor(math.log10(abs(value))) + 1 if value else 1) - math.floor(math.log10(delta))) if math.isfinite(value) else 0 def _unikey_or_keysym_to_mplkey(unikey, keysym): if unikey and unikey.isprintable(): return unikey key = keysym.lower() if key.startswith('kp_'): key = key[3:] if key.startswith('page_'): key = key.replace('page_', 'page') if key.endswith(('_l', '_r')): key = key[:-2] if sys.platform == 'darwin' and key == 'meta': key = 'cmd' key = {'return': 'enter', 'prior': 'pageup', 'next': 'pagedown'}.get(key, key) return key @functools.cache def _make_class_factory(mixin_class, fmt, attr_name=None): @functools.cache def class_factory(axes_class): if issubclass(axes_class, mixin_class): return axes_class base_class = axes_class class subcls(mixin_class, base_class): __module__ = mixin_class.__module__ def __reduce__(self): return (_picklable_class_constructor, (mixin_class, fmt, attr_name, base_class), self.__getstate__()) subcls.__name__ = subcls.__qualname__ = fmt.format(base_class.__name__) if attr_name is not None: setattr(subcls, attr_name, base_class) return subcls class_factory.__module__ = mixin_class.__module__ return class_factory def _picklable_class_constructor(mixin_class, fmt, attr_name, base_class): factory = _make_class_factory(mixin_class, fmt, attr_name) cls = factory(base_class) return cls.__new__(cls) def _is_torch_array(x): try: return isinstance(x, sys.modules['torch'].Tensor) except Exception: return False def _is_jax_array(x): try: return isinstance(x, sys.modules['jax'].Array) except Exception: return False def _is_tensorflow_array(x): try: return isinstance(x, sys.modules['tensorflow'].is_tensor(x)) except Exception: return False def _unpack_to_numpy(x): if isinstance(x, np.ndarray): return x if hasattr(x, 'to_numpy'): return x.to_numpy() if hasattr(x, 'values'): xtmp = x.values if isinstance(xtmp, np.ndarray): return xtmp if _is_torch_array(x) or _is_jax_array(x) or _is_tensorflow_array(x): xtmp = np.asarray(x) if isinstance(xtmp, np.ndarray): return xtmp return x def _auto_format_str(fmt, value): try: return fmt % (value,) except (TypeError, ValueError): return fmt.format(value) # File: matplotlib-main/lib/matplotlib/cm.py """""" from collections.abc import Mapping import functools import numpy as np from numpy import ma import matplotlib as mpl from matplotlib import _api, colors, cbook, scale from matplotlib._cm import datad from matplotlib._cm_listed import cmaps as cmaps_listed from matplotlib._cm_multivar import cmap_families as multivar_cmaps from matplotlib._cm_bivar import cmaps as bivar_cmaps _LUTSIZE = mpl.rcParams['image.lut'] def _gen_cmap_registry(): cmap_d = {**cmaps_listed} for (name, spec) in datad.items(): cmap_d[name] = colors.LinearSegmentedColormap(name, spec, _LUTSIZE) if 'red' in spec else colors.ListedColormap(spec['listed'], name) if 'listed' in spec else colors.LinearSegmentedColormap.from_list(name, spec, _LUTSIZE) aliases = {'grey': 'gray', 'gist_grey': 'gist_gray', 'gist_yerg': 'gist_yarg', 'Grays': 'Greys'} for (alias, original_name) in aliases.items(): cmap = cmap_d[original_name].copy() cmap.name = alias cmap_d[alias] = cmap for cmap in list(cmap_d.values()): rmap = cmap.reversed() cmap_d[rmap.name] = rmap return cmap_d class ColormapRegistry(Mapping): def __init__(self, cmaps): self._cmaps = cmaps self._builtin_cmaps = tuple(cmaps) def __getitem__(self, item): try: return self._cmaps[item].copy() except KeyError: raise KeyError(f'{item!r} is not a known colormap name') from None def __iter__(self): return iter(self._cmaps) def __len__(self): return len(self._cmaps) def __str__(self): return 'ColormapRegistry; available colormaps:\n' + ', '.join((f"'{name}'" for name in self)) def __call__(self): return list(self) def register(self, cmap, *, name=None, force=False): _api.check_isinstance(colors.Colormap, cmap=cmap) name = name or cmap.name if name in self: if not force: raise ValueError(f'A colormap named "{name}" is already registered.') elif name in self._builtin_cmaps: raise ValueError(f'Re-registering the builtin cmap {name!r} is not allowed.') _api.warn_external(f'Overwriting the cmap {name!r} that was already in the registry.') self._cmaps[name] = cmap.copy() if self._cmaps[name].name != name: self._cmaps[name].name = name def unregister(self, name): if name in self._builtin_cmaps: raise ValueError(f'cannot unregister {name!r} which is a builtin colormap.') self._cmaps.pop(name, None) def get_cmap(self, cmap): if cmap is None: return self[mpl.rcParams['image.cmap']] if isinstance(cmap, colors.Colormap): return cmap if isinstance(cmap, str): _api.check_in_list(sorted(_colormaps), cmap=cmap) return self[cmap] raise TypeError('get_cmap expects None or an instance of a str or Colormap . ' + f'you passed {cmap!r} of type {type(cmap)}') _colormaps = ColormapRegistry(_gen_cmap_registry()) globals().update(_colormaps) _multivar_colormaps = ColormapRegistry(multivar_cmaps) _bivar_colormaps = ColormapRegistry(bivar_cmaps) @_api.deprecated('3.7', removal='3.11', alternative='``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()`` or ``pyplot.get_cmap()``') def get_cmap(name=None, lut=None): if name is None: name = mpl.rcParams['image.cmap'] if isinstance(name, colors.Colormap): return name _api.check_in_list(sorted(_colormaps), name=name) if lut is None: return _colormaps[name] else: return _colormaps[name].resampled(lut) def _auto_norm_from_scale(scale_cls): try: norm = colors.make_norm_from_scale(functools.partial(scale_cls, nonpositive='mask'))(colors.Normalize)() except TypeError: norm = colors.make_norm_from_scale(scale_cls)(colors.Normalize)() return type(norm) class ScalarMappable: def __init__(self, norm=None, cmap=None): self._A = None self._norm = None self.set_norm(norm) self.cmap = None self.set_cmap(cmap) self.colorbar = None self.callbacks = cbook.CallbackRegistry(signals=['changed']) def _scale_norm(self, norm, vmin, vmax): if vmin is not None or vmax is not None: self.set_clim(vmin, vmax) if isinstance(norm, colors.Normalize): raise ValueError('Passing a Normalize instance simultaneously with vmin/vmax is not supported. Please pass vmin/vmax directly to the norm when creating it.') self.autoscale_None() def to_rgba(self, x, alpha=None, bytes=False, norm=True): try: if x.ndim == 3: if x.shape[2] == 3: if alpha is None: alpha = 1 if x.dtype == np.uint8: alpha = np.uint8(alpha * 255) (m, n) = x.shape[:2] xx = np.empty(shape=(m, n, 4), dtype=x.dtype) xx[:, :, :3] = x xx[:, :, 3] = alpha elif x.shape[2] == 4: xx = x else: raise ValueError('Third dimension must be 3 or 4') if xx.dtype.kind == 'f': if np.any((nans := np.isnan(x))): if x.shape[2] == 4: xx = xx.copy() xx[np.any(nans, axis=2), :] = 0 if norm and (xx.max() > 1 or xx.min() < 0): raise ValueError('Floating point image RGB values must be in the 0..1 range.') if bytes: xx = (xx * 255).astype(np.uint8) elif xx.dtype == np.uint8: if not bytes: xx = xx.astype(np.float32) / 255 else: raise ValueError('Image RGB array must be uint8 or floating point; found %s' % xx.dtype) if np.ma.is_masked(x): xx[np.any(np.ma.getmaskarray(x), axis=2), 3] = 0 return xx except AttributeError: pass x = ma.asarray(x) if norm: x = self.norm(x) rgba = self.cmap(x, alpha=alpha, bytes=bytes) return rgba def set_array(self, A): if A is None: self._A = None return A = cbook.safe_masked_invalid(A, copy=True) if not np.can_cast(A.dtype, float, 'same_kind'): raise TypeError(f'Image data of dtype {A.dtype} cannot be converted to float') self._A = A if not self.norm.scaled(): self.norm.autoscale_None(A) def get_array(self): return self._A def get_cmap(self): return self.cmap def get_clim(self): return (self.norm.vmin, self.norm.vmax) def set_clim(self, vmin=None, vmax=None): if vmax is None: try: (vmin, vmax) = vmin except (TypeError, ValueError): pass if vmin is not None: self.norm.vmin = colors._sanitize_extrema(vmin) if vmax is not None: self.norm.vmax = colors._sanitize_extrema(vmax) def get_alpha(self): return 1.0 def set_cmap(self, cmap): in_init = self.cmap is None self.cmap = _ensure_cmap(cmap) if not in_init: self.changed() @property def norm(self): return self._norm @norm.setter def norm(self, norm): _api.check_isinstance((colors.Normalize, str, None), norm=norm) if norm is None: norm = colors.Normalize() elif isinstance(norm, str): try: scale_cls = scale._scale_mapping[norm] except KeyError: raise ValueError(f"Invalid norm str name; the following values are supported: {', '.join(scale._scale_mapping)}") from None norm = _auto_norm_from_scale(scale_cls)() if norm is self.norm: return in_init = self.norm is None if not in_init: self.norm.callbacks.disconnect(self._id_norm) self._norm = norm self._id_norm = self.norm.callbacks.connect('changed', self.changed) if not in_init: self.changed() def set_norm(self, norm): self.norm = norm def autoscale(self): if self._A is None: raise TypeError('You must first set_array for mappable') self.norm.autoscale(self._A) def autoscale_None(self): if self._A is None: raise TypeError('You must first set_array for mappable') self.norm.autoscale_None(self._A) def changed(self): self.callbacks.process('changed', self) self.stale = True def _format_cursor_data_override(self, data): n = self.cmap.N if np.ma.getmask(data): return '[]' normed = self.norm(data) if np.isfinite(normed): if isinstance(self.norm, colors.BoundaryNorm): cur_idx = np.argmin(np.abs(self.norm.boundaries - data)) neigh_idx = max(0, cur_idx - 1) delta = np.diff(self.norm.boundaries[neigh_idx:cur_idx + 2]).max() elif self.norm.vmin == self.norm.vmax: delta = np.abs(self.norm.vmin * 0.1) else: neighbors = self.norm.inverse((int(normed * n) + np.array([0, 1])) / n) delta = abs(neighbors - data).max() g_sig_digits = cbook._g_sig_digits(data, delta) else: g_sig_digits = 3 return f'[{data:-#.{g_sig_digits}g}]' mpl._docstring.interpd.update(cmap_doc='cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\n The Colormap instance or registered colormap name used to map scalar data\n to colors.', norm_doc='norm : str or `~matplotlib.colors.Normalize`, optional\n The normalization method used to scale scalar data to the [0, 1] range\n before mapping to colors using *cmap*. By default, a linear scaling is\n used, mapping the lowest value to 0 and the highest to 1.\n\n If given, this can be one of the following:\n\n - An instance of `.Normalize` or one of its subclasses\n (see :ref:`colormapnorms`).\n - A scale name, i.e. one of "linear", "log", "symlog", "logit", etc. For a\n list of available scales, call `matplotlib.scale.get_scale_names()`.\n In that case, a suitable `.Normalize` subclass is dynamically generated\n and instantiated.', vmin_vmax_doc='vmin, vmax : float, optional\n When using scalar data and no explicit *norm*, *vmin* and *vmax* define\n the data range that the colormap covers. By default, the colormap covers\n the complete value range of the supplied data. It is an error to use\n *vmin*/*vmax* when a *norm* instance is given (but using a `str` *norm*\n name together with *vmin*/*vmax* is acceptable).') def _ensure_cmap(cmap): if isinstance(cmap, colors.Colormap): return cmap cmap_name = cmap if cmap is not None else mpl.rcParams['image.cmap'] if cmap_name not in _colormaps: _api.check_in_list(sorted(_colormaps), cmap=cmap_name) return mpl.colormaps[cmap_name] # File: matplotlib-main/lib/matplotlib/collections.py """""" import itertools import math from numbers import Number, Real import warnings import numpy as np import matplotlib as mpl from . import _api, _path, artist, cbook, cm, colors as mcolors, _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms from ._enums import JoinStyle, CapStyle @_api.define_aliases({'antialiased': ['antialiaseds', 'aa'], 'edgecolor': ['edgecolors', 'ec'], 'facecolor': ['facecolors', 'fc'], 'linestyle': ['linestyles', 'dashes', 'ls'], 'linewidth': ['linewidths', 'lw'], 'offset_transform': ['transOffset']}) class Collection(artist.Artist, cm.ScalarMappable): _transforms = np.empty((0, 3, 3)) _edge_default = False @_docstring.interpd def __init__(self, *, edgecolors=None, facecolors=None, linewidths=None, linestyles='solid', capstyle=None, joinstyle=None, antialiaseds=None, offsets=None, offset_transform=None, norm=None, cmap=None, pickradius=5.0, hatch=None, urls=None, zorder=1, **kwargs): artist.Artist.__init__(self) cm.ScalarMappable.__init__(self, norm, cmap) self._us_linestyles = [(0, None)] self._linestyles = [(0, None)] self._us_lw = [0] self._linewidths = [0] self._gapcolor = None self._face_is_mapped = None self._edge_is_mapped = None self._mapped_colors = None self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color']) self.set_facecolor(facecolors) self.set_edgecolor(edgecolors) self.set_linewidth(linewidths) self.set_linestyle(linestyles) self.set_antialiased(antialiaseds) self.set_pickradius(pickradius) self.set_urls(urls) self.set_hatch(hatch) self.set_zorder(zorder) if capstyle: self.set_capstyle(capstyle) else: self._capstyle = None if joinstyle: self.set_joinstyle(joinstyle) else: self._joinstyle = None if offsets is not None: offsets = np.asanyarray(offsets, float) if offsets.shape == (2,): offsets = offsets[None, :] self._offsets = offsets self._offset_transform = offset_transform self._path_effects = None self._internal_update(kwargs) self._paths = None def get_paths(self): return self._paths def set_paths(self, paths): self._paths = paths self.stale = True def get_transforms(self): return self._transforms def get_offset_transform(self): if self._offset_transform is None: self._offset_transform = transforms.IdentityTransform() elif not isinstance(self._offset_transform, transforms.Transform) and hasattr(self._offset_transform, '_as_mpl_transform'): self._offset_transform = self._offset_transform._as_mpl_transform(self.axes) return self._offset_transform def set_offset_transform(self, offset_transform): self._offset_transform = offset_transform def get_datalim(self, transData): transform = self.get_transform() offset_trf = self.get_offset_transform() if not (isinstance(offset_trf, transforms.IdentityTransform) or offset_trf.contains_branch(transData)): return transforms.Bbox.null() paths = self.get_paths() if not len(paths): return transforms.Bbox.null() if not transform.is_affine: paths = [transform.transform_path_non_affine(p) for p in paths] offsets = self.get_offsets() if any(transform.contains_branch_seperately(transData)): if isinstance(offsets, np.ma.MaskedArray): offsets = offsets.filled(np.nan) return mpath.get_path_collection_extents(transform.get_affine() - transData, paths, self.get_transforms(), offset_trf.transform_non_affine(offsets), offset_trf.get_affine().frozen()) if self._offsets is not None: offsets = (offset_trf - transData).transform(offsets) offsets = np.ma.masked_invalid(offsets) if not offsets.mask.all(): bbox = transforms.Bbox.null() bbox.update_from_data_xy(offsets) return bbox return transforms.Bbox.null() def get_window_extent(self, renderer=None): return self.get_datalim(transforms.IdentityTransform()) def _prepare_points(self): transform = self.get_transform() offset_trf = self.get_offset_transform() offsets = self.get_offsets() paths = self.get_paths() if self.have_units(): paths = [] for path in self.get_paths(): vertices = path.vertices (xs, ys) = (vertices[:, 0], vertices[:, 1]) xs = self.convert_xunits(xs) ys = self.convert_yunits(ys) paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes)) xs = self.convert_xunits(offsets[:, 0]) ys = self.convert_yunits(offsets[:, 1]) offsets = np.ma.column_stack([xs, ys]) if not transform.is_affine: paths = [transform.transform_path_non_affine(path) for path in paths] transform = transform.get_affine() if not offset_trf.is_affine: offsets = offset_trf.transform_non_affine(offsets) offset_trf = offset_trf.get_affine() if isinstance(offsets, np.ma.MaskedArray): offsets = offsets.filled(np.nan) return (transform, offset_trf, offsets, paths) @artist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group(self.__class__.__name__, self.get_gid()) self.update_scalarmappable() (transform, offset_trf, offsets, paths) = self._prepare_points() gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_snap(self.get_snap()) if self._hatch: gc.set_hatch(self._hatch) gc.set_hatch_color(self._hatch_color) if self.get_sketch_params() is not None: gc.set_sketch_params(*self.get_sketch_params()) if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer) trans = self.get_transforms() facecolors = self.get_facecolor() edgecolors = self.get_edgecolor() do_single_path_optimization = False if len(paths) == 1 and len(trans) <= 1 and (len(facecolors) == 1) and (len(edgecolors) == 1) and (len(self._linewidths) == 1) and all((ls[1] is None for ls in self._linestyles)) and (len(self._antialiaseds) == 1) and (len(self._urls) == 1) and (self.get_hatch() is None): if len(trans): combined_transform = transforms.Affine2D(trans[0]) + transform else: combined_transform = transform extents = paths[0].get_extents(combined_transform) if extents.width < self.get_figure(root=True).bbox.width and extents.height < self.get_figure(root=True).bbox.height: do_single_path_optimization = True if self._joinstyle: gc.set_joinstyle(self._joinstyle) if self._capstyle: gc.set_capstyle(self._capstyle) if do_single_path_optimization: gc.set_foreground(tuple(edgecolors[0])) gc.set_linewidth(self._linewidths[0]) gc.set_dashes(*self._linestyles[0]) gc.set_antialiased(self._antialiaseds[0]) gc.set_url(self._urls[0]) renderer.draw_markers(gc, paths[0], combined_transform.frozen(), mpath.Path(offsets), offset_trf, tuple(facecolors[0])) else: if self._gapcolor is not None: (ipaths, ilinestyles) = self._get_inverse_paths_linestyles() renderer.draw_path_collection(gc, transform.frozen(), ipaths, self.get_transforms(), offsets, offset_trf, [mcolors.to_rgba('none')], self._gapcolor, self._linewidths, ilinestyles, self._antialiaseds, self._urls, 'screen') renderer.draw_path_collection(gc, transform.frozen(), paths, self.get_transforms(), offsets, offset_trf, self.get_facecolor(), self.get_edgecolor(), self._linewidths, self._linestyles, self._antialiaseds, self._urls, 'screen') gc.restore() renderer.close_group(self.__class__.__name__) self.stale = False def set_pickradius(self, pickradius): if not isinstance(pickradius, Real): raise ValueError(f'pickradius must be a real-valued number, not {pickradius!r}') self._pickradius = pickradius def get_pickradius(self): return self._pickradius def contains(self, mouseevent): if self._different_canvas(mouseevent) or not self.get_visible(): return (False, {}) pickradius = float(self._picker) if isinstance(self._picker, Number) and self._picker is not True else self._pickradius if self.axes: self.axes._unstale_viewLim() (transform, offset_trf, offsets, paths) = self._prepare_points() ind = _path.point_in_path_collection(mouseevent.x, mouseevent.y, pickradius, transform.frozen(), paths, self.get_transforms(), offsets, offset_trf, pickradius <= 0) return (len(ind) > 0, dict(ind=ind)) def set_urls(self, urls): self._urls = urls if urls is not None else [None] self.stale = True def get_urls(self): return self._urls def set_hatch(self, hatch): mhatch._validate_hatch_pattern(hatch) self._hatch = hatch self.stale = True def get_hatch(self): return self._hatch def set_offsets(self, offsets): offsets = np.asanyarray(offsets) if offsets.shape == (2,): offsets = offsets[None, :] cstack = np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray) else np.column_stack self._offsets = cstack((np.asanyarray(self.convert_xunits(offsets[:, 0]), float), np.asanyarray(self.convert_yunits(offsets[:, 1]), float))) self.stale = True def get_offsets(self): return np.zeros((1, 2)) if self._offsets is None else self._offsets def _get_default_linewidth(self): return mpl.rcParams['patch.linewidth'] def set_linewidth(self, lw): if lw is None: lw = self._get_default_linewidth() self._us_lw = np.atleast_1d(lw) (self._linewidths, self._linestyles) = self._bcast_lwls(self._us_lw, self._us_linestyles) self.stale = True def set_linestyle(self, ls): try: dashes = [mlines._get_dash_pattern(ls)] except ValueError: try: dashes = [mlines._get_dash_pattern(x) for x in ls] except ValueError as err: emsg = f'Do not know how to convert {ls!r} to dashes' raise ValueError(emsg) from err self._us_linestyles = dashes (self._linewidths, self._linestyles) = self._bcast_lwls(self._us_lw, self._us_linestyles) @_docstring.interpd def set_capstyle(self, cs): self._capstyle = CapStyle(cs) @_docstring.interpd def get_capstyle(self): return self._capstyle.name if self._capstyle else None @_docstring.interpd def set_joinstyle(self, js): self._joinstyle = JoinStyle(js) @_docstring.interpd def get_joinstyle(self): return self._joinstyle.name if self._joinstyle else None @staticmethod def _bcast_lwls(linewidths, dashes): if mpl.rcParams['_internal.classic_mode']: return (linewidths, dashes) if len(dashes) != len(linewidths): l_dashes = len(dashes) l_lw = len(linewidths) gcd = math.gcd(l_dashes, l_lw) dashes = list(dashes) * (l_lw // gcd) linewidths = list(linewidths) * (l_dashes // gcd) dashes = [mlines._scale_dashes(o, d, lw) for ((o, d), lw) in zip(dashes, linewidths)] return (linewidths, dashes) def get_antialiased(self): return self._antialiaseds def set_antialiased(self, aa): if aa is None: aa = self._get_default_antialiased() self._antialiaseds = np.atleast_1d(np.asarray(aa, bool)) self.stale = True def _get_default_antialiased(self): return mpl.rcParams['patch.antialiased'] def set_color(self, c): self.set_facecolor(c) self.set_edgecolor(c) def _get_default_facecolor(self): return mpl.rcParams['patch.facecolor'] def _set_facecolor(self, c): if c is None: c = self._get_default_facecolor() self._facecolors = mcolors.to_rgba_array(c, self._alpha) self.stale = True def set_facecolor(self, c): if isinstance(c, str) and c.lower() in ('none', 'face'): c = c.lower() self._original_facecolor = c self._set_facecolor(c) def get_facecolor(self): return self._facecolors def get_edgecolor(self): if cbook._str_equal(self._edgecolors, 'face'): return self.get_facecolor() else: return self._edgecolors def _get_default_edgecolor(self): return mpl.rcParams['patch.edgecolor'] def _set_edgecolor(self, c): set_hatch_color = True if c is None: if mpl.rcParams['patch.force_edgecolor'] or self._edge_default or cbook._str_equal(self._original_facecolor, 'none'): c = self._get_default_edgecolor() else: c = 'none' set_hatch_color = False if cbook._str_lower_equal(c, 'face'): self._edgecolors = 'face' self.stale = True return self._edgecolors = mcolors.to_rgba_array(c, self._alpha) if set_hatch_color and len(self._edgecolors): self._hatch_color = tuple(self._edgecolors[0]) self.stale = True def set_edgecolor(self, c): if isinstance(c, str) and c.lower() in ('none', 'face'): c = c.lower() self._original_edgecolor = c self._set_edgecolor(c) def set_alpha(self, alpha): artist.Artist._set_alpha_for_array(self, alpha) self._set_facecolor(self._original_facecolor) self._set_edgecolor(self._original_edgecolor) set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__ def get_linewidth(self): return self._linewidths def get_linestyle(self): return self._linestyles def _set_mappable_flags(self): edge0 = self._edge_is_mapped face0 = self._face_is_mapped self._edge_is_mapped = False self._face_is_mapped = False if self._A is not None: if not cbook._str_equal(self._original_facecolor, 'none'): self._face_is_mapped = True if cbook._str_equal(self._original_edgecolor, 'face'): self._edge_is_mapped = True elif self._original_edgecolor is None: self._edge_is_mapped = True mapped = self._face_is_mapped or self._edge_is_mapped changed = edge0 is None or face0 is None or self._edge_is_mapped != edge0 or (self._face_is_mapped != face0) return mapped or changed def update_scalarmappable(self): if not self._set_mappable_flags(): return if self._A is not None: if self._A.ndim > 1 and (not isinstance(self, _MeshData)): raise ValueError('Collections can only map rank 1 arrays') if np.iterable(self._alpha): if self._alpha.size != self._A.size: raise ValueError(f'Data array shape, {self._A.shape} is incompatible with alpha array shape, {self._alpha.shape}. This can occur with the deprecated behavior of the "flat" shading option, in which a row and/or column of the data array is dropped.') self._alpha = self._alpha.reshape(self._A.shape) self._mapped_colors = self.to_rgba(self._A, self._alpha) if self._face_is_mapped: self._facecolors = self._mapped_colors else: self._set_facecolor(self._original_facecolor) if self._edge_is_mapped: self._edgecolors = self._mapped_colors else: self._set_edgecolor(self._original_edgecolor) self.stale = True def get_fill(self): return not cbook._str_lower_equal(self._original_facecolor, 'none') def update_from(self, other): artist.Artist.update_from(self, other) self._antialiaseds = other._antialiaseds self._mapped_colors = other._mapped_colors self._edge_is_mapped = other._edge_is_mapped self._original_edgecolor = other._original_edgecolor self._edgecolors = other._edgecolors self._face_is_mapped = other._face_is_mapped self._original_facecolor = other._original_facecolor self._facecolors = other._facecolors self._linewidths = other._linewidths self._linestyles = other._linestyles self._us_linestyles = other._us_linestyles self._pickradius = other._pickradius self._hatch = other._hatch self._A = other._A self.norm = other.norm self.cmap = other.cmap self.stale = True class _CollectionWithSizes(Collection): _factor = 1.0 def get_sizes(self): return self._sizes def set_sizes(self, sizes, dpi=72.0): if sizes is None: self._sizes = np.array([]) self._transforms = np.empty((0, 3, 3)) else: self._sizes = np.asarray(sizes) self._transforms = np.zeros((len(self._sizes), 3, 3)) scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor self._transforms[:, 0, 0] = scale self._transforms[:, 1, 1] = scale self._transforms[:, 2, 2] = 1.0 self.stale = True @artist.allow_rasterization def draw(self, renderer): self.set_sizes(self._sizes, self.get_figure(root=True).dpi) super().draw(renderer) class PathCollection(_CollectionWithSizes): def __init__(self, paths, sizes=None, **kwargs): super().__init__(**kwargs) self.set_paths(paths) self.set_sizes(sizes) self.stale = True def get_paths(self): return self._paths def legend_elements(self, prop='colors', num='auto', fmt=None, func=lambda x: x, **kwargs): handles = [] labels = [] hasarray = self.get_array() is not None if fmt is None: fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True) elif isinstance(fmt, str): fmt = mpl.ticker.StrMethodFormatter(fmt) fmt.create_dummy_axis() if prop == 'colors': if not hasarray: warnings.warn('Collection without array used. Make sure to specify the values to be colormapped via the `c` argument.') return (handles, labels) u = np.unique(self.get_array()) size = kwargs.pop('size', mpl.rcParams['lines.markersize']) elif prop == 'sizes': u = np.unique(self.get_sizes()) color = kwargs.pop('color', 'k') else: raise ValueError(f"Valid values for `prop` are 'colors' or 'sizes'. You supplied '{prop}' instead.") fu = func(u) fmt.axis.set_view_interval(fu.min(), fu.max()) fmt.axis.set_data_interval(fu.min(), fu.max()) if num == 'auto': num = 9 if len(u) <= num: num = None if num is None: values = u label_values = func(values) else: if prop == 'colors': arr = self.get_array() elif prop == 'sizes': arr = self.get_sizes() if isinstance(num, mpl.ticker.Locator): loc = num elif np.iterable(num): loc = mpl.ticker.FixedLocator(num) else: num = int(num) loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num - 1, steps=[1, 2, 2.5, 3, 5, 6, 8, 10]) label_values = loc.tick_values(func(arr).min(), func(arr).max()) cond = (label_values >= func(arr).min()) & (label_values <= func(arr).max()) label_values = label_values[cond] yarr = np.linspace(arr.min(), arr.max(), 256) xarr = func(yarr) ix = np.argsort(xarr) values = np.interp(label_values, xarr[ix], yarr[ix]) kw = {'markeredgewidth': self.get_linewidths()[0], 'alpha': self.get_alpha(), **kwargs} for (val, lab) in zip(values, label_values): if prop == 'colors': color = self.cmap(self.norm(val)) elif prop == 'sizes': size = np.sqrt(val) if np.isclose(size, 0.0): continue h = mlines.Line2D([0], [0], ls='', color=color, ms=size, marker=self.get_paths()[0], **kw) handles.append(h) if hasattr(fmt, 'set_locs'): fmt.set_locs(label_values) l = fmt(lab) labels.append(l) return (handles, labels) class PolyCollection(_CollectionWithSizes): def __init__(self, verts, sizes=None, *, closed=True, **kwargs): super().__init__(**kwargs) self.set_sizes(sizes) self.set_verts(verts, closed) self.stale = True def set_verts(self, verts, closed=True): self.stale = True if isinstance(verts, np.ma.MaskedArray): verts = verts.astype(float).filled(np.nan) if not closed: self._paths = [mpath.Path(xy) for xy in verts] return if isinstance(verts, np.ndarray) and len(verts.shape) == 3: verts_pad = np.concatenate((verts, verts[:, :1]), axis=1) codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type) codes[:] = mpath.Path.LINETO codes[0] = mpath.Path.MOVETO codes[-1] = mpath.Path.CLOSEPOLY self._paths = [mpath.Path(xy, codes) for xy in verts_pad] return self._paths = [] for xy in verts: if len(xy): self._paths.append(mpath.Path._create_closed(xy)) else: self._paths.append(mpath.Path(xy)) set_paths = set_verts def set_verts_and_codes(self, verts, codes): if len(verts) != len(codes): raise ValueError("'codes' must be a 1D list or array with the same length of 'verts'") self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy) for (xy, cds) in zip(verts, codes)] self.stale = True class RegularPolyCollection(_CollectionWithSizes): _path_generator = mpath.Path.unit_regular_polygon _factor = np.pi ** (-1 / 2) def __init__(self, numsides, *, rotation=0, sizes=(1,), **kwargs): super().__init__(**kwargs) self.set_sizes(sizes) self._numsides = numsides self._paths = [self._path_generator(numsides)] self._rotation = rotation self.set_transform(transforms.IdentityTransform()) def get_numsides(self): return self._numsides def get_rotation(self): return self._rotation @artist.allow_rasterization def draw(self, renderer): self.set_sizes(self._sizes, self.get_figure(root=True).dpi) self._transforms = [transforms.Affine2D(x).rotate(-self._rotation).get_matrix() for x in self._transforms] Collection.draw(self, renderer) class StarPolygonCollection(RegularPolyCollection): _path_generator = mpath.Path.unit_regular_star class AsteriskPolygonCollection(RegularPolyCollection): _path_generator = mpath.Path.unit_regular_asterisk class LineCollection(Collection): _edge_default = True def __init__(self, segments, *, zorder=2, **kwargs): kwargs.setdefault('facecolors', 'none') super().__init__(zorder=zorder, **kwargs) self.set_segments(segments) def set_segments(self, segments): if segments is None: return self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray) else mpath.Path(np.asarray(seg, float)) for seg in segments] self.stale = True set_verts = set_segments set_paths = set_segments def get_segments(self): segments = [] for path in self._paths: vertices = [vertex for (vertex, _) in path.iter_segments(simplify=False)] vertices = np.asarray(vertices) segments.append(vertices) return segments def _get_default_linewidth(self): return mpl.rcParams['lines.linewidth'] def _get_default_antialiased(self): return mpl.rcParams['lines.antialiased'] def _get_default_edgecolor(self): return mpl.rcParams['lines.color'] def _get_default_facecolor(self): return 'none' def set_alpha(self, alpha): super().set_alpha(alpha) if self._gapcolor is not None: self.set_gapcolor(self._original_gapcolor) def set_color(self, c): self.set_edgecolor(c) set_colors = set_color def get_color(self): return self._edgecolors get_colors = get_color def set_gapcolor(self, gapcolor): self._original_gapcolor = gapcolor self._set_gapcolor(gapcolor) def _set_gapcolor(self, gapcolor): if gapcolor is not None: gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha) self._gapcolor = gapcolor self.stale = True def get_gapcolor(self): return self._gapcolor def _get_inverse_paths_linestyles(self): path_patterns = [(mpath.Path(np.full((1, 2), np.nan)), ls) if ls == (0, None) else (path, mlines._get_inverse_dash_pattern(*ls)) for (path, ls) in zip(self._paths, itertools.cycle(self._linestyles))] return zip(*path_patterns) class EventCollection(LineCollection): _edge_default = True def __init__(self, positions, orientation='horizontal', *, lineoffset=0, linelength=1, linewidth=None, color=None, linestyle='solid', antialiased=None, **kwargs): super().__init__([], linewidths=linewidth, linestyles=linestyle, colors=color, antialiaseds=antialiased, **kwargs) self._is_horizontal = True self._linelength = linelength self._lineoffset = lineoffset self.set_orientation(orientation) self.set_positions(positions) def get_positions(self): pos = 0 if self.is_horizontal() else 1 return [segment[0, pos] for segment in self.get_segments()] def set_positions(self, positions): if positions is None: positions = [] if np.ndim(positions) != 1: raise ValueError('positions must be one-dimensional') lineoffset = self.get_lineoffset() linelength = self.get_linelength() pos_idx = 0 if self.is_horizontal() else 1 segments = np.empty((len(positions), 2, 2)) segments[:, :, pos_idx] = np.sort(positions)[:, None] segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2 segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2 self.set_segments(segments) def add_positions(self, position): if position is None or (hasattr(position, 'len') and len(position) == 0): return positions = self.get_positions() positions = np.hstack([positions, np.asanyarray(position)]) self.set_positions(positions) extend_positions = append_positions = add_positions def is_horizontal(self): return self._is_horizontal def get_orientation(self): return 'horizontal' if self.is_horizontal() else 'vertical' def switch_orientation(self): segments = self.get_segments() for (i, segment) in enumerate(segments): segments[i] = np.fliplr(segment) self.set_segments(segments) self._is_horizontal = not self.is_horizontal() self.stale = True def set_orientation(self, orientation): is_horizontal = _api.check_getitem({'horizontal': True, 'vertical': False}, orientation=orientation) if is_horizontal == self.is_horizontal(): return self.switch_orientation() def get_linelength(self): return self._linelength def set_linelength(self, linelength): if linelength == self.get_linelength(): return lineoffset = self.get_lineoffset() segments = self.get_segments() pos = 1 if self.is_horizontal() else 0 for segment in segments: segment[0, pos] = lineoffset + linelength / 2.0 segment[1, pos] = lineoffset - linelength / 2.0 self.set_segments(segments) self._linelength = linelength def get_lineoffset(self): return self._lineoffset def set_lineoffset(self, lineoffset): if lineoffset == self.get_lineoffset(): return linelength = self.get_linelength() segments = self.get_segments() pos = 1 if self.is_horizontal() else 0 for segment in segments: segment[0, pos] = lineoffset + linelength / 2.0 segment[1, pos] = lineoffset - linelength / 2.0 self.set_segments(segments) self._lineoffset = lineoffset def get_linewidth(self): return super().get_linewidth()[0] def get_linewidths(self): return super().get_linewidth() def get_color(self): return self.get_colors()[0] class CircleCollection(_CollectionWithSizes): _factor = np.pi ** (-1 / 2) def __init__(self, sizes, **kwargs): super().__init__(**kwargs) self.set_sizes(sizes) self.set_transform(transforms.IdentityTransform()) self._paths = [mpath.Path.unit_circle()] class EllipseCollection(Collection): def __init__(self, widths, heights, angles, *, units='points', **kwargs): super().__init__(**kwargs) self.set_widths(widths) self.set_heights(heights) self.set_angles(angles) self._units = units self.set_transform(transforms.IdentityTransform()) self._transforms = np.empty((0, 3, 3)) self._paths = [mpath.Path.unit_circle()] def _set_transforms(self): ax = self.axes fig = self.get_figure(root=False) if self._units == 'xy': sc = 1 elif self._units == 'x': sc = ax.bbox.width / ax.viewLim.width elif self._units == 'y': sc = ax.bbox.height / ax.viewLim.height elif self._units == 'inches': sc = fig.dpi elif self._units == 'points': sc = fig.dpi / 72.0 elif self._units == 'width': sc = ax.bbox.width elif self._units == 'height': sc = ax.bbox.height elif self._units == 'dots': sc = 1.0 else: raise ValueError(f'Unrecognized units: {self._units!r}') self._transforms = np.zeros((len(self._widths), 3, 3)) widths = self._widths * sc heights = self._heights * sc sin_angle = np.sin(self._angles) cos_angle = np.cos(self._angles) self._transforms[:, 0, 0] = widths * cos_angle self._transforms[:, 0, 1] = heights * -sin_angle self._transforms[:, 1, 0] = widths * sin_angle self._transforms[:, 1, 1] = heights * cos_angle self._transforms[:, 2, 2] = 1.0 _affine = transforms.Affine2D if self._units == 'xy': m = ax.transData.get_affine().get_matrix().copy() m[:2, 2:] = 0 self.set_transform(_affine(m)) def set_widths(self, widths): self._widths = 0.5 * np.asarray(widths).ravel() self.stale = True def set_heights(self, heights): self._heights = 0.5 * np.asarray(heights).ravel() self.stale = True def set_angles(self, angles): self._angles = np.deg2rad(angles).ravel() self.stale = True def get_widths(self): return self._widths * 2 def get_heights(self): return self._heights * 2 def get_angles(self): return np.rad2deg(self._angles) @artist.allow_rasterization def draw(self, renderer): self._set_transforms() super().draw(renderer) class PatchCollection(Collection): def __init__(self, patches, *, match_original=False, **kwargs): if match_original: def determine_facecolor(patch): if patch.get_fill(): return patch.get_facecolor() return [0, 0, 0, 0] kwargs['facecolors'] = [determine_facecolor(p) for p in patches] kwargs['edgecolors'] = [p.get_edgecolor() for p in patches] kwargs['linewidths'] = [p.get_linewidth() for p in patches] kwargs['linestyles'] = [p.get_linestyle() for p in patches] kwargs['antialiaseds'] = [p.get_antialiased() for p in patches] super().__init__(**kwargs) self.set_paths(patches) def set_paths(self, patches): paths = [p.get_transform().transform_path(p.get_path()) for p in patches] self._paths = paths class TriMesh(Collection): def __init__(self, triangulation, **kwargs): super().__init__(**kwargs) self._triangulation = triangulation self._shading = 'gouraud' self._bbox = transforms.Bbox.unit() xy = np.hstack((triangulation.x.reshape(-1, 1), triangulation.y.reshape(-1, 1))) self._bbox.update_from_data_xy(xy) def get_paths(self): if self._paths is None: self.set_paths() return self._paths def set_paths(self): self._paths = self.convert_mesh_to_paths(self._triangulation) @staticmethod def convert_mesh_to_paths(tri): triangles = tri.get_masked_triangles() verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1) return [mpath.Path(x) for x in verts] @artist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group(self.__class__.__name__, gid=self.get_gid()) transform = self.get_transform() tri = self._triangulation triangles = tri.get_masked_triangles() verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1) self.update_scalarmappable() colors = self._facecolors[triangles] gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_linewidth(self.get_linewidth()[0]) renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen()) gc.restore() renderer.close_group(self.__class__.__name__) class _MeshData: def __init__(self, coordinates, *, shading='flat'): _api.check_shape((None, None, 2), coordinates=coordinates) self._coordinates = coordinates self._shading = shading def set_array(self, A): (height, width) = self._coordinates.shape[0:-1] if self._shading == 'flat': (h, w) = (height - 1, width - 1) else: (h, w) = (height, width) ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)] if A is not None: shape = np.shape(A) if shape not in ok_shapes: raise ValueError(f"For X ({width}) and Y ({height}) with {self._shading} shading, A should have shape {' or '.join(map(str, ok_shapes))}, not {A.shape}") return super().set_array(A) def get_coordinates(self): return self._coordinates def get_edgecolor(self): return super().get_edgecolor().reshape(-1, 4) def get_facecolor(self): return super().get_facecolor().reshape(-1, 4) @staticmethod def _convert_mesh_to_paths(coordinates): if isinstance(coordinates, np.ma.MaskedArray): c = coordinates.data else: c = coordinates points = np.concatenate([c[:-1, :-1], c[:-1, 1:], c[1:, 1:], c[1:, :-1], c[:-1, :-1]], axis=2).reshape((-1, 5, 2)) return [mpath.Path(x) for x in points] def _convert_mesh_to_triangles(self, coordinates): if isinstance(coordinates, np.ma.MaskedArray): p = coordinates.data else: p = coordinates p_a = p[:-1, :-1] p_b = p[:-1, 1:] p_c = p[1:, 1:] p_d = p[1:, :-1] p_center = (p_a + p_b + p_c + p_d) / 4.0 triangles = np.concatenate([p_a, p_b, p_center, p_b, p_c, p_center, p_c, p_d, p_center, p_d, p_a, p_center], axis=2).reshape((-1, 3, 2)) c = self.get_facecolor().reshape((*coordinates.shape[:2], 4)) z = self.get_array() mask = z.mask if np.ma.is_masked(z) else None if mask is not None: c[mask, 3] = np.nan c_a = c[:-1, :-1] c_b = c[:-1, 1:] c_c = c[1:, 1:] c_d = c[1:, :-1] c_center = (c_a + c_b + c_c + c_d) / 4.0 colors = np.concatenate([c_a, c_b, c_center, c_b, c_c, c_center, c_c, c_d, c_center, c_d, c_a, c_center], axis=2).reshape((-1, 3, 4)) tmask = np.isnan(colors[..., 2, 3]) return (triangles[~tmask], colors[~tmask]) class QuadMesh(_MeshData, Collection): def __init__(self, coordinates, *, antialiased=True, shading='flat', **kwargs): kwargs.setdefault('pickradius', 0) super().__init__(coordinates=coordinates, shading=shading) Collection.__init__(self, **kwargs) self._antialiased = antialiased self._bbox = transforms.Bbox.unit() self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2)) self.set_mouseover(False) def get_paths(self): if self._paths is None: self.set_paths() return self._paths def set_paths(self): self._paths = self._convert_mesh_to_paths(self._coordinates) self.stale = True def get_datalim(self, transData): return (self.get_transform() - transData).transform_bbox(self._bbox) @artist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group(self.__class__.__name__, self.get_gid()) transform = self.get_transform() offset_trf = self.get_offset_transform() offsets = self.get_offsets() if self.have_units(): xs = self.convert_xunits(offsets[:, 0]) ys = self.convert_yunits(offsets[:, 1]) offsets = np.column_stack([xs, ys]) self.update_scalarmappable() if not transform.is_affine: coordinates = self._coordinates.reshape((-1, 2)) coordinates = transform.transform(coordinates) coordinates = coordinates.reshape(self._coordinates.shape) transform = transforms.IdentityTransform() else: coordinates = self._coordinates if not offset_trf.is_affine: offsets = offset_trf.transform_non_affine(offsets) offset_trf = offset_trf.get_affine() gc = renderer.new_gc() gc.set_snap(self.get_snap()) self._set_gc_clip(gc) gc.set_linewidth(self.get_linewidth()[0]) if self._shading == 'gouraud': (triangles, colors) = self._convert_mesh_to_triangles(coordinates) renderer.draw_gouraud_triangles(gc, triangles, colors, transform.frozen()) else: renderer.draw_quad_mesh(gc, transform.frozen(), coordinates.shape[1] - 1, coordinates.shape[0] - 1, coordinates, offsets, offset_trf, self.get_facecolor().reshape((-1, 4)), self._antialiased, self.get_edgecolors().reshape((-1, 4))) gc.restore() renderer.close_group(self.__class__.__name__) self.stale = False def get_cursor_data(self, event): (contained, info) = self.contains(event) if contained and self.get_array() is not None: return self.get_array().ravel()[info['ind']] return None class PolyQuadMesh(_MeshData, PolyCollection): def __init__(self, coordinates, **kwargs): super().__init__(coordinates=coordinates) PolyCollection.__init__(self, verts=[], **kwargs) self._set_unmasked_verts() def _get_unmasked_polys(self): mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1) mask = mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1] arr = self.get_array() if arr is not None: arr = np.ma.getmaskarray(arr) if arr.ndim == 3: mask |= np.any(arr, axis=-1) elif arr.ndim == 2: mask |= arr else: mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2]) return ~mask def _set_unmasked_verts(self): X = self._coordinates[..., 0] Y = self._coordinates[..., 1] unmask = self._get_unmasked_polys() X1 = np.ma.filled(X[:-1, :-1])[unmask] Y1 = np.ma.filled(Y[:-1, :-1])[unmask] X2 = np.ma.filled(X[1:, :-1])[unmask] Y2 = np.ma.filled(Y[1:, :-1])[unmask] X3 = np.ma.filled(X[1:, 1:])[unmask] Y3 = np.ma.filled(Y[1:, 1:])[unmask] X4 = np.ma.filled(X[:-1, 1:])[unmask] Y4 = np.ma.filled(Y[:-1, 1:])[unmask] npoly = len(X1) xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1) verts = xy.reshape((npoly, 5, 2)) self.set_verts(verts) def get_edgecolor(self): ec = super().get_edgecolor() unmasked_polys = self._get_unmasked_polys().ravel() if len(ec) != len(unmasked_polys): return ec return ec[unmasked_polys, :] def get_facecolor(self): fc = super().get_facecolor() unmasked_polys = self._get_unmasked_polys().ravel() if len(fc) != len(unmasked_polys): return fc return fc[unmasked_polys, :] def set_array(self, A): prev_unmask = self._get_unmasked_polys() super().set_array(A) if not np.array_equal(prev_unmask, self._get_unmasked_polys()): self._set_unmasked_verts() # File: matplotlib-main/lib/matplotlib/colorbar.py """""" import logging import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, collections, cm, colors, contour, ticker import matplotlib.artist as martist import matplotlib.patches as mpatches import matplotlib.path as mpath import matplotlib.spines as mspines import matplotlib.transforms as mtransforms from matplotlib import _docstring _log = logging.getLogger(__name__) _docstring.interpd.update(_make_axes_kw_doc="\nlocation : None or {'left', 'right', 'top', 'bottom'}\n The location, relative to the parent Axes, where the colorbar Axes\n is created. It also determines the *orientation* of the colorbar\n (colorbars on the left and right are vertical, colorbars at the top\n and bottom are horizontal). If None, the location will come from the\n *orientation* if it is set (vertical colorbars on the right, horizontal\n ones at the bottom), or default to 'right' if *orientation* is unset.\n\norientation : None or {'vertical', 'horizontal'}\n The orientation of the colorbar. It is preferable to set the *location*\n of the colorbar, as that also determines the *orientation*; passing\n incompatible values for *location* and *orientation* raises an exception.\n\nfraction : float, default: 0.15\n Fraction of original Axes to use for colorbar.\n\nshrink : float, default: 1.0\n Fraction by which to multiply the size of the colorbar.\n\naspect : float, default: 20\n Ratio of long to short dimensions.\n\npad : float, default: 0.05 if vertical, 0.15 if horizontal\n Fraction of original Axes between colorbar and new image Axes.\n\nanchor : (float, float), optional\n The anchor point of the colorbar Axes.\n Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.\n\npanchor : (float, float), or *False*, optional\n The anchor point of the colorbar parent Axes. If *False*, the parent\n axes' anchor will be unchanged.\n Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.", _colormap_kw_doc='\nextend : {\'neither\', \'both\', \'min\', \'max\'}\n Make pointed end(s) for out-of-range values (unless \'neither\'). These are\n set for a given colormap using the colormap set_under and set_over methods.\n\nextendfrac : {*None*, \'auto\', length, lengths}\n If set to *None*, both the minimum and maximum triangular colorbar\n extensions will have a length of 5% of the interior colorbar length (this\n is the default setting).\n\n If set to \'auto\', makes the triangular colorbar extensions the same lengths\n as the interior boxes (when *spacing* is set to \'uniform\') or the same\n lengths as the respective adjacent interior boxes (when *spacing* is set to\n \'proportional\').\n\n If a scalar, indicates the length of both the minimum and maximum\n triangular colorbar extensions as a fraction of the interior colorbar\n length. A two-element sequence of fractions may also be given, indicating\n the lengths of the minimum and maximum colorbar extensions respectively as\n a fraction of the interior colorbar length.\n\nextendrect : bool\n If *False* the minimum and maximum colorbar extensions will be triangular\n (the default). If *True* the extensions will be rectangular.\n\nspacing : {\'uniform\', \'proportional\'}\n For discrete colorbars (`.BoundaryNorm` or contours), \'uniform\' gives each\n color the same space; \'proportional\' makes the space proportional to the\n data interval.\n\nticks : None or list of ticks or Locator\n If None, ticks are determined automatically from the input.\n\nformat : None or str or Formatter\n If None, `~.ticker.ScalarFormatter` is used.\n Format strings, e.g., ``"%4.2e"`` or ``"{x:.2e}"``, are supported.\n An alternative `~.ticker.Formatter` may be given instead.\n\ndrawedges : bool\n Whether to draw lines at color boundaries.\n\nlabel : str\n The label on the colorbar\'s long axis.\n\nboundaries, values : None or a sequence\n If unset, the colormap will be displayed on a 0-1 scale.\n If sequences, *values* must have a length 1 less than *boundaries*. For\n each region delimited by adjacent entries in *boundaries*, the color mapped\n to the corresponding value in values will be used.\n Normally only useful for indexed colors (i.e. ``norm=NoNorm()``) or other\n unusual circumstances.') def _set_ticks_on_axis_warn(*args, **kwargs): _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): 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: 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 if hasattr(ax, '_colorbar_info'): aspect = ax._colorbar_info['aspect'] else: aspect = False 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): return self._cbar.ax.get_subplotspec() or getattr(self._orig_locator, 'get_subplotspec', lambda : None)() @_docstring.interpd class Colorbar: n_rasterize = 50 def __init__(self, ax, mappable=None, *, cmap=None, norm=None, alpha=None, values=None, boundaries=None, orientation=None, ticklocation='auto', extend=None, spacing='uniform', ticks=None, format=None, drawedges=False, extendfrac=None, extendrect=False, label='', location=None): 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 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): try: self._formatter = ticker.FormatStrFormatter(format) _ = self._formatter(0) except (TypeError, ValueError): self._formatter = ticker.StrMethodFormatter(format) else: self._formatter = format self._draw_all() if isinstance(mappable, contour.ContourSet) and (not mappable.filled): self.add_lines(mappable) self.ax._colorbar = self if isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or isinstance(self.mappable, contour.ContourSet): self.ax.set_navigate(False) 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)) self.ax.cla = self._cbar_cla 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 locator(self): 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): 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): 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): 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): for x in self._interactive_funcs: delattr(self.ax, x) del self.ax.cla self.ax.cla() def update_normal(self, mappable): _log.debug('colorbar update normal %r %r', mappable.norm, self.norm) self.mappable = mappable self.set_alpha(mappable.get_alpha()) self.cmap = mappable.cmap if mappable.norm != self.norm: self.norm = 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): if self.orientation == 'vertical': if mpl.rcParams['ytick.minor.visible']: self.minorticks_on() elif 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) self._process_values() (self.vmin, self.vmax) = self._boundaries[self._inside][[0, -1]] (X, Y) = self._mesh() self._do_extends() (lower, upper) = (self.vmin, self.vmax) if self._long_axis().get_inverted(): (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) 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): if self.solids is not None: self.solids.remove() for solid in self.solids_patches: solid.remove() 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 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] 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) if self._extend_lower(): 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): for patch in self._extend_patches: patch.remove() self._extend_patches = [] (_, extendlen) = self._proportional_y() bot = 0 - (extendlen[0] if self._extend_lower() else 0) top = 1 + (extendlen[1] if self._extend_upper() else 0) if not self.extendrect: xyout = np.array([[0, 0], [0.5, bot], [1, 0], [1, 1], [0.5, top], [0, 1], [0, 0]]) else: 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] self.outline.set_xy(xyout) if not self._filled: return 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: xy = np.array([[0, 0], [0.5, bot], [1, 0]]) else: xy = np.array([[0, 0], [0, bot], [1.0, bot], [1, 0]]) if self.orientation == 'horizontal': xy = xy[:, ::-1] 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, zorder=np.nextafter(self.ax.patch.zorder, -np.inf)) self.ax.add_patch(patch) self._extend_patches.append(patch) hatches = hatches[1:] if self._extend_upper(): if not self.extendrect: xy = np.array([[0, 1], [0.5, top], [1, 1]]) else: xy = np.array([[0, 1], [0, top], [1, top], [1, 1]]) if self.orientation == 'horizontal': xy = xy[:, ::-1] 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, 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): 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') 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) 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 xy = inches.inverted().transform(self.ax.transAxes.transform(xy)) xy[[0, 1, 4], 1] -= fac xy[[2, 3], 1] += fac 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): 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): 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: nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0.5) elif self.boundaries is not None: b = self._boundaries[self._inside] if locator is None: locator = ticker.FixedLocator(b, nbins=10) else: if locator is None: 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): 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): if minor: return self._long_axis().get_minorticklocs() else: return self._long_axis().get_majorticklocs() def set_ticklabels(self, ticklabels, *, minor=False, **kwargs): self._long_axis().set_ticklabels(ticklabels, minor=minor, **kwargs) def minorticks_on(self): self.ax.minorticks_on() self._short_axis().set_minor_locator(ticker.NullLocator()) def minorticks_off(self): self._minorlocator = ticker.NullLocator() self._long_axis().set_minor_locator(self._minorlocator) def set_label(self, label, *, loc=None, **kwargs): 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): self.alpha = None if isinstance(alpha, np.ndarray) else alpha def _set_scale(self, scale, **kwargs): self._long_axis()._set_axes_scale(scale, **kwargs) def remove(self): 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 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: pos = ax.get_position(original=True) ax._set_position(pos) else: ax.set_subplotspec(subplotspec) def _process_values(self): if self.values is not None: self._values = np.array(self.values) if self.boundaries is None: 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 if isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries elif isinstance(self.norm, colors.NoNorm): b = np.arange(self.cmap.N + 1) - 0.5 elif self.boundaries is not None: b = self.boundaries else: N = self.cmap.N + 1 (b, _) = self._uniform_y(N) if self._extend_lower(): b = np.hstack((b[0] - 1, b)) if self._extend_upper(): b = np.hstack((b, b[-1] + 1)) if self.mappable.get_array() is not None: self.mappable.autoscale_None() if not self.norm.scaled(): 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 + 1e-05).astype(np.int16) def _mesh(self): (y, _) = self._proportional_y() if isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or self.boundaries is not None: y = y * (self.vmax - self.vmin) + self.vmin else: 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.0, 1.0], y) if self.orientation == 'vertical': return (X, Y) else: return (Y, X) def _forward_boundaries(self, x): b = self._boundaries y = np.interp(x, b, np.linspace(0, 1, len(b))) eps = (b[-1] - b[0]) * 1e-06 y[x < b[0] - eps] = -1 y[x > b[-1] + eps] = 2 return y def _inverse_boundaries(self, x): b = self._boundaries return np.interp(x, np.linspace(0, 1, len(b)), b) def _reset_locator_formatter_scale(self): 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): 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): self._set_scale(self.norm._scale) elif type(self.norm) is colors.Normalize: self._set_scale('linear') else: funcs = (self.norm, self.norm.inverse) self._set_scale('function', functions=funcs) def _locate(self, x): if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)): b = self._boundaries xn = x else: 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 def _uniform_y(self, N): automin = automax = 1.0 / (N - 1.0) 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): 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]) 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) yscaled = y y = y[self._inside] yscaled = yscaled[self._inside] 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) 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): extendlength = np.array([default, default]) if isinstance(frac, str): _api.check_in_list(['auto'], extendfrac=frac.lower()) extendlength[:] = [automin, automax] elif frac is not None: try: extendlength[:] = frac if np.isnan(extendlength).any(): raise ValueError() except (TypeError, ValueError) as err: raise ValueError('invalid value for extendfrac') from err return extendlength def _extend_lower(self): minmax = 'max' if self._long_axis().get_inverted() else 'min' return self.extend in ('both', minmax) def _extend_upper(self): minmax = 'min' if self._long_axis().get_inverted() else 'max' return self.extend in ('both', minmax) def _long_axis(self): if self.orientation == 'vertical': return self.ax.yaxis return self.ax.xaxis def _short_axis(self): if self.orientation == 'vertical': return self.ax.xaxis return self.ax.yaxis def _get_view(self): return (self.norm.vmin, self.norm.vmax) def _set_view(self, view): (self.norm.vmin, self.norm.vmax) = view def _set_view_from_bbox(self, bbox, direction='in', mode=None, twinx=False, twiny=False): (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): 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 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.1}, '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']: 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.interpd def make_axes(parents, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs): loc_settings = _normalize_location_orientation(location, orientation) 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 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.') 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) aspect = 1.0 / aspect shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1) 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='') for a in parents: a._colorbars += [cax] cax._colorbar_info = dict(parents=parents, location=location, shrink=shrink, anchor=anchor, panchor=panchor, fraction=fraction, aspect=aspect0, pad=pad) cax.set_anchor(anchor) cax.set_box_aspect(aspect) cax.set_aspect('auto') return (cax, kwargs) @_docstring.interpd def make_axes_gridspec(parent, *, location=None, orientation=None, fraction=0.15, shrink=1.0, aspect=20, **kwargs): 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='') cax.set_anchor(anchor) cax.set_box_aspect(aspect) cax.set_aspect('auto') cax._colorbar_info = dict(location=location, parents=[parent], shrink=shrink, anchor=anchor, panchor=panchor, fraction=fraction, aspect=aspect0, pad=pad) return (cax, kwargs) # File: matplotlib-main/lib/matplotlib/colors.py """""" import base64 from collections.abc import Sized, Sequence, Mapping import functools import importlib import inspect import io import itertools from numbers import Real import re from PIL import Image from PIL.PngImagePlugin import PngInfo import matplotlib as mpl import numpy as np from matplotlib import _api, _cm, cbook, scale, _image from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS class _ColorMapping(dict): def __init__(self, mapping): super().__init__(mapping) self.cache = {} def __setitem__(self, key, value): super().__setitem__(key, value) self.cache.clear() def __delitem__(self, key): super().__delitem__(key) self.cache.clear() _colors_full_map = {} _colors_full_map.update(XKCD_COLORS) _colors_full_map.update({k.replace('grey', 'gray'): v for (k, v) in XKCD_COLORS.items() if 'grey' in k}) _colors_full_map.update(CSS4_COLORS) _colors_full_map.update(TABLEAU_COLORS) _colors_full_map.update({k.replace('gray', 'grey'): v for (k, v) in TABLEAU_COLORS.items() if 'gray' in k}) _colors_full_map.update(BASE_COLORS) _colors_full_map = _ColorMapping(_colors_full_map) _REPR_PNG_SIZE = (512, 64) _BIVAR_REPR_PNG_SIZE = 256 def get_named_colors_mapping(): return _colors_full_map class ColorSequenceRegistry(Mapping): _BUILTIN_COLOR_SEQUENCES = {'tab10': _cm._tab10_data, 'tab20': _cm._tab20_data, 'tab20b': _cm._tab20b_data, 'tab20c': _cm._tab20c_data, 'Pastel1': _cm._Pastel1_data, 'Pastel2': _cm._Pastel2_data, 'Paired': _cm._Paired_data, 'Accent': _cm._Accent_data, 'Dark2': _cm._Dark2_data, 'Set1': _cm._Set1_data, 'Set2': _cm._Set2_data, 'Set3': _cm._Set3_data, 'petroff10': _cm._petroff10_data} def __init__(self): self._color_sequences = {**self._BUILTIN_COLOR_SEQUENCES} def __getitem__(self, item): try: return list(self._color_sequences[item]) except KeyError: raise KeyError(f'{item!r} is not a known color sequence name') def __iter__(self): return iter(self._color_sequences) def __len__(self): return len(self._color_sequences) def __str__(self): return 'ColorSequenceRegistry; available colormaps:\n' + ', '.join((f"'{name}'" for name in self)) def register(self, name, color_list): if name in self._BUILTIN_COLOR_SEQUENCES: raise ValueError(f'{name!r} is a reserved name for a builtin color sequence') color_list = list(color_list) for color in color_list: try: to_rgba(color) except ValueError: raise ValueError(f'{color!r} is not a valid color specification') self._color_sequences[name] = color_list def unregister(self, name): if name in self._BUILTIN_COLOR_SEQUENCES: raise ValueError(f'Cannot unregister builtin color sequence {name!r}') self._color_sequences.pop(name, None) _color_sequences = ColorSequenceRegistry() def _sanitize_extrema(ex): if ex is None: return ex try: ret = ex.item() except AttributeError: ret = float(ex) return ret _nth_color_re = re.compile('\\AC[0-9]+\\Z') def _is_nth_color(c): return isinstance(c, str) and _nth_color_re.match(c) def is_color_like(c): if _is_nth_color(c): return True try: to_rgba(c) except (TypeError, ValueError): return False else: return True def _has_alpha_channel(c): return not isinstance(c, str) and len(c) == 4 def _check_color_like(**kwargs): for (k, v) in kwargs.items(): if not is_color_like(v): raise ValueError(f"{v!r} is not a valid value for {k}: supported inputs are (r, g, b) and (r, g, b, a) 0-1 float tuples; '#rrggbb', '#rrggbbaa', '#rgb', '#rgba' strings; named color strings; string reprs of 0-1 floats for grayscale values; 'C0', 'C1', ... strings for colors of the color cycle; and pairs combining one of the above with an alpha value") def same_color(c1, c2): c1 = to_rgba_array(c1) c2 = to_rgba_array(c2) n1 = max(c1.shape[0], 1) n2 = max(c2.shape[0], 1) if n1 != n2: raise ValueError('Different number of elements passed.') return c1.shape == c2.shape and (c1 == c2).all() def to_rgba(c, alpha=None): if isinstance(c, tuple) and len(c) == 2: if alpha is None: (c, alpha) = c else: c = c[0] if _is_nth_color(c): prop_cycler = mpl.rcParams['axes.prop_cycle'] colors = prop_cycler.by_key().get('color', ['k']) c = colors[int(c[1:]) % len(colors)] try: rgba = _colors_full_map.cache[c, alpha] except (KeyError, TypeError): rgba = None if rgba is None: rgba = _to_rgba_no_colorcycle(c, alpha) try: _colors_full_map.cache[c, alpha] = rgba except TypeError: pass return rgba def _to_rgba_no_colorcycle(c, alpha=None): if alpha is not None and (not 0 <= alpha <= 1): raise ValueError("'alpha' must be between 0 and 1, inclusive") orig_c = c if c is np.ma.masked: return (0.0, 0.0, 0.0, 0.0) if isinstance(c, str): if c.lower() == 'none': return (0.0, 0.0, 0.0, 0.0) try: c = _colors_full_map[c] except KeyError: if len(orig_c) != 1: try: c = _colors_full_map[c.lower()] except KeyError: pass if isinstance(c, str): match = re.match('\\A#[a-fA-F0-9]{6}\\Z', c) if match: return tuple((int(n, 16) / 255 for n in [c[1:3], c[3:5], c[5:7]])) + (alpha if alpha is not None else 1.0,) match = re.match('\\A#[a-fA-F0-9]{3}\\Z', c) if match: return tuple((int(n, 16) / 255 for n in [c[1] * 2, c[2] * 2, c[3] * 2])) + (alpha if alpha is not None else 1.0,) match = re.match('\\A#[a-fA-F0-9]{8}\\Z', c) if match: color = [int(n, 16) / 255 for n in [c[1:3], c[3:5], c[5:7], c[7:9]]] if alpha is not None: color[-1] = alpha return tuple(color) match = re.match('\\A#[a-fA-F0-9]{4}\\Z', c) if match: color = [int(n, 16) / 255 for n in [c[1] * 2, c[2] * 2, c[3] * 2, c[4] * 2]] if alpha is not None: color[-1] = alpha return tuple(color) try: c = float(c) except ValueError: pass else: if not 0 <= c <= 1: raise ValueError(f'Invalid string grayscale value {orig_c!r}. Value must be within 0-1 range') return (c, c, c, alpha if alpha is not None else 1.0) raise ValueError(f'Invalid RGBA argument: {orig_c!r}') if isinstance(c, np.ndarray): if c.ndim == 2 and c.shape[0] == 1: c = c.reshape(-1) if not np.iterable(c): raise ValueError(f'Invalid RGBA argument: {orig_c!r}') if len(c) not in [3, 4]: raise ValueError('RGBA sequence should have length 3 or 4') if not all((isinstance(x, Real) for x in c)): raise ValueError(f'Invalid RGBA argument: {orig_c!r}') c = tuple(map(float, c)) if len(c) == 3 and alpha is None: alpha = 1 if alpha is not None: c = c[:3] + (alpha,) if any((elem < 0 or elem > 1 for elem in c)): raise ValueError('RGBA values should be within 0-1 range') return c def to_rgba_array(c, alpha=None): if isinstance(c, tuple) and len(c) == 2 and isinstance(c[1], Real): if alpha is None: (c, alpha) = c else: c = c[0] if np.iterable(alpha): alpha = np.asarray(alpha).ravel() if isinstance(c, np.ndarray) and c.dtype.kind in 'if' and (c.ndim == 2) and (c.shape[1] in [3, 4]): mask = c.mask.any(axis=1) if np.ma.is_masked(c) else None c = np.ma.getdata(c) if np.iterable(alpha): if c.shape[0] == 1 and alpha.shape[0] > 1: c = np.tile(c, (alpha.shape[0], 1)) elif c.shape[0] != alpha.shape[0]: raise ValueError('The number of colors must match the number of alpha values if there are more than one of each.') if c.shape[1] == 3: result = np.column_stack([c, np.zeros(len(c))]) result[:, -1] = alpha if alpha is not None else 1.0 elif c.shape[1] == 4: result = c.copy() if alpha is not None: result[:, -1] = alpha if mask is not None: result[mask] = 0 if np.any((result < 0) | (result > 1)): raise ValueError('RGBA values should be within 0-1 range') return result if cbook._str_lower_equal(c, 'none'): return np.zeros((0, 4), float) try: if np.iterable(alpha): return np.array([to_rgba(c, a) for a in alpha], float) else: return np.array([to_rgba(c, alpha)], float) except TypeError: pass except ValueError as e: if e.args == ("'alpha' must be between 0 and 1, inclusive",): raise e if isinstance(c, str): raise ValueError(f'{c!r} is not a valid color value.') if len(c) == 0: return np.zeros((0, 4), float) if isinstance(c, Sequence): lens = {len(cc) if isinstance(cc, (list, tuple)) else -1 for cc in c} if lens == {3}: rgba = np.column_stack([c, np.ones(len(c))]) elif lens == {4}: rgba = np.array(c) else: rgba = np.array([to_rgba(cc) for cc in c]) else: rgba = np.array([to_rgba(cc) for cc in c]) if alpha is not None: rgba[:, 3] = alpha if isinstance(c, Sequence): none_mask = [cbook._str_equal(cc, 'none') for cc in c] rgba[:, 3][none_mask] = 0 return rgba def to_rgb(c): return to_rgba(c)[:3] def to_hex(c, keep_alpha=False): c = to_rgba(c) if not keep_alpha: c = c[:3] return '#' + ''.join((format(round(val * 255), '02x') for val in c)) cnames = CSS4_COLORS hexColorPattern = re.compile('\\A#[a-fA-F0-9]{6}\\Z') rgb2hex = to_hex hex2color = to_rgb class ColorConverter: colors = _colors_full_map cache = _colors_full_map.cache to_rgb = staticmethod(to_rgb) to_rgba = staticmethod(to_rgba) to_rgba_array = staticmethod(to_rgba_array) colorConverter = ColorConverter() def _create_lookup_table(N, data, gamma=1.0): if callable(data): xind = np.linspace(0, 1, N) ** gamma lut = np.clip(np.array(data(xind), dtype=float), 0, 1) return lut try: adata = np.array(data) except Exception as err: raise TypeError('data must be convertible to an array') from err _api.check_shape((None, 3), data=adata) x = adata[:, 0] y0 = adata[:, 1] y1 = adata[:, 2] if x[0] != 0.0 or x[-1] != 1.0: raise ValueError('data mapping points must start with x=0 and end with x=1') if (np.diff(x) < 0).any(): raise ValueError('data mapping points must have x in increasing order') if N == 1: lut = np.array(y0[-1]) else: x = x * (N - 1) xind = (N - 1) * np.linspace(0, 1, N) ** gamma ind = np.searchsorted(x, xind)[1:-1] distance = (xind[1:-1] - x[ind - 1]) / (x[ind] - x[ind - 1]) lut = np.concatenate([[y1[0]], distance * (y0[ind] - y1[ind - 1]) + y1[ind - 1], [y0[-1]]]) return np.clip(lut, 0.0, 1.0) class Colormap: def __init__(self, name, N=256): self.name = name self.N = int(N) self._rgba_bad = (0.0, 0.0, 0.0, 0.0) self._rgba_under = None self._rgba_over = None self._i_under = self.N self._i_over = self.N + 1 self._i_bad = self.N + 2 self._isinit = False self.n_variates = 1 self.colorbar_extend = False def __call__(self, X, alpha=None, bytes=False): (rgba, mask) = self._get_rgba_and_mask(X, alpha=alpha, bytes=bytes) if not np.iterable(X): rgba = tuple(rgba) return rgba def _get_rgba_and_mask(self, X, alpha=None, bytes=False): if not self._isinit: self._init() xa = np.array(X, copy=True) if not xa.dtype.isnative: xa = xa.byteswap().view(xa.dtype.newbyteorder()) if xa.dtype.kind == 'f': xa *= self.N xa[xa == self.N] = self.N - 1 mask_under = xa < 0 mask_over = xa >= self.N mask_bad = X.mask if np.ma.is_masked(X) else np.isnan(xa) with np.errstate(invalid='ignore'): xa = xa.astype(int) xa[mask_under] = self._i_under xa[mask_over] = self._i_over xa[mask_bad] = self._i_bad lut = self._lut if bytes: lut = (lut * 255).astype(np.uint8) rgba = lut.take(xa, axis=0, mode='clip') if alpha is not None: alpha = np.clip(alpha, 0, 1) if bytes: alpha *= 255 if alpha.shape not in [(), xa.shape]: raise ValueError(f'alpha is array-like but its shape {alpha.shape} does not match that of X {xa.shape}') rgba[..., -1] = alpha if (lut[-1] == 0).all(): rgba[mask_bad] = (0, 0, 0, 0) return (rgba, mask_bad) def __copy__(self): cls = self.__class__ cmapobject = cls.__new__(cls) cmapobject.__dict__.update(self.__dict__) if self._isinit: cmapobject._lut = np.copy(self._lut) return cmapobject def __eq__(self, other): if not isinstance(other, Colormap) or self.colorbar_extend != other.colorbar_extend: return False if not self._isinit: self._init() if not other._isinit: other._init() return np.array_equal(self._lut, other._lut) def get_bad(self): if not self._isinit: self._init() return np.array(self._lut[self._i_bad]) def set_bad(self, color='k', alpha=None): self._rgba_bad = to_rgba(color, alpha) if self._isinit: self._set_extremes() def get_under(self): if not self._isinit: self._init() return np.array(self._lut[self._i_under]) def set_under(self, color='k', alpha=None): self._rgba_under = to_rgba(color, alpha) if self._isinit: self._set_extremes() def get_over(self): if not self._isinit: self._init() return np.array(self._lut[self._i_over]) def set_over(self, color='k', alpha=None): self._rgba_over = to_rgba(color, alpha) if self._isinit: self._set_extremes() def set_extremes(self, *, bad=None, under=None, over=None): if bad is not None: self.set_bad(bad) if under is not None: self.set_under(under) if over is not None: self.set_over(over) def with_extremes(self, *, bad=None, under=None, over=None): new_cm = self.copy() new_cm.set_extremes(bad=bad, under=under, over=over) return new_cm def _set_extremes(self): if self._rgba_under: self._lut[self._i_under] = self._rgba_under else: self._lut[self._i_under] = self._lut[0] if self._rgba_over: self._lut[self._i_over] = self._rgba_over else: self._lut[self._i_over] = self._lut[self.N - 1] self._lut[self._i_bad] = self._rgba_bad def _init(self): raise NotImplementedError('Abstract class only') def is_gray(self): if not self._isinit: self._init() return np.all(self._lut[:, 0] == self._lut[:, 1]) and np.all(self._lut[:, 0] == self._lut[:, 2]) def resampled(self, lutsize): if hasattr(self, '_resample'): _api.warn_external(f'The ability to resample a color map is now public API However the class {type(self)} still only implements the previous private _resample method. Please update your class.') return self._resample(lutsize) raise NotImplementedError() def reversed(self, name=None): raise NotImplementedError() def _repr_png_(self): X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]), (_REPR_PNG_SIZE[1], 1)) pixels = self(X, bytes=True) png_bytes = io.BytesIO() title = self.name + ' colormap' author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org' pnginfo = PngInfo() pnginfo.add_text('Title', title) pnginfo.add_text('Description', title) pnginfo.add_text('Author', author) pnginfo.add_text('Software', author) Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo) return png_bytes.getvalue() def _repr_html_(self): png_bytes = self._repr_png_() png_base64 = base64.b64encode(png_bytes).decode('ascii') def color_block(color): hex_color = to_hex(color, keep_alpha=True) return f'
' return f'
{self.name}
{self.name} colormap
{color_block(self.get_under())} under
bad {color_block(self.get_bad())}
over {color_block(self.get_over())}
' def copy(self): return self.__copy__() class LinearSegmentedColormap(Colormap): def __init__(self, name, segmentdata, N=256, gamma=1.0): self.monochrome = False super().__init__(name, N) self._segmentdata = segmentdata self._gamma = gamma def _init(self): self._lut = np.ones((self.N + 3, 4), float) self._lut[:-3, 0] = _create_lookup_table(self.N, self._segmentdata['red'], self._gamma) self._lut[:-3, 1] = _create_lookup_table(self.N, self._segmentdata['green'], self._gamma) self._lut[:-3, 2] = _create_lookup_table(self.N, self._segmentdata['blue'], self._gamma) if 'alpha' in self._segmentdata: self._lut[:-3, 3] = _create_lookup_table(self.N, self._segmentdata['alpha'], 1) self._isinit = True self._set_extremes() def set_gamma(self, gamma): self._gamma = gamma self._init() @staticmethod def from_list(name, colors, N=256, gamma=1.0): if not np.iterable(colors): raise ValueError('colors must be iterable') if isinstance(colors[0], Sized) and len(colors[0]) == 2 and (not isinstance(colors[0], str)): (vals, colors) = zip(*colors) else: vals = np.linspace(0, 1, len(colors)) (r, g, b, a) = to_rgba_array(colors).T cdict = {'red': np.column_stack([vals, r, r]), 'green': np.column_stack([vals, g, g]), 'blue': np.column_stack([vals, b, b]), 'alpha': np.column_stack([vals, a, a])} return LinearSegmentedColormap(name, cdict, N, gamma) def resampled(self, lutsize): new_cmap = LinearSegmentedColormap(self.name, self._segmentdata, lutsize) new_cmap._rgba_over = self._rgba_over new_cmap._rgba_under = self._rgba_under new_cmap._rgba_bad = self._rgba_bad return new_cmap @staticmethod def _reverser(func, x): return func(1 - x) def reversed(self, name=None): if name is None: name = self.name + '_r' data_r = {key: functools.partial(self._reverser, data) if callable(data) else [(1.0 - x, y1, y0) for (x, y0, y1) in reversed(data)] for (key, data) in self._segmentdata.items()} new_cmap = LinearSegmentedColormap(name, data_r, self.N, self._gamma) new_cmap._rgba_over = self._rgba_under new_cmap._rgba_under = self._rgba_over new_cmap._rgba_bad = self._rgba_bad return new_cmap class ListedColormap(Colormap): def __init__(self, colors, name='from_list', N=None): self.monochrome = False if N is None: self.colors = colors N = len(colors) elif isinstance(colors, str): self.colors = [colors] * N self.monochrome = True elif np.iterable(colors): if len(colors) == 1: self.monochrome = True self.colors = list(itertools.islice(itertools.cycle(colors), N)) else: try: gray = float(colors) except TypeError: pass else: self.colors = [gray] * N self.monochrome = True super().__init__(name, N) def _init(self): self._lut = np.zeros((self.N + 3, 4), float) self._lut[:-3] = to_rgba_array(self.colors) self._isinit = True self._set_extremes() def resampled(self, lutsize): colors = self(np.linspace(0, 1, lutsize)) new_cmap = ListedColormap(colors, name=self.name) new_cmap._rgba_over = self._rgba_over new_cmap._rgba_under = self._rgba_under new_cmap._rgba_bad = self._rgba_bad return new_cmap def reversed(self, name=None): if name is None: name = self.name + '_r' colors_r = list(reversed(self.colors)) new_cmap = ListedColormap(colors_r, name=name, N=self.N) new_cmap._rgba_over = self._rgba_under new_cmap._rgba_under = self._rgba_over new_cmap._rgba_bad = self._rgba_bad return new_cmap class MultivarColormap: def __init__(self, colormaps, combination_mode, name='multivariate colormap'): self.name = name if not np.iterable(colormaps) or len(colormaps) == 1 or isinstance(colormaps, str): raise ValueError('A MultivarColormap must have more than one colormap.') colormaps = list(colormaps) for (i, cmap) in enumerate(colormaps): if isinstance(cmap, str): colormaps[i] = mpl.colormaps[cmap] elif not isinstance(cmap, Colormap): raise ValueError('colormaps must be a list of objects that subclass Colormap or a name found in the colormap registry.') self._colormaps = colormaps _api.check_in_list(['sRGB_add', 'sRGB_sub'], combination_mode=combination_mode) self._combination_mode = combination_mode self.n_variates = len(colormaps) self._rgba_bad = (0.0, 0.0, 0.0, 0.0) def __call__(self, X, alpha=None, bytes=False, clip=True): if len(X) != len(self): raise ValueError(f'For the selected colormap the data must have a first dimension {len(self)}, not {len(X)}') (rgba, mask_bad) = self[0]._get_rgba_and_mask(X[0], bytes=False) for (c, xx) in zip(self[1:], X[1:]): (sub_rgba, sub_mask_bad) = c._get_rgba_and_mask(xx, bytes=False) rgba[..., :3] += sub_rgba[..., :3] rgba[..., 3] *= sub_rgba[..., 3] mask_bad |= sub_mask_bad if self.combination_mode == 'sRGB_sub': rgba[..., :3] -= len(self) - 1 rgba[mask_bad] = self.get_bad() if clip: rgba = np.clip(rgba, 0, 1) if alpha is not None: if clip: alpha = np.clip(alpha, 0, 1) if np.shape(alpha) not in [(), np.shape(X[0])]: raise ValueError(f'alpha is array-like but its shape {np.shape(alpha)} does not match that of X[0] {np.shape(X[0])}') rgba[..., -1] *= alpha if bytes: if not clip: raise ValueError('clip cannot be false while bytes is true as uint8 does not support values below 0 or above 255.') rgba = (rgba * 255).astype('uint8') if not np.iterable(X[0]): rgba = tuple(rgba) return rgba def copy(self): return self.__copy__() def __copy__(self): cls = self.__class__ cmapobject = cls.__new__(cls) cmapobject.__dict__.update(self.__dict__) cmapobject._colormaps = [cm.copy() for cm in self._colormaps] cmapobject._rgba_bad = np.copy(self._rgba_bad) return cmapobject def __eq__(self, other): if not isinstance(other, MultivarColormap): return False if len(self) != len(other): return False for (c0, c1) in zip(self, other): if c0 != c1: return False if not all(self._rgba_bad == other._rgba_bad): return False if self.combination_mode != other.combination_mode: return False return True def __getitem__(self, item): return self._colormaps[item] def __iter__(self): for c in self._colormaps: yield c def __len__(self): return len(self._colormaps) def __str__(self): return self.name def get_bad(self): return np.array(self._rgba_bad) def resampled(self, lutshape): if not np.iterable(lutshape) or len(lutshape) != len(self): raise ValueError(f'lutshape must be of length {len(self)}') new_cmap = self.copy() for (i, s) in enumerate(lutshape): if s is not None: new_cmap._colormaps[i] = self[i].resampled(s) return new_cmap def with_extremes(self, *, bad=None, under=None, over=None): new_cm = self.copy() if bad is not None: new_cm._rgba_bad = to_rgba(bad) if under is not None: if not np.iterable(under) or len(under) != len(new_cm): raise ValueError(f'*under* must contain a color for each scalar colormap i.e. be of length {len(new_cm)}.') else: for (c, b) in zip(new_cm, under): c.set_under(b) if over is not None: if not np.iterable(over) or len(over) != len(new_cm): raise ValueError(f'*over* must contain a color for each scalar colormap i.e. be of length {len(new_cm)}.') else: for (c, b) in zip(new_cm, over): c.set_over(b) return new_cm @property def combination_mode(self): return self._combination_mode def _repr_png_(self): X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]), (_REPR_PNG_SIZE[1], 1)) pixels = np.zeros((_REPR_PNG_SIZE[1] * len(self), _REPR_PNG_SIZE[0], 4), dtype=np.uint8) for (i, c) in enumerate(self): pixels[i * _REPR_PNG_SIZE[1]:(i + 1) * _REPR_PNG_SIZE[1], :] = c(X, bytes=True) png_bytes = io.BytesIO() title = self.name + ' multivariate colormap' author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org' pnginfo = PngInfo() pnginfo.add_text('Title', title) pnginfo.add_text('Description', title) pnginfo.add_text('Author', author) pnginfo.add_text('Software', author) Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo) return png_bytes.getvalue() def _repr_html_(self): return ''.join([c._repr_html_() for c in self._colormaps]) class BivarColormap: def __init__(self, N=256, M=256, shape='square', origin=(0, 0), name='bivariate colormap'): self.name = name self.N = int(N) self.M = int(M) _api.check_in_list(['square', 'circle', 'ignore', 'circleignore'], shape=shape) self._shape = shape self._rgba_bad = (0.0, 0.0, 0.0, 0.0) self._rgba_outside = (1.0, 0.0, 1.0, 1.0) self._isinit = False self.n_variates = 2 self._origin = (float(origin[0]), float(origin[1])) '' def __call__(self, X, alpha=None, bytes=False): if len(X) != 2: raise ValueError(f'For a `BivarColormap` the data must have a first dimension 2, not {len(X)}') if not self._isinit: self._init() X0 = np.ma.array(X[0], copy=True) X1 = np.ma.array(X[1], copy=True) self._clip((X0, X1)) if not X0.dtype.isnative: X0 = X0.byteswap().view(X0.dtype.newbyteorder()) if not X1.dtype.isnative: X1 = X1.byteswap().view(X1.dtype.newbyteorder()) if X0.dtype.kind == 'f': X0 *= self.N X0[X0 == self.N] = self.N - 1 if X1.dtype.kind == 'f': X1 *= self.M X1[X1 == self.M] = self.M - 1 mask_outside = (X0 < 0) | (X1 < 0) | (X0 >= self.N) | (X1 >= self.M) mask_bad_0 = X0.mask if np.ma.is_masked(X0) else np.isnan(X0) mask_bad_1 = X1.mask if np.ma.is_masked(X1) else np.isnan(X1) mask_bad = mask_bad_0 | mask_bad_1 with np.errstate(invalid='ignore'): X0 = X0.astype(int) X1 = X1.astype(int) for X_part in [X0, X1]: X_part[mask_outside] = 0 X_part[mask_bad] = 0 rgba = self._lut[X0, X1] if np.isscalar(X[0]): rgba = np.copy(rgba) rgba[mask_outside] = self._rgba_outside rgba[mask_bad] = self._rgba_bad if bytes: rgba = (rgba * 255).astype(np.uint8) if alpha is not None: alpha = np.clip(alpha, 0, 1) if bytes: alpha *= 255 if np.shape(alpha) not in [(), np.shape(X0)]: raise ValueError(f'alpha is array-like but its shape {np.shape(alpha)} does not match that of X[0] {np.shape(X0)}') rgba[..., -1] = alpha if (np.array(self._rgba_bad) == 0).all(): rgba[mask_bad] = (0, 0, 0, 0) if not np.iterable(X[0]): rgba = tuple(rgba) return rgba @property def lut(self): if not self._isinit: self._init() lut = np.copy(self._lut) if self.shape == 'circle' or self.shape == 'circleignore': n = np.linspace(-1, 1, self.N) m = np.linspace(-1, 1, self.M) radii_sqr = (n ** 2)[:, np.newaxis] + (m ** 2)[np.newaxis, :] mask_outside = radii_sqr > 1 lut[mask_outside, 3] = 0 return lut def __copy__(self): cls = self.__class__ cmapobject = cls.__new__(cls) cmapobject.__dict__.update(self.__dict__) cmapobject._rgba_outside = np.copy(self._rgba_outside) cmapobject._rgba_bad = np.copy(self._rgba_bad) cmapobject._shape = self.shape if self._isinit: cmapobject._lut = np.copy(self._lut) return cmapobject def __eq__(self, other): if not isinstance(other, BivarColormap): return False if not self._isinit: self._init() if not other._isinit: other._init() if not np.array_equal(self._lut, other._lut): return False if not np.array_equal(self._rgba_bad, other._rgba_bad): return False if not np.array_equal(self._rgba_outside, other._rgba_outside): return False if self.shape != other.shape: return False return True def get_bad(self): return self._rgba_bad def get_outside(self): return self._rgba_outside def resampled(self, lutshape, transposed=False): if not np.iterable(lutshape) or len(lutshape) != 2: raise ValueError('lutshape must be of length 2') lutshape = [lutshape[0], lutshape[1]] if lutshape[0] is None or lutshape[0] == 1: lutshape[0] = self.N if lutshape[1] is None or lutshape[1] == 1: lutshape[1] = self.M inverted = [False, False] if lutshape[0] < 0: inverted[0] = True lutshape[0] = -lutshape[0] if lutshape[0] == 1: lutshape[0] = self.N if lutshape[1] < 0: inverted[1] = True lutshape[1] = -lutshape[1] if lutshape[1] == 1: lutshape[1] = self.M (x_0, x_1) = np.mgrid[0:1:lutshape[0] * 1j, 0:1:lutshape[1] * 1j] if inverted[0]: x_0 = x_0[::-1, :] if inverted[1]: x_1 = x_1[:, ::-1] shape_memory = self._shape self._shape = 'square' if transposed: new_lut = self((x_1, x_0)) new_cmap = BivarColormapFromImage(new_lut, name=self.name, shape=shape_memory, origin=self.origin[::-1]) else: new_lut = self((x_0, x_1)) new_cmap = BivarColormapFromImage(new_lut, name=self.name, shape=shape_memory, origin=self.origin) self._shape = shape_memory new_cmap._rgba_bad = self._rgba_bad new_cmap._rgba_outside = self._rgba_outside return new_cmap def reversed(self, axis_0=True, axis_1=True): r_0 = -1 if axis_0 else 1 r_1 = -1 if axis_1 else 1 return self.resampled((r_0, r_1)) def transposed(self): return self.resampled((None, None), transposed=True) def with_extremes(self, *, bad=None, outside=None, shape=None, origin=None): new_cm = self.copy() if bad is not None: new_cm._rgba_bad = to_rgba(bad) if outside is not None: new_cm._rgba_outside = to_rgba(outside) if shape is not None: _api.check_in_list(['square', 'circle', 'ignore', 'circleignore'], shape=shape) new_cm._shape = shape if origin is not None: new_cm._origin = (float(origin[0]), float(origin[1])) return new_cm def _init(self): raise NotImplementedError('Abstract class only') @property def shape(self): return self._shape @property def origin(self): return self._origin def _clip(self, X): if self.shape == 'square': for (X_part, mx) in zip(X, (self.N, self.M)): X_part[X_part < 0] = 0 if X_part.dtype.kind == 'f': X_part[X_part > 1] = 1 else: X_part[X_part >= mx] = mx - 1 elif self.shape == 'ignore': for (X_part, mx) in zip(X, (self.N, self.M)): X_part[X_part < 0] = -1 if X_part.dtype.kind == 'f': X_part[X_part > 1] = -1 else: X_part[X_part >= mx] = -1 elif self.shape == 'circle' or self.shape == 'circleignore': for X_part in X: if X_part.dtype.kind != 'f': raise NotImplementedError('Circular bivariate colormaps are only implemented for use with with floats') radii_sqr = (X[0] - 0.5) ** 2 + (X[1] - 0.5) ** 2 mask_outside = radii_sqr > 0.25 if self.shape == 'circle': overextend = 2 * np.sqrt(radii_sqr[mask_outside]) X[0][mask_outside] = (X[0][mask_outside] - 0.5) / overextend + 0.5 X[1][mask_outside] = (X[1][mask_outside] - 0.5) / overextend + 0.5 else: X[0][mask_outside] = -1 X[1][mask_outside] = -1 def __getitem__(self, item): if not self._isinit: self._init() if item == 0: origin_1_as_int = int(self._origin[1] * self.M) if origin_1_as_int > self.M - 1: origin_1_as_int = self.M - 1 one_d_lut = self._lut[:, origin_1_as_int] new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_0', N=self.N) elif item == 1: origin_0_as_int = int(self._origin[0] * self.N) if origin_0_as_int > self.N - 1: origin_0_as_int = self.N - 1 one_d_lut = self._lut[origin_0_as_int, :] new_cmap = ListedColormap(one_d_lut, name=f'{self.name}_1', N=self.M) else: raise KeyError(f'only 0 or 1 are valid keys for BivarColormap, not {item!r}') new_cmap._rgba_bad = self._rgba_bad if self.shape in ['ignore', 'circleignore']: new_cmap.set_over(self._rgba_outside) new_cmap.set_under(self._rgba_outside) return new_cmap def _repr_png_(self): if not self._isinit: self._init() pixels = self.lut if pixels.shape[0] < _BIVAR_REPR_PNG_SIZE: pixels = np.repeat(pixels, repeats=_BIVAR_REPR_PNG_SIZE // pixels.shape[0], axis=0)[:256, :] if pixels.shape[1] < _BIVAR_REPR_PNG_SIZE: pixels = np.repeat(pixels, repeats=_BIVAR_REPR_PNG_SIZE // pixels.shape[1], axis=1)[:, :256] pixels = (pixels[::-1, :, :] * 255).astype(np.uint8) png_bytes = io.BytesIO() title = self.name + ' BivarColormap' author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org' pnginfo = PngInfo() pnginfo.add_text('Title', title) pnginfo.add_text('Description', title) pnginfo.add_text('Author', author) pnginfo.add_text('Software', author) Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo) return png_bytes.getvalue() def _repr_html_(self): png_bytes = self._repr_png_() png_base64 = base64.b64encode(png_bytes).decode('ascii') def color_block(color): hex_color = to_hex(color, keep_alpha=True) return f'
' return f'
{self.name}
{self.name} BivarColormap
{color_block(self.get_outside())} outside
bad {color_block(self.get_bad())}
' def copy(self): return self.__copy__() class SegmentedBivarColormap(BivarColormap): def __init__(self, patch, N=256, shape='square', origin=(0, 0), name='segmented bivariate colormap'): _api.check_shape((None, None, 3), patch=patch) self.patch = patch super().__init__(N, N, shape, origin, name=name) def _init(self): s = self.patch.shape _patch = np.empty((s[0], s[1], 4)) _patch[:, :, :3] = self.patch _patch[:, :, 3] = 1 transform = mpl.transforms.Affine2D().translate(-0.5, -0.5).scale(self.N / (s[1] - 1), self.N / (s[0] - 1)) self._lut = np.empty((self.N, self.N, 4)) _image.resample(_patch, self._lut, transform, _image.BILINEAR, resample=False, alpha=1) self._isinit = True class BivarColormapFromImage(BivarColormap): def __init__(self, lut, shape='square', origin=(0, 0), name='from image'): lut = np.array(lut, copy=True) if lut.ndim != 3 or lut.shape[2] not in (3, 4): raise ValueError('The lut must be an array of shape (n, m, 3) or (n, m, 4)', ' or a PIL.image encoded as RGB or RGBA') if lut.dtype == np.uint8: lut = lut.astype(np.float32) / 255 if lut.shape[2] == 3: new_lut = np.empty((lut.shape[0], lut.shape[1], 4), dtype=lut.dtype) new_lut[:, :, :3] = lut new_lut[:, :, 3] = 1.0 lut = new_lut self._lut = lut super().__init__(lut.shape[0], lut.shape[1], shape, origin, name=name) def _init(self): self._isinit = True class Normalize: def __init__(self, vmin=None, vmax=None, clip=False): self._vmin = _sanitize_extrema(vmin) self._vmax = _sanitize_extrema(vmax) self._clip = clip self._scale = None self.callbacks = cbook.CallbackRegistry(signals=['changed']) @property def vmin(self): return self._vmin @vmin.setter def vmin(self, value): value = _sanitize_extrema(value) if value != self._vmin: self._vmin = value self._changed() @property def vmax(self): return self._vmax @vmax.setter def vmax(self, value): value = _sanitize_extrema(value) if value != self._vmax: self._vmax = value self._changed() @property def clip(self): return self._clip @clip.setter def clip(self, value): if value != self._clip: self._clip = value self._changed() def _changed(self): self.callbacks.process('changed') @staticmethod def process_value(value): is_scalar = not np.iterable(value) if is_scalar: value = [value] dtype = np.min_scalar_type(value) if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_: dtype = np.promote_types(dtype, np.float32) mask = np.ma.getmask(value) data = np.asarray(value) result = np.ma.array(data, mask=mask, dtype=dtype, copy=True) return (result, is_scalar) def __call__(self, value, clip=None): if clip is None: clip = self.clip (result, is_scalar) = self.process_value(value) if self.vmin is None or self.vmax is None: self.autoscale_None(result) ((vmin,), _) = self.process_value(self.vmin) ((vmax,), _) = self.process_value(self.vmax) if vmin == vmax: result.fill(0) elif vmin > vmax: raise ValueError('minvalue must be less than or equal to maxvalue') else: if clip: mask = np.ma.getmask(result) result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax), mask=mask) resdat = result.data resdat -= vmin resdat /= vmax - vmin result = np.ma.array(resdat, mask=result.mask, copy=False) if is_scalar: result = result[0] return result def inverse(self, value): if not self.scaled(): raise ValueError('Not invertible until both vmin and vmax are set') ((vmin,), _) = self.process_value(self.vmin) ((vmax,), _) = self.process_value(self.vmax) if np.iterable(value): val = np.ma.asarray(value) return vmin + val * (vmax - vmin) else: return vmin + value * (vmax - vmin) def autoscale(self, A): with self.callbacks.blocked(): self.vmin = self.vmax = None self.autoscale_None(A) self._changed() def autoscale_None(self, A): A = np.asanyarray(A) if isinstance(A, np.ma.MaskedArray): if A.mask is False or not A.mask.shape: A = A.data if self.vmin is None and A.size: self.vmin = A.min() if self.vmax is None and A.size: self.vmax = A.max() def scaled(self): return self.vmin is not None and self.vmax is not None class TwoSlopeNorm(Normalize): def __init__(self, vcenter, vmin=None, vmax=None): super().__init__(vmin=vmin, vmax=vmax) self._vcenter = vcenter if vcenter is not None and vmax is not None and (vcenter >= vmax): raise ValueError('vmin, vcenter, and vmax must be in ascending order') if vcenter is not None and vmin is not None and (vcenter <= vmin): raise ValueError('vmin, vcenter, and vmax must be in ascending order') @property def vcenter(self): return self._vcenter @vcenter.setter def vcenter(self, value): if value != self._vcenter: self._vcenter = value self._changed() def autoscale_None(self, A): super().autoscale_None(A) if self.vmin >= self.vcenter: self.vmin = self.vcenter - (self.vmax - self.vcenter) if self.vmax <= self.vcenter: self.vmax = self.vcenter + (self.vcenter - self.vmin) def __call__(self, value, clip=None): (result, is_scalar) = self.process_value(value) self.autoscale_None(result) if not self.vmin <= self.vcenter <= self.vmax: raise ValueError('vmin, vcenter, vmax must increase monotonically') result = np.ma.masked_array(np.interp(result, [self.vmin, self.vcenter, self.vmax], [0, 0.5, 1], left=-np.inf, right=np.inf), mask=np.ma.getmask(result)) if is_scalar: result = np.atleast_1d(result)[0] return result def inverse(self, value): if not self.scaled(): raise ValueError('Not invertible until both vmin and vmax are set') ((vmin,), _) = self.process_value(self.vmin) ((vmax,), _) = self.process_value(self.vmax) ((vcenter,), _) = self.process_value(self.vcenter) result = np.interp(value, [0, 0.5, 1], [vmin, vcenter, vmax], left=-np.inf, right=np.inf) return result class CenteredNorm(Normalize): def __init__(self, vcenter=0, halfrange=None, clip=False): super().__init__(vmin=None, vmax=None, clip=clip) self._vcenter = vcenter self.halfrange = halfrange def autoscale(self, A): A = np.asanyarray(A) self.halfrange = max(self._vcenter - A.min(), A.max() - self._vcenter) def autoscale_None(self, A): A = np.asanyarray(A) if self.halfrange is None and A.size: self.autoscale(A) @property def vmin(self): return self._vmin @vmin.setter def vmin(self, value): value = _sanitize_extrema(value) if value != self._vmin: self._vmin = value self._vmax = 2 * self.vcenter - value self._changed() @property def vmax(self): return self._vmax @vmax.setter def vmax(self, value): value = _sanitize_extrema(value) if value != self._vmax: self._vmax = value self._vmin = 2 * self.vcenter - value self._changed() @property def vcenter(self): return self._vcenter @vcenter.setter def vcenter(self, vcenter): if vcenter != self._vcenter: self._vcenter = vcenter self.halfrange = self.halfrange self._changed() @property def halfrange(self): if self.vmin is None or self.vmax is None: return None return (self.vmax - self.vmin) / 2 @halfrange.setter def halfrange(self, halfrange): if halfrange is None: self.vmin = None self.vmax = None else: self.vmin = self.vcenter - abs(halfrange) self.vmax = self.vcenter + abs(halfrange) def make_norm_from_scale(scale_cls, base_norm_cls=None, *, init=None): if base_norm_cls is None: return functools.partial(make_norm_from_scale, scale_cls, init=init) if isinstance(scale_cls, functools.partial): scale_args = scale_cls.args scale_kwargs_items = tuple(scale_cls.keywords.items()) scale_cls = scale_cls.func else: scale_args = scale_kwargs_items = () if init is None: def init(vmin=None, vmax=None, clip=False): pass return _make_norm_from_scale(scale_cls, scale_args, scale_kwargs_items, base_norm_cls, inspect.signature(init)) @functools.cache def _make_norm_from_scale(scale_cls, scale_args, scale_kwargs_items, base_norm_cls, bound_init_signature): class Norm(base_norm_cls): def __reduce__(self): cls = type(self) try: if cls is getattr(importlib.import_module(cls.__module__), cls.__qualname__): return (_create_empty_object_of_class, (cls,), vars(self)) except (ImportError, AttributeError): pass return (_picklable_norm_constructor, (scale_cls, scale_args, scale_kwargs_items, base_norm_cls, bound_init_signature), vars(self)) def __init__(self, *args, **kwargs): ba = bound_init_signature.bind(*args, **kwargs) ba.apply_defaults() super().__init__(**{k: ba.arguments.pop(k) for k in ['vmin', 'vmax', 'clip']}) self._scale = functools.partial(scale_cls, *scale_args, **dict(scale_kwargs_items))(axis=None, **ba.arguments) self._trf = self._scale.get_transform() __init__.__signature__ = bound_init_signature.replace(parameters=[inspect.Parameter('self', inspect.Parameter.POSITIONAL_OR_KEYWORD), *bound_init_signature.parameters.values()]) def __call__(self, value, clip=None): (value, is_scalar) = self.process_value(value) if self.vmin is None or self.vmax is None: self.autoscale_None(value) if self.vmin > self.vmax: raise ValueError('vmin must be less or equal to vmax') if self.vmin == self.vmax: return np.full_like(value, 0) if clip is None: clip = self.clip if clip: value = np.clip(value, self.vmin, self.vmax) t_value = self._trf.transform(value).reshape(np.shape(value)) (t_vmin, t_vmax) = self._trf.transform([self.vmin, self.vmax]) if not np.isfinite([t_vmin, t_vmax]).all(): raise ValueError('Invalid vmin or vmax') t_value -= t_vmin t_value /= t_vmax - t_vmin t_value = np.ma.masked_invalid(t_value, copy=False) return t_value[0] if is_scalar else t_value def inverse(self, value): if not self.scaled(): raise ValueError('Not invertible until scaled') if self.vmin > self.vmax: raise ValueError('vmin must be less or equal to vmax') (t_vmin, t_vmax) = self._trf.transform([self.vmin, self.vmax]) if not np.isfinite([t_vmin, t_vmax]).all(): raise ValueError('Invalid vmin or vmax') (value, is_scalar) = self.process_value(value) rescaled = value * (t_vmax - t_vmin) rescaled += t_vmin value = self._trf.inverted().transform(rescaled).reshape(np.shape(value)) return value[0] if is_scalar else value def autoscale_None(self, A): in_trf_domain = np.extract(np.isfinite(self._trf.transform(A)), A) if in_trf_domain.size == 0: in_trf_domain = np.ma.masked return super().autoscale_None(in_trf_domain) if base_norm_cls is Normalize: Norm.__name__ = f'{scale_cls.__name__}Norm' Norm.__qualname__ = f'{scale_cls.__qualname__}Norm' else: Norm.__name__ = base_norm_cls.__name__ Norm.__qualname__ = base_norm_cls.__qualname__ Norm.__module__ = base_norm_cls.__module__ Norm.__doc__ = base_norm_cls.__doc__ return Norm def _create_empty_object_of_class(cls): return cls.__new__(cls) def _picklable_norm_constructor(*args): return _create_empty_object_of_class(_make_norm_from_scale(*args)) @make_norm_from_scale(scale.FuncScale, init=lambda functions, vmin=None, vmax=None, clip=False: None) class FuncNorm(Normalize): LogNorm = make_norm_from_scale(functools.partial(scale.LogScale, nonpositive='mask'))(Normalize) LogNorm.__name__ = LogNorm.__qualname__ = 'LogNorm' LogNorm.__doc__ = 'Normalize a given value to the 0-1 range on a log scale.' @make_norm_from_scale(scale.SymmetricalLogScale, init=lambda linthresh, linscale=1.0, vmin=None, vmax=None, clip=False, *, base=10: None) class SymLogNorm(Normalize): @property def linthresh(self): return self._scale.linthresh @linthresh.setter def linthresh(self, value): self._scale.linthresh = value @make_norm_from_scale(scale.AsinhScale, init=lambda linear_width=1, vmin=None, vmax=None, clip=False: None) class AsinhNorm(Normalize): @property def linear_width(self): return self._scale.linear_width @linear_width.setter def linear_width(self, value): self._scale.linear_width = value class PowerNorm(Normalize): def __init__(self, gamma, vmin=None, vmax=None, clip=False): super().__init__(vmin, vmax, clip) self.gamma = gamma def __call__(self, value, clip=None): if clip is None: clip = self.clip (result, is_scalar) = self.process_value(value) self.autoscale_None(result) gamma = self.gamma (vmin, vmax) = (self.vmin, self.vmax) if vmin > vmax: raise ValueError('minvalue must be less than or equal to maxvalue') elif vmin == vmax: result.fill(0) else: if clip: mask = np.ma.getmask(result) result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax), mask=mask) resdat = result.data resdat -= vmin resdat /= vmax - vmin resdat[resdat > 0] = np.power(resdat[resdat > 0], gamma) result = np.ma.array(resdat, mask=result.mask, copy=False) if is_scalar: result = result[0] return result def inverse(self, value): if not self.scaled(): raise ValueError('Not invertible until scaled') (result, is_scalar) = self.process_value(value) gamma = self.gamma (vmin, vmax) = (self.vmin, self.vmax) resdat = result.data resdat[resdat > 0] = np.power(resdat[resdat > 0], 1 / gamma) resdat *= vmax - vmin resdat += vmin result = np.ma.array(resdat, mask=result.mask, copy=False) if is_scalar: result = result[0] return result class BoundaryNorm(Normalize): def __init__(self, boundaries, ncolors, clip=False, *, extend='neither'): if clip and extend != 'neither': raise ValueError("'clip=True' is not compatible with 'extend'") super().__init__(vmin=boundaries[0], vmax=boundaries[-1], clip=clip) self.boundaries = np.asarray(boundaries) self.N = len(self.boundaries) if self.N < 2: raise ValueError(f'You must provide at least 2 boundaries (1 region) but you passed in {boundaries!r}') self.Ncmap = ncolors self.extend = extend self._scale = None self._n_regions = self.N - 1 self._offset = 0 if extend in ('min', 'both'): self._n_regions += 1 self._offset = 1 if extend in ('max', 'both'): self._n_regions += 1 if self._n_regions > self.Ncmap: raise ValueError(f'There are {self._n_regions} color bins including extensions, but ncolors = {ncolors}; ncolors must equal or exceed the number of bins') def __call__(self, value, clip=None): if clip is None: clip = self.clip (xx, is_scalar) = self.process_value(value) mask = np.ma.getmaskarray(xx) xx = np.atleast_1d(xx.filled(self.vmax + 1)) if clip: np.clip(xx, self.vmin, self.vmax, out=xx) max_col = self.Ncmap - 1 else: max_col = self.Ncmap iret = np.digitize(xx, self.boundaries) - 1 + self._offset if self.Ncmap > self._n_regions: if self._n_regions == 1: iret[iret == 0] = (self.Ncmap - 1) // 2 else: iret = (self.Ncmap - 1) / (self._n_regions - 1) * iret iret = iret.astype(np.int16) iret[xx < self.vmin] = -1 iret[xx >= self.vmax] = max_col ret = np.ma.array(iret, mask=mask) if is_scalar: ret = int(ret[0]) return ret def inverse(self, value): raise ValueError('BoundaryNorm is not invertible') class NoNorm(Normalize): def __call__(self, value, clip=None): if np.iterable(value): return np.ma.array(value) return value def inverse(self, value): if np.iterable(value): return np.ma.array(value) return value def rgb_to_hsv(arr): arr = np.asarray(arr) if arr.shape[-1] != 3: raise ValueError(f'Last dimension of input array must be 3; shape {arr.shape} was found.') in_shape = arr.shape arr = np.array(arr, copy=False, dtype=np.promote_types(arr.dtype, np.float32), ndmin=2) out = np.zeros_like(arr) arr_max = arr.max(-1) ipos = arr_max > 0 delta = np.ptp(arr, -1) s = np.zeros_like(delta) s[ipos] = delta[ipos] / arr_max[ipos] ipos = delta > 0 idx = (arr[..., 0] == arr_max) & ipos out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx] idx = (arr[..., 1] == arr_max) & ipos out[idx, 0] = 2.0 + (arr[idx, 2] - arr[idx, 0]) / delta[idx] idx = (arr[..., 2] == arr_max) & ipos out[idx, 0] = 4.0 + (arr[idx, 0] - arr[idx, 1]) / delta[idx] out[..., 0] = out[..., 0] / 6.0 % 1.0 out[..., 1] = s out[..., 2] = arr_max return out.reshape(in_shape) def hsv_to_rgb(hsv): hsv = np.asarray(hsv) if hsv.shape[-1] != 3: raise ValueError(f'Last dimension of input array must be 3; shape {hsv.shape} was found.') in_shape = hsv.shape hsv = np.array(hsv, copy=False, dtype=np.promote_types(hsv.dtype, np.float32), ndmin=2) h = hsv[..., 0] s = hsv[..., 1] v = hsv[..., 2] r = np.empty_like(h) g = np.empty_like(h) b = np.empty_like(h) i = (h * 6.0).astype(int) f = h * 6.0 - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) idx = i % 6 == 0 r[idx] = v[idx] g[idx] = t[idx] b[idx] = p[idx] idx = i == 1 r[idx] = q[idx] g[idx] = v[idx] b[idx] = p[idx] idx = i == 2 r[idx] = p[idx] g[idx] = v[idx] b[idx] = t[idx] idx = i == 3 r[idx] = p[idx] g[idx] = q[idx] b[idx] = v[idx] idx = i == 4 r[idx] = t[idx] g[idx] = p[idx] b[idx] = v[idx] idx = i == 5 r[idx] = v[idx] g[idx] = p[idx] b[idx] = q[idx] idx = s == 0 r[idx] = v[idx] g[idx] = v[idx] b[idx] = v[idx] rgb = np.stack([r, g, b], axis=-1) return rgb.reshape(in_shape) def _vector_magnitude(arr): sum_sq = 0 for i in range(arr.shape[-1]): sum_sq += arr[..., i, np.newaxis] ** 2 return np.sqrt(sum_sq) class LightSource: def __init__(self, azdeg=315, altdeg=45, hsv_min_val=0, hsv_max_val=1, hsv_min_sat=1, hsv_max_sat=0): self.azdeg = azdeg self.altdeg = altdeg self.hsv_min_val = hsv_min_val self.hsv_max_val = hsv_max_val self.hsv_min_sat = hsv_min_sat self.hsv_max_sat = hsv_max_sat @property def direction(self): az = np.radians(90 - self.azdeg) alt = np.radians(self.altdeg) return np.array([np.cos(az) * np.cos(alt), np.sin(az) * np.cos(alt), np.sin(alt)]) def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.0): dy = -dy (e_dy, e_dx) = np.gradient(vert_exag * elevation, dy, dx) normal = np.empty(elevation.shape + (3,)).view(type(elevation)) normal[..., 0] = -e_dx normal[..., 1] = -e_dy normal[..., 2] = 1 normal /= _vector_magnitude(normal) return self.shade_normals(normal, fraction) def shade_normals(self, normals, fraction=1.0): intensity = normals.dot(self.direction) (imin, imax) = (intensity.min(), intensity.max()) intensity *= fraction if imax - imin > 1e-06: intensity -= imin intensity /= imax - imin intensity = np.clip(intensity, 0, 1) return intensity def shade(self, data, cmap, norm=None, blend_mode='overlay', vmin=None, vmax=None, vert_exag=1, dx=1, dy=1, fraction=1, **kwargs): if vmin is None: vmin = data.min() if vmax is None: vmax = data.max() if norm is None: norm = Normalize(vmin=vmin, vmax=vmax) rgb0 = cmap(norm(data)) rgb1 = self.shade_rgb(rgb0, elevation=data, blend_mode=blend_mode, vert_exag=vert_exag, dx=dx, dy=dy, fraction=fraction, **kwargs) rgb0[..., :3] = rgb1[..., :3] return rgb0 def shade_rgb(self, rgb, elevation, fraction=1.0, blend_mode='hsv', vert_exag=1, dx=1, dy=1, **kwargs): intensity = self.hillshade(elevation, vert_exag, dx, dy, fraction) intensity = intensity[..., np.newaxis] lookup = {'hsv': self.blend_hsv, 'soft': self.blend_soft_light, 'overlay': self.blend_overlay} if blend_mode in lookup: blend = lookup[blend_mode](rgb, intensity, **kwargs) else: try: blend = blend_mode(rgb, intensity, **kwargs) except TypeError as err: raise ValueError(f'"blend_mode" must be callable or one of {lookup.keys}') from err if np.ma.is_masked(intensity): mask = intensity.mask[..., 0] for i in range(3): blend[..., i][mask] = rgb[..., i][mask] return blend def blend_hsv(self, rgb, intensity, hsv_max_sat=None, hsv_max_val=None, hsv_min_val=None, hsv_min_sat=None): if hsv_max_sat is None: hsv_max_sat = self.hsv_max_sat if hsv_max_val is None: hsv_max_val = self.hsv_max_val if hsv_min_sat is None: hsv_min_sat = self.hsv_min_sat if hsv_min_val is None: hsv_min_val = self.hsv_min_val intensity = intensity[..., 0] intensity = 2 * intensity - 1 hsv = rgb_to_hsv(rgb[:, :, 0:3]) (hue, sat, val) = np.moveaxis(hsv, -1, 0) np.putmask(sat, (np.abs(sat) > 1e-10) & (intensity > 0), (1 - intensity) * sat + intensity * hsv_max_sat) np.putmask(sat, (np.abs(sat) > 1e-10) & (intensity < 0), (1 + intensity) * sat - intensity * hsv_min_sat) np.putmask(val, intensity > 0, (1 - intensity) * val + intensity * hsv_max_val) np.putmask(val, intensity < 0, (1 + intensity) * val - intensity * hsv_min_val) np.clip(hsv[:, :, 1:], 0, 1, out=hsv[:, :, 1:]) return hsv_to_rgb(hsv) def blend_soft_light(self, rgb, intensity): return 2 * intensity * rgb + (1 - 2 * intensity) * rgb ** 2 def blend_overlay(self, rgb, intensity): low = 2 * intensity * rgb high = 1 - 2 * (1 - intensity) * (1 - rgb) return np.where(rgb <= 0.5, low, high) def from_levels_and_colors(levels, colors, extend='neither'): slice_map = {'both': slice(1, -1), 'min': slice(1, None), 'max': slice(0, -1), 'neither': slice(0, None)} _api.check_in_list(slice_map, extend=extend) color_slice = slice_map[extend] n_data_colors = len(levels) - 1 n_expected = n_data_colors + color_slice.start - (color_slice.stop or 0) if len(colors) != n_expected: raise ValueError(f'With extend == {extend!r} and {len(levels)} levels, expected {n_expected} colors, but got {len(colors)}') cmap = ListedColormap(colors[color_slice], N=n_data_colors) if extend in ['min', 'both']: cmap.set_under(colors[0]) else: cmap.set_under('none') if extend in ['max', 'both']: cmap.set_over(colors[-1]) else: cmap.set_over('none') cmap.colorbar_extend = extend norm = BoundaryNorm(levels, ncolors=n_data_colors) return (cmap, norm) # File: matplotlib-main/lib/matplotlib/container.py from matplotlib import cbook from matplotlib.artist import Artist class Container(tuple): def __repr__(self): return f'<{type(self).__name__} object of {len(self)} artists>' def __new__(cls, *args, **kwargs): return tuple.__new__(cls, args[0]) def __init__(self, kl, label=None): self._callbacks = cbook.CallbackRegistry(signals=['pchanged']) self._remove_method = None self._label = str(label) if label is not None else None def remove(self): for c in cbook.flatten(self, scalarp=lambda x: isinstance(x, Artist)): if c is not None: c.remove() if self._remove_method: self._remove_method(self) def get_children(self): return [child for child in cbook.flatten(self) if child is not None] get_label = Artist.get_label set_label = Artist.set_label add_callback = Artist.add_callback remove_callback = Artist.remove_callback pchanged = Artist.pchanged class BarContainer(Container): def __init__(self, patches, errorbar=None, *, datavalues=None, orientation=None, **kwargs): self.patches = patches self.errorbar = errorbar self.datavalues = datavalues self.orientation = orientation super().__init__(patches, **kwargs) class ErrorbarContainer(Container): def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs): self.lines = lines self.has_xerr = has_xerr self.has_yerr = has_yerr super().__init__(lines, **kwargs) class StemContainer(Container): def __init__(self, markerline_stemlines_baseline, **kwargs): (markerline, stemlines, baseline) = markerline_stemlines_baseline self.markerline = markerline self.stemlines = stemlines self.baseline = baseline super().__init__(markerline_stemlines_baseline, **kwargs) # File: matplotlib-main/lib/matplotlib/contour.py """""" from contextlib import ExitStack import functools import math from numbers import Integral import numpy as np from numpy import ma import matplotlib as mpl from matplotlib import _api, _docstring from matplotlib.backend_bases import MouseButton from matplotlib.lines import Line2D from matplotlib.path import Path from matplotlib.text import Text import matplotlib.ticker as ticker import matplotlib.cm as cm import matplotlib.colors as mcolors import matplotlib.collections as mcoll import matplotlib.font_manager as font_manager import matplotlib.cbook as cbook import matplotlib.patches as mpatches import matplotlib.transforms as mtransforms def _contour_labeler_event_handler(cs, inline, inline_spacing, event): canvas = cs.axes.get_figure(root=True).canvas is_button = event.name == 'button_press_event' is_key = event.name == 'key_press_event' if is_button and event.button == MouseButton.MIDDLE or (is_key and event.key in ['escape', 'enter']): canvas.stop_event_loop() elif is_button and event.button == MouseButton.RIGHT or (is_key and event.key in ['backspace', 'delete']): if not inline: cs.pop_label() canvas.draw() elif is_button and event.button == MouseButton.LEFT or (is_key and event.key is not None): if cs.axes.contains(event)[0]: cs.add_label_near(event.x, event.y, transform=False, inline=inline, inline_spacing=inline_spacing) canvas.draw() class ContourLabeler: def clabel(self, levels=None, *, fontsize=None, inline=True, inline_spacing=5, fmt=None, colors=None, use_clabeltext=False, manual=False, rightside_up=True, zorder=None): if fmt is None: fmt = ticker.ScalarFormatter(useOffset=False) fmt.create_dummy_axis() self.labelFmt = fmt self._use_clabeltext = use_clabeltext self.labelManual = manual self.rightside_up = rightside_up self._clabel_zorder = 2 + self.get_zorder() if zorder is None else zorder if levels is None: levels = self.levels indices = list(range(len(self.cvalues))) else: levlabs = list(levels) (indices, levels) = ([], []) for (i, lev) in enumerate(self.levels): if lev in levlabs: indices.append(i) levels.append(lev) if len(levels) < len(levlabs): raise ValueError(f"Specified levels {levlabs} don't match available levels {self.levels}") self.labelLevelList = levels self.labelIndiceList = indices self._label_font_props = font_manager.FontProperties(size=fontsize) if colors is None: self.labelMappable = self self.labelCValueList = np.take(self.cvalues, self.labelIndiceList) else: cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList)) self.labelCValueList = list(range(len(self.labelLevelList))) self.labelMappable = cm.ScalarMappable(cmap=cmap, norm=mcolors.NoNorm()) self.labelXYs = [] if np.iterable(manual): for (x, y) in manual: self.add_label_near(x, y, inline, inline_spacing) elif manual: print('Select label locations manually using first mouse button.') print('End manual selection with second mouse button.') if not inline: print('Remove last label by clicking third mouse button.') mpl._blocking_input.blocking_input_loop(self.axes.get_figure(root=True), ['button_press_event', 'key_press_event'], timeout=-1, handler=functools.partial(_contour_labeler_event_handler, self, inline, inline_spacing)) else: self.labels(inline, inline_spacing) return cbook.silent_list('text.Text', self.labelTexts) def print_label(self, linecontour, labelwidth): return len(linecontour) > 10 * labelwidth or (len(linecontour) and (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()) def too_close(self, x, y, lw): thresh = (1.2 * lw) ** 2 return any(((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh for loc in self.labelXYs)) def _get_nth_label_width(self, nth): fig = self.axes.get_figure(root=False) renderer = fig.get_figure(root=True)._get_renderer() return Text(0, 0, self.get_text(self.labelLevelList[nth], self.labelFmt), figure=fig, fontproperties=self._label_font_props).get_window_extent(renderer).width def get_text(self, lev, fmt): if isinstance(lev, str): return lev elif isinstance(fmt, dict): return fmt.get(lev, '%1.3f') elif callable(getattr(fmt, 'format_ticks', None)): return fmt.format_ticks([*self.labelLevelList, lev])[-1] elif callable(fmt): return fmt(lev) else: return fmt % lev def locate_label(self, linecontour, labelwidth): ctr_size = len(linecontour) n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1 block_size = ctr_size if n_blocks == 1 else int(labelwidth) xx = np.resize(linecontour[:, 0], (n_blocks, block_size)) yy = np.resize(linecontour[:, 1], (n_blocks, block_size)) yfirst = yy[:, :1] ylast = yy[:, -1:] xfirst = xx[:, :1] xlast = xx[:, -1:] s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst) l = np.hypot(xlast - xfirst, ylast - yfirst) with np.errstate(divide='ignore', invalid='ignore'): distances = (abs(s) / l).sum(axis=-1) hbsize = block_size // 2 adist = np.argsort(distances) for idx in np.append(adist, adist[0]): (x, y) = (xx[idx, hbsize], yy[idx, hbsize]) if not self.too_close(x, y, labelwidth): break return (x, y, (idx * block_size + hbsize) % ctr_size) def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5): xys = path.vertices codes = path.codes pos = self.get_transform().inverted().transform(screen_pos) if not np.allclose(pos, xys[idx]): xys = np.insert(xys, idx, pos, axis=0) codes = np.insert(codes, idx, Path.LINETO) movetos = (codes == Path.MOVETO).nonzero()[0] start = movetos[movetos <= idx][-1] try: stop = movetos[movetos > idx][0] except IndexError: stop = len(codes) cc_xys = xys[start:stop] idx -= start is_closed_path = codes[stop - 1] == Path.CLOSEPOLY if is_closed_path: cc_xys = np.concatenate([cc_xys[idx:-1], cc_xys[:idx + 1]]) idx = 0 def interp_vec(x, xp, fp): return [np.interp(x, xp, col) for col in fp.T] screen_xys = self.get_transform().transform(cc_xys) path_cpls = np.insert(np.cumsum(np.hypot(*np.diff(screen_xys, axis=0).T)), 0, 0) path_cpls -= path_cpls[idx] target_cpls = np.array([-lw / 2, lw / 2]) if is_closed_path: target_cpls[0] += path_cpls[-1] - path_cpls[0] ((sx0, sx1), (sy0, sy1)) = interp_vec(target_cpls, path_cpls, screen_xys) angle = np.rad2deg(np.arctan2(sy1 - sy0, sx1 - sx0)) if self.rightside_up: angle = (angle + 90) % 180 - 90 target_cpls += [-spacing, +spacing] (i0, i1) = np.interp(target_cpls, path_cpls, range(len(path_cpls)), left=-1, right=-1) i0 = math.floor(i0) i1 = math.ceil(i1) ((x0, x1), (y0, y1)) = interp_vec(target_cpls, path_cpls, cc_xys) new_xy_blocks = [] new_code_blocks = [] if is_closed_path: if i0 != -1 and i1 != -1: points = cc_xys[i1:i0 + 1] new_xy_blocks.extend([[(x1, y1)], points, [(x0, y0)]]) nlines = len(points) + 1 new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * nlines]) else: if i0 != -1: new_xy_blocks.extend([cc_xys[:i0 + 1], [(x0, y0)]]) new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (i0 + 1)]) if i1 != -1: new_xy_blocks.extend([[(x1, y1)], cc_xys[i1:]]) new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (len(cc_xys) - i1)]) xys = np.concatenate([xys[:start], *new_xy_blocks, xys[stop:]]) codes = np.concatenate([codes[:start], *new_code_blocks, codes[stop:]]) return (angle, Path(xys, codes)) def add_label(self, x, y, rotation, lev, cvalue): (data_x, data_y) = self.axes.transData.inverted().transform((x, y)) t = Text(data_x, data_y, text=self.get_text(lev, self.labelFmt), rotation=rotation, horizontalalignment='center', verticalalignment='center', zorder=self._clabel_zorder, color=self.labelMappable.to_rgba(cvalue, alpha=self.get_alpha()), fontproperties=self._label_font_props, clip_box=self.axes.bbox) if self._use_clabeltext: (data_rotation,) = self.axes.transData.inverted().transform_angles([rotation], [[x, y]]) t.set(rotation=data_rotation, transform_rotates_text=True) self.labelTexts.append(t) self.labelCValues.append(cvalue) self.labelXYs.append((x, y)) self.axes.add_artist(t) def add_label_near(self, x, y, inline=True, inline_spacing=5, transform=None): if transform is None: transform = self.axes.transData if transform: (x, y) = transform.transform((x, y)) (idx_level_min, idx_vtx_min, proj) = self._find_nearest_contour((x, y), self.labelIndiceList) path = self._paths[idx_level_min] level = self.labelIndiceList.index(idx_level_min) label_width = self._get_nth_label_width(level) (rotation, path) = self._split_path_and_get_label_rotation(path, idx_vtx_min, proj, label_width, inline_spacing) self.add_label(*proj, rotation, self.labelLevelList[idx_level_min], self.labelCValueList[idx_level_min]) if inline: self._paths[idx_level_min] = path def pop_label(self, index=-1): self.labelCValues.pop(index) t = self.labelTexts.pop(index) t.remove() def labels(self, inline, inline_spacing): for (idx, (icon, lev, cvalue)) in enumerate(zip(self.labelIndiceList, self.labelLevelList, self.labelCValueList)): trans = self.get_transform() label_width = self._get_nth_label_width(idx) additions = [] for subpath in self._paths[icon]._iter_connected_components(): screen_xys = trans.transform(subpath.vertices) if self.print_label(screen_xys, label_width): (x, y, idx) = self.locate_label(screen_xys, label_width) (rotation, path) = self._split_path_and_get_label_rotation(subpath, idx, (x, y), label_width, inline_spacing) self.add_label(x, y, rotation, lev, cvalue) if inline: additions.append(path) else: additions.append(subpath) if inline: self._paths[icon] = Path.make_compound_path(*additions) def remove(self): super().remove() for text in self.labelTexts: text.remove() def _find_closest_point_on_path(xys, p): if len(xys) == 1: return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0)) dxys = xys[1:] - xys[:-1] norms = (dxys ** 2).sum(axis=1) norms[norms == 0] = 1 rel_projs = np.clip(((p - xys[:-1]) * dxys).sum(axis=1) / norms, 0, 1)[:, None] projs = xys[:-1] + rel_projs * dxys d2s = ((projs - p) ** 2).sum(axis=1) imin = np.argmin(d2s) return (d2s[imin], projs[imin], (imin, imin + 1)) _docstring.interpd.update(contour_set_attributes='\nAttributes\n----------\nax : `~matplotlib.axes.Axes`\n The Axes object in which the contours are drawn.\n\ncollections : `.silent_list` of `.PathCollection`\\s\n The `.Artist`\\s representing the contour. This is a list of\n `.PathCollection`\\s for both line and filled contours.\n\nlevels : array\n The values of the contour levels.\n\nlayers : array\n Same as levels for line contours; half-way between\n levels for filled contours. See ``ContourSet._process_colors``.\n') @_docstring.dedent_interpd class ContourSet(ContourLabeler, mcoll.Collection): def __init__(self, ax, *args, levels=None, filled=False, linewidths=None, linestyles=None, hatches=(None,), alpha=None, origin=None, extent=None, cmap=None, colors=None, norm=None, vmin=None, vmax=None, extend='neither', antialiased=None, nchunk=0, locator=None, transform=None, negative_linestyles=None, clip_path=None, **kwargs): if antialiased is None and filled: antialiased = False super().__init__(antialiaseds=antialiased, alpha=alpha, clip_path=clip_path, transform=transform) self.axes = ax self.levels = levels self.filled = filled self.hatches = hatches self.origin = origin self.extent = extent self.colors = colors self.extend = extend self.nchunk = nchunk self.locator = locator if isinstance(norm, mcolors.LogNorm) or isinstance(self.locator, ticker.LogLocator): self.logscale = True if norm is None: norm = mcolors.LogNorm() else: self.logscale = False _api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin) if self.extent is not None and len(self.extent) != 4: raise ValueError("If given, 'extent' must be None or (x0, x1, y0, y1)") if self.colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if self.origin == 'image': self.origin = mpl.rcParams['image.origin'] self._orig_linestyles = linestyles self.negative_linestyles = negative_linestyles if self.negative_linestyles is None: self.negative_linestyles = mpl.rcParams['contour.negative_linestyle'] kwargs = self._process_args(*args, **kwargs) self._process_levels() self._extend_min = self.extend in ['min', 'both'] self._extend_max = self.extend in ['max', 'both'] if self.colors is not None: if mcolors.is_color_like(self.colors): color_sequence = [self.colors] else: color_sequence = self.colors ncolors = len(self.levels) if self.filled: ncolors -= 1 i0 = 0 use_set_under_over = False total_levels = ncolors + int(self._extend_min) + int(self._extend_max) if len(color_sequence) == total_levels and (self._extend_min or self._extend_max): use_set_under_over = True if self._extend_min: i0 = 1 cmap = mcolors.ListedColormap(color_sequence[i0:None], N=ncolors) if use_set_under_over: if self._extend_min: cmap.set_under(color_sequence[0]) if self._extend_max: cmap.set_over(color_sequence[-1]) self.labelTexts = [] self.labelCValues = [] self.set_cmap(cmap) if norm is not None: self.set_norm(norm) with self.norm.callbacks.blocked(signal='changed'): if vmin is not None: self.norm.vmin = vmin if vmax is not None: self.norm.vmax = vmax self.norm._changed() self._process_colors() if self._paths is None: self._paths = self._make_paths_from_contour_generator() if self.filled: if linewidths is not None: _api.warn_external('linewidths is ignored by contourf') (lowers, uppers) = self._get_lowers_and_uppers() self.set(edgecolor='none', zorder=kwargs.pop('zorder', 1)) else: self.set(facecolor='none', linewidths=self._process_linewidths(linewidths), linestyle=self._process_linestyles(linestyles), zorder=kwargs.pop('zorder', 2), label='_nolegend_') self.axes.add_collection(self, autolim=False) self.sticky_edges.x[:] = [self._mins[0], self._maxs[0]] self.sticky_edges.y[:] = [self._mins[1], self._maxs[1]] self.axes.update_datalim([self._mins, self._maxs]) self.axes.autoscale_view(tight=True) self.changed() if kwargs: _api.warn_external('The following kwargs were not used by contour: ' + ', '.join(map(repr, kwargs))) allsegs = property(lambda self: [[subp.vertices for subp in p._iter_connected_components()] for p in self.get_paths()]) allkinds = property(lambda self: [[subp.codes for subp in p._iter_connected_components()] for p in self.get_paths()]) alpha = property(lambda self: self.get_alpha()) linestyles = property(lambda self: self._orig_linestyles) def get_transform(self): if self._transform is None: self._transform = self.axes.transData elif not isinstance(self._transform, mtransforms.Transform) and hasattr(self._transform, '_as_mpl_transform'): self._transform = self._transform._as_mpl_transform(self.axes) return self._transform def __getstate__(self): state = self.__dict__.copy() state['_contour_generator'] = None return state def legend_elements(self, variable_name='x', str_format=str): artists = [] labels = [] if self.filled: (lowers, uppers) = self._get_lowers_and_uppers() n_levels = len(self._paths) for idx in range(n_levels): artists.append(mpatches.Rectangle((0, 0), 1, 1, facecolor=self.get_facecolor()[idx], hatch=self.hatches[idx % len(self.hatches)])) lower = str_format(lowers[idx]) upper = str_format(uppers[idx]) if idx == 0 and self.extend in ('min', 'both'): labels.append(f'${variable_name} \\leq {lower}s$') elif idx == n_levels - 1 and self.extend in ('max', 'both'): labels.append(f'${variable_name} > {upper}s$') else: labels.append(f'${lower} < {variable_name} \\leq {upper}$') else: for (idx, level) in enumerate(self.levels): artists.append(Line2D([], [], color=self.get_edgecolor()[idx], linewidth=self.get_linewidths()[idx], linestyle=self.get_linestyles()[idx])) labels.append(f'${variable_name} = {str_format(level)}$') return (artists, labels) def _process_args(self, *args, **kwargs): self.levels = args[0] allsegs = args[1] allkinds = args[2] if len(args) > 2 else None self.zmax = np.max(self.levels) self.zmin = np.min(self.levels) if allkinds is None: allkinds = [[None] * len(segs) for segs in allsegs] if self.filled: if len(allsegs) != len(self.levels) - 1: raise ValueError('must be one less number of segments as levels') elif len(allsegs) != len(self.levels): raise ValueError('must be same number of segments as levels') if len(allkinds) != len(allsegs): raise ValueError('allkinds has different length to allsegs') flatseglist = [s for seg in allsegs for s in seg] points = np.concatenate(flatseglist, axis=0) self._mins = points.min(axis=0) self._maxs = points.max(axis=0) self._paths = [Path.make_compound_path(*map(Path, segs, kinds)) for (segs, kinds) in zip(allsegs, allkinds)] return kwargs def _make_paths_from_contour_generator(self): if self._paths is not None: return self._paths cg = self._contour_generator empty_path = Path(np.empty((0, 2))) vertices_and_codes = map(cg.create_filled_contour, *self._get_lowers_and_uppers()) if self.filled else map(cg.create_contour, self.levels) return [Path(np.concatenate(vs), np.concatenate(cs)) if len(vs) else empty_path for (vs, cs) in vertices_and_codes] def _get_lowers_and_uppers(self): lowers = self._levels[:-1] if self.zmin == lowers[0]: lowers = lowers.copy() if self.logscale: lowers[0] = 0.99 * self.zmin else: lowers[0] -= 1 uppers = self._levels[1:] return (lowers, uppers) def changed(self): if not hasattr(self, 'cvalues'): self._process_colors() self.norm.autoscale_None(self.levels) self.set_array(self.cvalues) self.update_scalarmappable() alphas = np.broadcast_to(self.get_alpha(), len(self.cvalues)) for (label, cv, alpha) in zip(self.labelTexts, self.labelCValues, alphas): label.set_alpha(alpha) label.set_color(self.labelMappable.to_rgba(cv)) super().changed() def _autolev(self, N): if self.locator is None: if self.logscale: self.locator = ticker.LogLocator() else: self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1) lev = self.locator.tick_values(self.zmin, self.zmax) try: if self.locator._symmetric: return lev except AttributeError: pass under = np.nonzero(lev < self.zmin)[0] i0 = under[-1] if len(under) else 0 over = np.nonzero(lev > self.zmax)[0] i1 = over[0] + 1 if len(over) else len(lev) if self.extend in ('min', 'both'): i0 += 1 if self.extend in ('max', 'both'): i1 -= 1 if i1 - i0 < 3: (i0, i1) = (0, len(lev)) return lev[i0:i1] def _process_contour_level_args(self, args, z_dtype): if self.levels is None: if args: levels_arg = args[0] elif np.issubdtype(z_dtype, bool): if self.filled: levels_arg = [0, 0.5, 1] else: levels_arg = [0.5] else: levels_arg = 7 else: levels_arg = self.levels if isinstance(levels_arg, Integral): self.levels = self._autolev(levels_arg) else: self.levels = np.asarray(levels_arg, np.float64) if self.filled and len(self.levels) < 2: raise ValueError('Filled contours require at least 2 levels.') if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0: raise ValueError('Contour levels must be increasing') def _process_levels(self): self._levels = list(self.levels) if self.logscale: (lower, upper) = (1e-250, 1e+250) else: (lower, upper) = (-1e+250, 1e+250) if self.extend in ('both', 'min'): self._levels.insert(0, lower) if self.extend in ('both', 'max'): self._levels.append(upper) self._levels = np.asarray(self._levels) if not self.filled: self.layers = self.levels return if self.logscale: self.layers = np.sqrt(self._levels[:-1]) * np.sqrt(self._levels[1:]) else: self.layers = 0.5 * (self._levels[:-1] + self._levels[1:]) def _process_colors(self): self.monochrome = self.cmap.monochrome if self.colors is not None: (i0, i1) = (0, len(self.levels)) if self.filled: i1 -= 1 if self.extend in ('both', 'min'): i0 -= 1 if self.extend in ('both', 'max'): i1 += 1 self.cvalues = list(range(i0, i1)) self.set_norm(mcolors.NoNorm()) else: self.cvalues = self.layers self.norm.autoscale_None(self.levels) self.set_array(self.cvalues) self.update_scalarmappable() if self.extend in ('both', 'max', 'min'): self.norm.clip = False def _process_linewidths(self, linewidths): Nlev = len(self.levels) if linewidths is None: default_linewidth = mpl.rcParams['contour.linewidth'] if default_linewidth is None: default_linewidth = mpl.rcParams['lines.linewidth'] return [default_linewidth] * Nlev elif not np.iterable(linewidths): return [linewidths] * Nlev else: linewidths = list(linewidths) return (linewidths * math.ceil(Nlev / len(linewidths)))[:Nlev] def _process_linestyles(self, linestyles): Nlev = len(self.levels) if linestyles is None: tlinestyles = ['solid'] * Nlev if self.monochrome: eps = -(self.zmax - self.zmin) * 1e-15 for (i, lev) in enumerate(self.levels): if lev < eps: tlinestyles[i] = self.negative_linestyles elif isinstance(linestyles, str): tlinestyles = [linestyles] * Nlev elif np.iterable(linestyles): tlinestyles = list(linestyles) if len(tlinestyles) < Nlev: nreps = int(np.ceil(Nlev / len(linestyles))) tlinestyles = tlinestyles * nreps if len(tlinestyles) > Nlev: tlinestyles = tlinestyles[:Nlev] else: raise ValueError('Unrecognized type for linestyles kwarg') return tlinestyles def _find_nearest_contour(self, xy, indices=None): if self.filled: raise ValueError('Method does not support filled contours') if indices is None: indices = range(len(self._paths)) d2min = np.inf idx_level_min = idx_vtx_min = proj_min = None for idx_level in indices: path = self._paths[idx_level] idx_vtx_start = 0 for subpath in path._iter_connected_components(): if not len(subpath.vertices): continue lc = self.get_transform().transform(subpath.vertices) (d2, proj, leg) = _find_closest_point_on_path(lc, xy) if d2 < d2min: d2min = d2 idx_level_min = idx_level idx_vtx_min = leg[1] + idx_vtx_start proj_min = proj idx_vtx_start += len(subpath) return (idx_level_min, idx_vtx_min, proj_min) def find_nearest_contour(self, x, y, indices=None, pixel=True): segment = index = d2 = None with ExitStack() as stack: if not pixel: stack.enter_context(self._cm_set(transform=mtransforms.IdentityTransform())) (i_level, i_vtx, (xmin, ymin)) = self._find_nearest_contour((x, y), indices) if i_level is not None: cc_cumlens = np.cumsum([*map(len, self._paths[i_level]._iter_connected_components())]) segment = cc_cumlens.searchsorted(i_vtx, 'right') index = i_vtx if segment == 0 else i_vtx - cc_cumlens[segment - 1] d2 = (xmin - x) ** 2 + (ymin - y) ** 2 return (i_level, segment, index, xmin, ymin, d2) def draw(self, renderer): paths = self._paths n_paths = len(paths) if not self.filled or all((hatch is None for hatch in self.hatches)): super().draw(renderer) return for idx in range(n_paths): with cbook._setattr_cm(self, _paths=[paths[idx]]), self._cm_set(hatch=self.hatches[idx % len(self.hatches)], array=[self.get_array()[idx]], linewidths=[self.get_linewidths()[idx % len(self.get_linewidths())]], linestyles=[self.get_linestyles()[idx % len(self.get_linestyles())]]): super().draw(renderer) @_docstring.dedent_interpd class QuadContourSet(ContourSet): def _process_args(self, *args, corner_mask=None, algorithm=None, **kwargs): if args and isinstance(args[0], QuadContourSet): if self.levels is None: self.levels = args[0].levels self.zmin = args[0].zmin self.zmax = args[0].zmax self._corner_mask = args[0]._corner_mask contour_generator = args[0]._contour_generator self._mins = args[0]._mins self._maxs = args[0]._maxs self._algorithm = args[0]._algorithm else: import contourpy if algorithm is None: algorithm = mpl.rcParams['contour.algorithm'] mpl.rcParams.validate['contour.algorithm'](algorithm) self._algorithm = algorithm if corner_mask is None: if self._algorithm == 'mpl2005': corner_mask = False else: corner_mask = mpl.rcParams['contour.corner_mask'] self._corner_mask = corner_mask (x, y, z) = self._contour_args(args, kwargs) contour_generator = contourpy.contour_generator(x, y, z, name=self._algorithm, corner_mask=self._corner_mask, line_type=contourpy.LineType.SeparateCode, fill_type=contourpy.FillType.OuterCode, chunk_size=self.nchunk) t = self.get_transform() if t != self.axes.transData and any(t.contains_branch_seperately(self.axes.transData)): trans_to_data = t - self.axes.transData pts = np.vstack([x.flat, y.flat]).T transformed_pts = trans_to_data.transform(pts) x = transformed_pts[..., 0] y = transformed_pts[..., 1] self._mins = [ma.min(x), ma.min(y)] self._maxs = [ma.max(x), ma.max(y)] self._contour_generator = contour_generator return kwargs def _contour_args(self, args, kwargs): if self.filled: fn = 'contourf' else: fn = 'contour' nargs = len(args) if 0 < nargs <= 2: (z, *args) = args z = ma.asarray(z) (x, y) = self._initialize_x_y(z) elif 2 < nargs <= 4: (x, y, z_orig, *args) = args (x, y, z) = self._check_xyz(x, y, z_orig, kwargs) else: raise _api.nargs_error(fn, takes='from 1 to 4', given=nargs) z = ma.masked_invalid(z, copy=False) self.zmax = z.max().astype(float) self.zmin = z.min().astype(float) if self.logscale and self.zmin <= 0: z = ma.masked_where(z <= 0, z) _api.warn_external('Log scale: values of z <= 0 have been masked') self.zmin = z.min().astype(float) self._process_contour_level_args(args, z.dtype) return (x, y, z) def _check_xyz(self, x, y, z, kwargs): (x, y) = self.axes._process_unit_info([('x', x), ('y', y)], kwargs) x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) z = ma.asarray(z) if z.ndim != 2: raise TypeError(f'Input z must be 2D, not {z.ndim}D') if z.shape[0] < 2 or z.shape[1] < 2: raise TypeError(f'Input z must be at least a (2, 2) shaped array, but has shape {z.shape}') (Ny, Nx) = z.shape if x.ndim != y.ndim: raise TypeError(f'Number of dimensions of x ({x.ndim}) and y ({y.ndim}) do not match') if x.ndim == 1: (nx,) = x.shape (ny,) = y.shape if nx != Nx: raise TypeError(f'Length of x ({nx}) must match number of columns in z ({Nx})') if ny != Ny: raise TypeError(f'Length of y ({ny}) must match number of rows in z ({Ny})') (x, y) = np.meshgrid(x, y) elif x.ndim == 2: if x.shape != z.shape: raise TypeError(f'Shapes of x {x.shape} and z {z.shape} do not match') if y.shape != z.shape: raise TypeError(f'Shapes of y {y.shape} and z {z.shape} do not match') else: raise TypeError(f'Inputs x and y must be 1D or 2D, not {x.ndim}D') return (x, y, z) def _initialize_x_y(self, z): if z.ndim != 2: raise TypeError(f'Input z must be 2D, not {z.ndim}D') elif z.shape[0] < 2 or z.shape[1] < 2: raise TypeError(f'Input z must be at least a (2, 2) shaped array, but has shape {z.shape}') else: (Ny, Nx) = z.shape if self.origin is None: if self.extent is None: return np.meshgrid(np.arange(Nx), np.arange(Ny)) else: (x0, x1, y0, y1) = self.extent x = np.linspace(x0, x1, Nx) y = np.linspace(y0, y1, Ny) return np.meshgrid(x, y) if self.extent is None: (x0, x1, y0, y1) = (0, Nx, 0, Ny) else: (x0, x1, y0, y1) = self.extent dx = (x1 - x0) / Nx dy = (y1 - y0) / Ny x = x0 + (np.arange(Nx) + 0.5) * dx y = y0 + (np.arange(Ny) + 0.5) * dy if self.origin == 'upper': y = y[::-1] return np.meshgrid(x, y) _docstring.interpd.update(contour_doc='\n`.contour` and `.contourf` draw contour lines and filled contours,\nrespectively. Except as noted, function signatures and return values\nare the same for both versions.\n\nParameters\n----------\nX, Y : array-like, optional\n The coordinates of the values in *Z*.\n\n *X* and *Y* must both be 2D with the same shape as *Z* (e.g.\n created via `numpy.meshgrid`), or they must both be 1-D such\n that ``len(X) == N`` is the number of columns in *Z* and\n ``len(Y) == M`` is the number of rows in *Z*.\n\n *X* and *Y* must both be ordered monotonically.\n\n If not given, they are assumed to be integer indices, i.e.\n ``X = range(N)``, ``Y = range(M)``.\n\nZ : (M, N) array-like\n The height values over which the contour is drawn. Color-mapping is\n controlled by *cmap*, *norm*, *vmin*, and *vmax*.\n\nlevels : int or array-like, optional\n Determines the number and positions of the contour lines / regions.\n\n If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries\n to automatically choose no more than *n+1* "nice" contour levels\n between minimum and maximum numeric values of *Z*.\n\n If array-like, draw contour lines at the specified levels.\n The values must be in increasing order.\n\nReturns\n-------\n`~.contour.QuadContourSet`\n\nOther Parameters\n----------------\ncorner_mask : bool, default: :rc:`contour.corner_mask`\n Enable/disable corner masking, which only has an effect if *Z* is\n a masked array. If ``False``, any quad touching a masked point is\n masked out. If ``True``, only the triangular corners of quads\n nearest those points are always masked out, other triangular\n corners comprising three unmasked points are contoured as usual.\n\ncolors : :mpltype:`color` or list of :mpltype:`color`, optional\n The colors of the levels, i.e. the lines for `.contour` and the\n areas for `.contourf`.\n\n The sequence is cycled for the levels in ascending order. If the\n sequence is shorter than the number of levels, it\'s repeated.\n\n As a shortcut, a single color may be used in place of one-element lists, i.e.\n ``\'red\'`` instead of ``[\'red\']`` to color all levels with the same color.\n\n .. versionchanged:: 3.10\n Previously a single color had to be expressed as a string, but now any\n valid color format may be passed.\n\n By default (value *None*), the colormap specified by *cmap*\n will be used.\n\nalpha : float, default: 1\n The alpha blending value, between 0 (transparent) and 1 (opaque).\n\n%(cmap_doc)s\n\n This parameter is ignored if *colors* is set.\n\n%(norm_doc)s\n\n This parameter is ignored if *colors* is set.\n\n%(vmin_vmax_doc)s\n\n If *vmin* or *vmax* are not given, the default color scaling is based on\n *levels*.\n\n This parameter is ignored if *colors* is set.\n\norigin : {*None*, \'upper\', \'lower\', \'image\'}, default: None\n Determines the orientation and exact position of *Z* by specifying\n the position of ``Z[0, 0]``. This is only relevant, if *X*, *Y*\n are not given.\n\n - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.\n - \'lower\': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.\n - \'upper\': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left\n corner.\n - \'image\': Use the value from :rc:`image.origin`.\n\nextent : (x0, x1, y0, y1), optional\n If *origin* is not *None*, then *extent* is interpreted as in\n `.imshow`: it gives the outer pixel boundaries. In this case, the\n position of Z[0, 0] is the center of the pixel, not a corner. If\n *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],\n and (*x1*, *y1*) is the position of Z[-1, -1].\n\n This argument is ignored if *X* and *Y* are specified in the call\n to contour.\n\nlocator : ticker.Locator subclass, optional\n The locator is used to determine the contour levels if they\n are not given explicitly via *levels*.\n Defaults to `~.ticker.MaxNLocator`.\n\nextend : {\'neither\', \'both\', \'min\', \'max\'}, default: \'neither\'\n Determines the ``contourf``-coloring of values that are outside the\n *levels* range.\n\n If \'neither\', values outside the *levels* range are not colored.\n If \'min\', \'max\' or \'both\', color the values below, above or below\n and above the *levels* range.\n\n Values below ``min(levels)`` and above ``max(levels)`` are mapped\n to the under/over values of the `.Colormap`. Note that most\n colormaps do not have dedicated colors for these by default, so\n that the over and under values are the edge values of the colormap.\n You may want to set these values explicitly using\n `.Colormap.set_under` and `.Colormap.set_over`.\n\n .. note::\n\n An existing `.QuadContourSet` does not get notified if\n properties of its colormap are changed. Therefore, an explicit\n call ``QuadContourSet.changed()`` is needed after modifying the\n colormap. The explicit call can be left out, if a colorbar is\n assigned to the `.QuadContourSet` because it internally calls\n ``QuadContourSet.changed()``.\n\n Example::\n\n x = np.arange(1, 10)\n y = x.reshape(-1, 1)\n h = x * y\n\n cs = plt.contourf(h, levels=[10, 30, 50],\n colors=[\'#808080\', \'#A0A0A0\', \'#C0C0C0\'], extend=\'both\')\n cs.cmap.set_over(\'red\')\n cs.cmap.set_under(\'blue\')\n cs.changed()\n\nxunits, yunits : registered units, optional\n Override axis units by specifying an instance of a\n :class:`matplotlib.units.ConversionInterface`.\n\nantialiased : bool, optional\n Enable antialiasing, overriding the defaults. For\n filled contours, the default is *False*. For line contours,\n it is taken from :rc:`lines.antialiased`.\n\nnchunk : int >= 0, optional\n If 0, no subdivision of the domain. Specify a positive integer to\n divide the domain into subdomains of *nchunk* by *nchunk* quads.\n Chunking reduces the maximum length of polygons generated by the\n contouring algorithm which reduces the rendering workload passed\n on to the backend and also requires slightly less RAM. It can\n however introduce rendering artifacts at chunk boundaries depending\n on the backend, the *antialiased* flag and value of *alpha*.\n\nlinewidths : float or array-like, default: :rc:`contour.linewidth`\n *Only applies to* `.contour`.\n\n The line width of the contour lines.\n\n If a number, all levels will be plotted with this linewidth.\n\n If a sequence, the levels in ascending order will be plotted with\n the linewidths in the order specified.\n\n If None, this falls back to :rc:`lines.linewidth`.\n\nlinestyles : {*None*, \'solid\', \'dashed\', \'dashdot\', \'dotted\'}, optional\n *Only applies to* `.contour`.\n\n If *linestyles* is *None*, the default is \'solid\' unless the lines are\n monochrome. In that case, negative contours will instead take their\n linestyle from the *negative_linestyles* argument.\n\n *linestyles* can also be an iterable of the above strings specifying a set\n of linestyles to be used. If this iterable is shorter than the number of\n contour levels it will be repeated as necessary.\n\nnegative_linestyles : {*None*, \'solid\', \'dashed\', \'dashdot\', \'dotted\'}, optional\n *Only applies to* `.contour`.\n\n If *linestyles* is *None* and the lines are monochrome, this argument\n specifies the line style for negative contours.\n\n If *negative_linestyles* is *None*, the default is taken from\n :rc:`contour.negative_linestyles`.\n\n *negative_linestyles* can also be an iterable of the above strings\n specifying a set of linestyles to be used. If this iterable is shorter than\n the number of contour levels it will be repeated as necessary.\n\nhatches : list[str], optional\n *Only applies to* `.contourf`.\n\n A list of cross hatch patterns to use on the filled areas.\n If None, no hatching will be added to the contour.\n\nalgorithm : {\'mpl2005\', \'mpl2014\', \'serial\', \'threaded\'}, optional\n Which contouring algorithm to use to calculate the contour lines and\n polygons. The algorithms are implemented in\n `ContourPy `_, consult the\n `ContourPy documentation `_ for\n further information.\n\n The default is taken from :rc:`contour.algorithm`.\n\nclip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`\n Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.\n\n .. versionadded:: 3.8\n\ndata : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\nNotes\n-----\n1. `.contourf` differs from the MATLAB version in that it does not draw\n the polygon edges. To draw edges, add line contours with calls to\n `.contour`.\n\n2. `.contourf` fills intervals that are closed at the top; that is, for\n boundaries *z1* and *z2*, the filled region is::\n\n z1 < Z <= z2\n\n except for the lowest interval, which is closed on both sides (i.e.\n it includes the lowest value).\n\n3. `.contour` and `.contourf` use a `marching squares\n `_ algorithm to\n compute contour locations. More information can be found in\n `ContourPy documentation `_.\n' % _docstring.interpd.params) # File: matplotlib-main/lib/matplotlib/dates.py """""" import datetime import functools import logging import re from dateutil.rrule import rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY from dateutil.relativedelta import relativedelta import dateutil.parser import dateutil.tz import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, ticker, units __all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange', 'set_epoch', 'get_epoch', 'DateFormatter', 'ConciseDateFormatter', 'AutoDateFormatter', 'DateLocator', 'RRuleLocator', 'AutoDateLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator', 'DayLocator', 'HourLocator', 'MinuteLocator', 'SecondLocator', 'MicrosecondLocator', 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU', 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta', 'DateConverter', 'ConciseDateConverter', 'rrulewrapper') _log = logging.getLogger(__name__) UTC = datetime.timezone.utc def _get_tzinfo(tz=None): tz = mpl._val_or_rc(tz, 'timezone') if tz == 'UTC': return UTC if isinstance(tz, str): tzinfo = dateutil.tz.gettz(tz) if tzinfo is None: raise ValueError(f'{tz} is not a valid timezone as parsed by dateutil.tz.gettz.') return tzinfo if isinstance(tz, datetime.tzinfo): return tz raise TypeError(f'tz must be string or tzinfo subclass, not {tz!r}.') EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal()) MICROSECONDLY = SECONDLY + 1 HOURS_PER_DAY = 24.0 MIN_PER_HOUR = 60.0 SEC_PER_MIN = 60.0 MONTHS_PER_YEAR = 12.0 DAYS_PER_WEEK = 7.0 DAYS_PER_MONTH = 30.0 DAYS_PER_YEAR = 365.0 MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK MUSECONDS_PER_DAY = 1000000.0 * SEC_PER_DAY (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = (MO, TU, WE, TH, FR, SA, SU) WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) _epoch = None def _reset_epoch_test_example(): global _epoch _epoch = None def set_epoch(epoch): global _epoch if _epoch is not None: raise RuntimeError('set_epoch must be called before dates plotted.') _epoch = epoch def get_epoch(): global _epoch _epoch = mpl._val_or_rc(_epoch, 'date.epoch') return _epoch def _dt64_to_ordinalf(d): dseconds = d.astype('datetime64[s]') extra = (d - dseconds).astype('timedelta64[ns]') t0 = np.datetime64(get_epoch(), 's') dt = (dseconds - t0).astype(np.float64) dt += extra.astype(np.float64) / 1000000000.0 dt = dt / SEC_PER_DAY NaT_int = np.datetime64('NaT').astype(np.int64) d_int = d.astype(np.int64) dt[d_int == NaT_int] = np.nan return dt def _from_ordinalf(x, tz=None): tz = _get_tzinfo(tz) dt = np.datetime64(get_epoch()) + np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us') if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'): raise ValueError(f'Date ordinal {x} converts to {dt} (using epoch {get_epoch()}), but Matplotlib dates must be between year 0001 and 9999.') dt = dt.tolist() dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC')) dt = dt.astimezone(tz) if np.abs(x) > 70 * 365: ms = round(dt.microsecond / 20) * 20 if ms == 1000000: dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1) else: dt = dt.replace(microsecond=ms) return dt _from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes='O') _dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse) def datestr2num(d, default=None): if isinstance(d, str): dt = dateutil.parser.parse(d, default=default) return date2num(dt) else: if default is not None: d = [date2num(dateutil.parser.parse(s, default=default)) for s in d] return np.asarray(d) d = np.asarray(d) if not d.size: return d return date2num(_dateutil_parser_parse_np_vectorized(d)) def date2num(d): d = cbook._unpack_to_numpy(d) iterable = np.iterable(d) if not iterable: d = [d] masked = np.ma.is_masked(d) mask = np.ma.getmask(d) d = np.asarray(d) if not np.issubdtype(d.dtype, np.datetime64): if not d.size: return d tzi = getattr(d[0], 'tzinfo', None) if tzi is not None: d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d] d = np.asarray(d) d = d.astype('datetime64[us]') d = np.ma.masked_array(d, mask=mask) if masked else d d = _dt64_to_ordinalf(d) return d if iterable else d[0] def num2date(x, tz=None): tz = _get_tzinfo(tz) return _from_ordinalf_np_vectorized(x, tz).tolist() _ordinalf_to_timedelta_np_vectorized = np.vectorize(lambda x: datetime.timedelta(days=x), otypes='O') def num2timedelta(x): return _ordinalf_to_timedelta_np_vectorized(x).tolist() def drange(dstart, dend, delta): f1 = date2num(dstart) f2 = date2num(dend) step = delta.total_seconds() / SEC_PER_DAY num = int(np.ceil((f2 - f1) / step)) dinterval_end = dstart + num * delta if dinterval_end >= dend: dinterval_end -= delta num -= 1 f2 = date2num(dinterval_end) return np.linspace(f1, f2, num + 1) def _wrap_in_tex(text): p = '([a-zA-Z]+)' ret_text = re.sub(p, '}$\\1$\\\\mathdefault{', text) ret_text = ret_text.replace('-', '{-}').replace(':', '{:}') ret_text = ret_text.replace(' ', '\\;') ret_text = '$\\mathdefault{' + ret_text + '}$' ret_text = ret_text.replace('$\\mathdefault{}$', '') return ret_text class DateFormatter(ticker.Formatter): def __init__(self, fmt, tz=None, *, usetex=None): self.tz = _get_tzinfo(tz) self.fmt = fmt self._usetex = mpl._val_or_rc(usetex, 'text.usetex') def __call__(self, x, pos=0): result = num2date(x, self.tz).strftime(self.fmt) return _wrap_in_tex(result) if self._usetex else result def set_tzinfo(self, tz): self.tz = _get_tzinfo(tz) class ConciseDateFormatter(ticker.Formatter): def __init__(self, locator, tz=None, formats=None, offset_formats=None, zero_formats=None, show_offset=True, *, usetex=None): self._locator = locator self._tz = tz self.defaultfmt = '%Y' if formats: if len(formats) != 6: raise ValueError('formats argument must be a list of 6 format strings (or None)') self.formats = formats else: self.formats = ['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f'] if zero_formats: if len(zero_formats) != 6: raise ValueError('zero_formats argument must be a list of 6 format strings (or None)') self.zero_formats = zero_formats elif formats: self.zero_formats = [''] + self.formats[:-1] else: self.zero_formats = [''] + self.formats[:-1] self.zero_formats[3] = '%b-%d' if offset_formats: if len(offset_formats) != 6: raise ValueError('offset_formats argument must be a list of 6 format strings (or None)') self.offset_formats = offset_formats else: self.offset_formats = ['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M'] self.offset_string = '' self.show_offset = show_offset self._usetex = mpl._val_or_rc(usetex, 'text.usetex') def __call__(self, x, pos=None): formatter = DateFormatter(self.defaultfmt, self._tz, usetex=self._usetex) return formatter(x, pos=pos) def format_ticks(self, values): tickdatetime = [num2date(value, tz=self._tz) for value in values] tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime]) fmts = self.formats zerofmts = self.zero_formats offsetfmts = self.offset_formats show_offset = self.show_offset for level in range(5, -1, -1): unique = np.unique(tickdate[:, level]) if len(unique) > 1: if level < 2 and np.any(unique == 1): show_offset = False break elif level == 0: level = 5 zerovals = [0, 1, 1, 0, 0, 0, 0] labels = [''] * len(tickdate) for nn in range(len(tickdate)): if level < 5: if tickdate[nn][level] == zerovals[level]: fmt = zerofmts[level] else: fmt = fmts[level] elif tickdatetime[nn].second == tickdatetime[nn].microsecond == 0: fmt = zerofmts[level] else: fmt = fmts[level] labels[nn] = tickdatetime[nn].strftime(fmt) if level >= 5: trailing_zeros = min((len(s) - len(s.rstrip('0')) for s in labels if '.' in s), default=None) if trailing_zeros: for nn in range(len(labels)): if '.' in labels[nn]: labels[nn] = labels[nn][:-trailing_zeros].rstrip('.') if show_offset: if self._locator.axis and self._locator.axis.__name__ in ('xaxis', 'yaxis') and self._locator.axis.get_inverted(): self.offset_string = tickdatetime[0].strftime(offsetfmts[level]) else: self.offset_string = tickdatetime[-1].strftime(offsetfmts[level]) if self._usetex: self.offset_string = _wrap_in_tex(self.offset_string) else: self.offset_string = '' if self._usetex: return [_wrap_in_tex(l) for l in labels] else: return labels def get_offset(self): return self.offset_string def format_data_short(self, value): return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S') class AutoDateFormatter(ticker.Formatter): def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *, usetex=None): self._locator = locator self._tz = tz self.defaultfmt = defaultfmt self._formatter = DateFormatter(self.defaultfmt, tz) rcParams = mpl.rcParams self._usetex = mpl._val_or_rc(usetex, 'text.usetex') self.scaled = {DAYS_PER_YEAR: rcParams['date.autoformatter.year'], DAYS_PER_MONTH: rcParams['date.autoformatter.month'], 1: rcParams['date.autoformatter.day'], 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'], 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'], 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'], 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond']} def _set_locator(self, locator): self._locator = locator def __call__(self, x, pos=None): try: locator_unit_scale = float(self._locator._get_unit()) except AttributeError: locator_unit_scale = 1 fmt = next((fmt for (scale, fmt) in sorted(self.scaled.items()) if scale >= locator_unit_scale), self.defaultfmt) if isinstance(fmt, str): self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex) result = self._formatter(x, pos) elif callable(fmt): result = fmt(x, pos) else: raise TypeError(f'Unexpected type passed to {self!r}.') return result class rrulewrapper: def __init__(self, freq, tzinfo=None, **kwargs): kwargs['freq'] = freq self._base_tzinfo = tzinfo self._update_rrule(**kwargs) def set(self, **kwargs): self._construct.update(kwargs) self._update_rrule(**self._construct) def _update_rrule(self, **kwargs): tzinfo = self._base_tzinfo if 'dtstart' in kwargs: dtstart = kwargs['dtstart'] if dtstart.tzinfo is not None: if tzinfo is None: tzinfo = dtstart.tzinfo else: dtstart = dtstart.astimezone(tzinfo) kwargs['dtstart'] = dtstart.replace(tzinfo=None) if 'until' in kwargs: until = kwargs['until'] if until.tzinfo is not None: if tzinfo is not None: until = until.astimezone(tzinfo) else: raise ValueError('until cannot be aware if dtstart is naive and tzinfo is None') kwargs['until'] = until.replace(tzinfo=None) self._construct = kwargs.copy() self._tzinfo = tzinfo self._rrule = rrule(**self._construct) def _attach_tzinfo(self, dt, tzinfo): if hasattr(tzinfo, 'localize'): return tzinfo.localize(dt, is_dst=True) return dt.replace(tzinfo=tzinfo) def _aware_return_wrapper(self, f, returns_list=False): if self._tzinfo is None: return f def normalize_arg(arg): if isinstance(arg, datetime.datetime) and arg.tzinfo is not None: if arg.tzinfo is not self._tzinfo: arg = arg.astimezone(self._tzinfo) return arg.replace(tzinfo=None) return arg def normalize_args(args, kwargs): args = tuple((normalize_arg(arg) for arg in args)) kwargs = {kw: normalize_arg(arg) for (kw, arg) in kwargs.items()} return (args, kwargs) if not returns_list: def inner_func(*args, **kwargs): (args, kwargs) = normalize_args(args, kwargs) dt = f(*args, **kwargs) return self._attach_tzinfo(dt, self._tzinfo) else: def inner_func(*args, **kwargs): (args, kwargs) = normalize_args(args, kwargs) dts = f(*args, **kwargs) return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts] return functools.wraps(f)(inner_func) def __getattr__(self, name): if name in self.__dict__: return self.__dict__[name] f = getattr(self._rrule, name) if name in {'after', 'before'}: return self._aware_return_wrapper(f) elif name in {'xafter', 'xbefore', 'between'}: return self._aware_return_wrapper(f, returns_list=True) else: return f def __setstate__(self, state): self.__dict__.update(state) class DateLocator(ticker.Locator): hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0} def __init__(self, tz=None): self.tz = _get_tzinfo(tz) def set_tzinfo(self, tz): self.tz = _get_tzinfo(tz) def datalim_to_dt(self): (dmin, dmax) = self.axis.get_data_interval() if dmin > dmax: (dmin, dmax) = (dmax, dmin) return (num2date(dmin, self.tz), num2date(dmax, self.tz)) def viewlim_to_dt(self): (vmin, vmax) = self.axis.get_view_interval() if vmin > vmax: (vmin, vmax) = (vmax, vmin) return (num2date(vmin, self.tz), num2date(vmax, self.tz)) def _get_unit(self): return 1 def _get_interval(self): return 1 def nonsingular(self, vmin, vmax): if not np.isfinite(vmin) or not np.isfinite(vmax): return (date2num(datetime.date(1970, 1, 1)), date2num(datetime.date(1970, 1, 2))) if vmax < vmin: (vmin, vmax) = (vmax, vmin) unit = self._get_unit() interval = self._get_interval() if abs(vmax - vmin) < 1e-06: vmin -= 2 * unit * interval vmax += 2 * unit * interval return (vmin, vmax) class RRuleLocator(DateLocator): def __init__(self, o, tz=None): super().__init__(tz) self.rule = o def __call__(self): try: (dmin, dmax) = self.viewlim_to_dt() except ValueError: return [] return self.tick_values(dmin, dmax) def tick_values(self, vmin, vmax): (start, stop) = self._create_rrule(vmin, vmax) dates = self.rule.between(start, stop, True) if len(dates) == 0: return date2num([vmin, vmax]) return self.raise_if_exceeds(date2num(dates)) def _create_rrule(self, vmin, vmax): delta = relativedelta(vmax, vmin) try: start = vmin - delta except (ValueError, OverflowError): start = datetime.datetime(1, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc) try: stop = vmax + delta except (ValueError, OverflowError): stop = datetime.datetime(9999, 12, 31, 23, 59, 59, tzinfo=datetime.timezone.utc) self.rule.set(dtstart=start, until=stop) return (vmin, vmax) def _get_unit(self): freq = self.rule._rrule._freq return self.get_unit_generic(freq) @staticmethod def get_unit_generic(freq): if freq == YEARLY: return DAYS_PER_YEAR elif freq == MONTHLY: return DAYS_PER_MONTH elif freq == WEEKLY: return DAYS_PER_WEEK elif freq == DAILY: return 1.0 elif freq == HOURLY: return 1.0 / HOURS_PER_DAY elif freq == MINUTELY: return 1.0 / MINUTES_PER_DAY elif freq == SECONDLY: return 1.0 / SEC_PER_DAY else: return -1 def _get_interval(self): return self.rule._rrule._interval class AutoDateLocator(DateLocator): def __init__(self, tz=None, minticks=5, maxticks=None, interval_multiples=True): super().__init__(tz=tz) self._freq = YEARLY self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY, SECONDLY, MICROSECONDLY] self.minticks = minticks self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12, MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8} if maxticks is not None: try: self.maxticks.update(maxticks) except TypeError: self.maxticks = dict.fromkeys(self._freqs, maxticks) self.interval_multiples = interval_multiples self.intervald = {YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500, 1000, 2000, 4000, 5000, 10000], MONTHLY: [1, 2, 3, 4, 6], DAILY: [1, 2, 3, 7, 14, 21], HOURLY: [1, 2, 3, 4, 6, 12], MINUTELY: [1, 5, 10, 15, 30], SECONDLY: [1, 5, 10, 15, 30], MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000]} if interval_multiples: self.intervald[DAILY] = [1, 2, 4, 7, 14] self._byranges = [None, range(1, 13), range(1, 32), range(0, 24), range(0, 60), range(0, 60), None] def __call__(self): (dmin, dmax) = self.viewlim_to_dt() locator = self.get_locator(dmin, dmax) return locator() def tick_values(self, vmin, vmax): return self.get_locator(vmin, vmax).tick_values(vmin, vmax) def nonsingular(self, vmin, vmax): if not np.isfinite(vmin) or not np.isfinite(vmax): return (date2num(datetime.date(1970, 1, 1)), date2num(datetime.date(1970, 1, 2))) if vmax < vmin: (vmin, vmax) = (vmax, vmin) if vmin == vmax: vmin = vmin - DAYS_PER_YEAR * 2 vmax = vmax + DAYS_PER_YEAR * 2 return (vmin, vmax) def _get_unit(self): if self._freq in [MICROSECONDLY]: return 1.0 / MUSECONDS_PER_DAY else: return RRuleLocator.get_unit_generic(self._freq) def get_locator(self, dmin, dmax): delta = relativedelta(dmax, dmin) tdelta = dmax - dmin if dmin > dmax: delta = -delta tdelta = -tdelta numYears = float(delta.years) numMonths = numYears * MONTHS_PER_YEAR + delta.months numDays = tdelta.days numHours = numDays * HOURS_PER_DAY + delta.hours numMinutes = numHours * MIN_PER_HOUR + delta.minutes numSeconds = np.floor(tdelta.total_seconds()) numMicroseconds = np.floor(tdelta.total_seconds() * 1000000.0) nums = [numYears, numMonths, numDays, numHours, numMinutes, numSeconds, numMicroseconds] use_rrule_locator = [True] * 6 + [False] byranges = [None, 1, 1, 0, 0, 0, None] for (i, (freq, num)) in enumerate(zip(self._freqs, nums)): if num < self.minticks: byranges[i] = None continue for interval in self.intervald[freq]: if num <= interval * (self.maxticks[freq] - 1): break else: if not (self.interval_multiples and freq == DAILY): _api.warn_external(f"AutoDateLocator was unable to pick an appropriate interval for this date range. It may be necessary to add an interval value to the AutoDateLocator's intervald dictionary. Defaulting to {interval}.") self._freq = freq if self._byranges[i] and self.interval_multiples: byranges[i] = self._byranges[i][::interval] if i in (DAILY, WEEKLY): if interval == 14: byranges[i] = [1, 15] elif interval == 7: byranges[i] = [1, 8, 15, 22] interval = 1 else: byranges[i] = self._byranges[i] break else: interval = 1 if freq == YEARLY and self.interval_multiples: locator = YearLocator(interval, tz=self.tz) elif use_rrule_locator[i]: (_, bymonth, bymonthday, byhour, byminute, bysecond, _) = byranges rrule = rrulewrapper(self._freq, interval=interval, dtstart=dmin, until=dmax, bymonth=bymonth, bymonthday=bymonthday, byhour=byhour, byminute=byminute, bysecond=bysecond) locator = RRuleLocator(rrule, tz=self.tz) else: locator = MicrosecondLocator(interval, tz=self.tz) if date2num(dmin) > 70 * 365 and interval < 1000: _api.warn_external(f'Plotting microsecond time intervals for dates far from the epoch (time origin: {get_epoch()}) is not well-supported. See matplotlib.dates.set_epoch to change the epoch.') locator.set_axis(self.axis) return locator class YearLocator(RRuleLocator): def __init__(self, base=1, month=1, day=1, tz=None): rule = rrulewrapper(YEARLY, interval=base, bymonth=month, bymonthday=day, **self.hms0d) super().__init__(rule, tz=tz) self.base = ticker._Edge_integer(base, 0) def _create_rrule(self, vmin, vmax): ymin = max(self.base.le(vmin.year) * self.base.step, 1) ymax = min(self.base.ge(vmax.year) * self.base.step, 9999) c = self.rule._construct replace = {'year': ymin, 'month': c.get('bymonth', 1), 'day': c.get('bymonthday', 1), 'hour': 0, 'minute': 0, 'second': 0} start = vmin.replace(**replace) stop = start.replace(year=ymax) self.rule.set(dtstart=start, until=stop) return (start, stop) class MonthLocator(RRuleLocator): def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None): if bymonth is None: bymonth = range(1, 13) rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday, interval=interval, **self.hms0d) super().__init__(rule, tz=tz) class WeekdayLocator(RRuleLocator): def __init__(self, byweekday=1, interval=1, tz=None): rule = rrulewrapper(DAILY, byweekday=byweekday, interval=interval, **self.hms0d) super().__init__(rule, tz=tz) class DayLocator(RRuleLocator): def __init__(self, bymonthday=None, interval=1, tz=None): if interval != int(interval) or interval < 1: raise ValueError('interval must be an integer greater than 0') if bymonthday is None: bymonthday = range(1, 32) rule = rrulewrapper(DAILY, bymonthday=bymonthday, interval=interval, **self.hms0d) super().__init__(rule, tz=tz) class HourLocator(RRuleLocator): def __init__(self, byhour=None, interval=1, tz=None): if byhour is None: byhour = range(24) rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval, byminute=0, bysecond=0) super().__init__(rule, tz=tz) class MinuteLocator(RRuleLocator): def __init__(self, byminute=None, interval=1, tz=None): if byminute is None: byminute = range(60) rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval, bysecond=0) super().__init__(rule, tz=tz) class SecondLocator(RRuleLocator): def __init__(self, bysecond=None, interval=1, tz=None): if bysecond is None: bysecond = range(60) rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval) super().__init__(rule, tz=tz) class MicrosecondLocator(DateLocator): def __init__(self, interval=1, tz=None): super().__init__(tz=tz) self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) def set_axis(self, axis): self._wrapped_locator.set_axis(axis) return super().set_axis(axis) def __call__(self): try: (dmin, dmax) = self.viewlim_to_dt() except ValueError: return [] return self.tick_values(dmin, dmax) def tick_values(self, vmin, vmax): (nmin, nmax) = date2num((vmin, vmax)) t0 = np.floor(nmin) nmax = nmax - t0 nmin = nmin - t0 nmin *= MUSECONDS_PER_DAY nmax *= MUSECONDS_PER_DAY ticks = self._wrapped_locator.tick_values(nmin, nmax) ticks = ticks / MUSECONDS_PER_DAY + t0 return ticks def _get_unit(self): return 1.0 / MUSECONDS_PER_DAY def _get_interval(self): return self._interval class DateConverter(units.ConversionInterface): def __init__(self, *, interval_multiples=True): self._interval_multiples = interval_multiples super().__init__() def axisinfo(self, unit, axis): tz = unit majloc = AutoDateLocator(tz=tz, interval_multiples=self._interval_multiples) majfmt = AutoDateFormatter(majloc, tz=tz) datemin = datetime.date(1970, 1, 1) datemax = datetime.date(1970, 1, 2) return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='', default_limits=(datemin, datemax)) @staticmethod def convert(value, unit, axis): return date2num(value) @staticmethod def default_units(x, axis): if isinstance(x, np.ndarray): x = x.ravel() try: x = cbook._safe_first_finite(x) except (TypeError, StopIteration): pass try: return x.tzinfo except AttributeError: pass return None class ConciseDateConverter(DateConverter): def __init__(self, formats=None, zero_formats=None, offset_formats=None, show_offset=True, *, interval_multiples=True): self._formats = formats self._zero_formats = zero_formats self._offset_formats = offset_formats self._show_offset = show_offset self._interval_multiples = interval_multiples super().__init__() def axisinfo(self, unit, axis): tz = unit majloc = AutoDateLocator(tz=tz, interval_multiples=self._interval_multiples) majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats, zero_formats=self._zero_formats, offset_formats=self._offset_formats, show_offset=self._show_offset) datemin = datetime.date(1970, 1, 1) datemax = datetime.date(1970, 1, 2) return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='', default_limits=(datemin, datemax)) class _SwitchableDateConverter: @staticmethod def _get_converter(): converter_cls = {'concise': ConciseDateConverter, 'auto': DateConverter}[mpl.rcParams['date.converter']] interval_multiples = mpl.rcParams['date.interval_multiples'] return converter_cls(interval_multiples=interval_multiples) def axisinfo(self, *args, **kwargs): return self._get_converter().axisinfo(*args, **kwargs) def default_units(self, *args, **kwargs): return self._get_converter().default_units(*args, **kwargs) def convert(self, *args, **kwargs): return self._get_converter().convert(*args, **kwargs) units.registry[np.datetime64] = units.registry[datetime.date] = units.registry[datetime.datetime] = _SwitchableDateConverter() # File: matplotlib-main/lib/matplotlib/dviread.py """""" from collections import namedtuple import enum from functools import lru_cache, partial, wraps import logging import os from pathlib import Path import re import struct import subprocess import sys import numpy as np from matplotlib import _api, cbook _log = logging.getLogger(__name__) _dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale') Page = namedtuple('Page', 'text boxes height width descent') Box = namedtuple('Box', 'x y height width') class Text(namedtuple('Text', 'x y font glyph width')): def _get_pdftexmap_entry(self): return PsfontsMap(find_tex_file('pdftex.map'))[self.font.texname] @property def font_path(self): psfont = self._get_pdftexmap_entry() if psfont.filename is None: raise ValueError('No usable font file found for {} ({}); the font may lack a Type-1 version'.format(psfont.psname.decode('ascii'), psfont.texname.decode('ascii'))) return Path(psfont.filename) @property def font_size(self): return self.font.size @property def font_effects(self): return self._get_pdftexmap_entry().effects @property def glyph_name_or_index(self): entry = self._get_pdftexmap_entry() return _parse_enc(entry.encoding)[self.glyph] if entry.encoding is not None else self.glyph _arg_mapping = dict(raw=lambda dvi, delta: delta, u1=lambda dvi, delta: dvi._read_arg(1, signed=False), u4=lambda dvi, delta: dvi._read_arg(4, signed=False), s4=lambda dvi, delta: dvi._read_arg(4, signed=True), slen=lambda dvi, delta: dvi._read_arg(delta, signed=True) if delta else None, slen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=True), ulen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=False), olen1=lambda dvi, delta: dvi._read_arg(delta + 1, signed=delta == 3)) def _dispatch(table, min, max=None, state=None, args=('raw',)): def decorate(method): get_args = [_arg_mapping[x] for x in args] @wraps(method) def wrapper(self, byte): if state is not None and self.state != state: raise ValueError('state precondition failed') return method(self, *[f(self, byte - min) for f in get_args]) if max is None: table[min] = wrapper else: for i in range(min, max + 1): assert table[i] is None table[i] = wrapper return wrapper return decorate class Dvi: _dtable = [None] * 256 _dispatch = partial(_dispatch, _dtable) def __init__(self, filename, dpi): _log.debug('Dvi: %s', filename) self.file = open(filename, 'rb') self.dpi = dpi self.fonts = {} self.state = _dvistate.pre self._missing_font = None def __enter__(self): return self def __exit__(self, etype, evalue, etrace): self.close() def __iter__(self): while self._read(): yield self._output() def close(self): if not self.file.closed: self.file.close() def _output(self): minx = miny = np.inf maxx = maxy = -np.inf maxy_pure = -np.inf for elt in self.text + self.boxes: if isinstance(elt, Box): (x, y, h, w) = elt e = 0 else: (x, y, font, g, w) = elt (h, e) = font._height_depth_of(g) minx = min(minx, x) miny = min(miny, y - h) maxx = max(maxx, x + w) maxy = max(maxy, y + e) maxy_pure = max(maxy_pure, y) if self._baseline_v is not None: maxy_pure = self._baseline_v self._baseline_v = None if not self.text and (not self.boxes): return Page(text=[], boxes=[], width=0, height=0, descent=0) if self.dpi is None: return Page(text=self.text, boxes=self.boxes, width=maxx - minx, height=maxy_pure - miny, descent=maxy - maxy_pure) d = self.dpi / (72.27 * 2 ** 16) descent = (maxy - maxy_pure) * d text = [Text((x - minx) * d, (maxy - y) * d - descent, f, g, w * d) for (x, y, f, g, w) in self.text] boxes = [Box((x - minx) * d, (maxy - y) * d - descent, h * d, w * d) for (x, y, h, w) in self.boxes] return Page(text=text, boxes=boxes, width=(maxx - minx) * d, height=(maxy_pure - miny) * d, descent=descent) def _read(self): down_stack = [0] self._baseline_v = None while True: byte = self.file.read(1)[0] self._dtable[byte](self, byte) if self._missing_font: raise self._missing_font name = self._dtable[byte].__name__ if name == '_push': down_stack.append(down_stack[-1]) elif name == '_pop': down_stack.pop() elif name == '_down': down_stack[-1] += 1 if self._baseline_v is None and len(getattr(self, 'stack', [])) == 3 and (down_stack[-1] >= 4): self._baseline_v = self.v if byte == 140: return True if self.state is _dvistate.post_post: self.close() return False def _read_arg(self, nbytes, signed=False): return int.from_bytes(self.file.read(nbytes), 'big', signed=signed) @_dispatch(min=0, max=127, state=_dvistate.inpage) def _set_char_immediate(self, char): self._put_char_real(char) if isinstance(self.fonts[self.f], FileNotFoundError): return self.h += self.fonts[self.f]._width_of(char) @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',)) def _set_char(self, char): self._put_char_real(char) if isinstance(self.fonts[self.f], FileNotFoundError): return self.h += self.fonts[self.f]._width_of(char) @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4')) def _set_rule(self, a, b): self._put_rule_real(a, b) self.h += b @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',)) def _put_char(self, char): self._put_char_real(char) def _put_char_real(self, char): font = self.fonts[self.f] if isinstance(font, FileNotFoundError): self._missing_font = font elif font._vf is None: self.text.append(Text(self.h, self.v, font, char, font._width_of(char))) else: scale = font._scale for (x, y, f, g, w) in font._vf[char].text: newf = DviFont(scale=_mul2012(scale, f._scale), tfm=f._tfm, texname=f.texname, vf=f._vf) self.text.append(Text(self.h + _mul2012(x, scale), self.v + _mul2012(y, scale), newf, g, newf._width_of(g))) self.boxes.extend([Box(self.h + _mul2012(x, scale), self.v + _mul2012(y, scale), _mul2012(a, scale), _mul2012(b, scale)) for (x, y, a, b) in font._vf[char].boxes]) @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4')) def _put_rule(self, a, b): self._put_rule_real(a, b) def _put_rule_real(self, a, b): if a > 0 and b > 0: self.boxes.append(Box(self.h, self.v, a, b)) @_dispatch(138) def _nop(self, _): pass @_dispatch(139, state=_dvistate.outer, args=('s4',) * 11) def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p): self.state = _dvistate.inpage self.h = self.v = self.w = self.x = self.y = self.z = 0 self.stack = [] self.text = [] self.boxes = [] @_dispatch(140, state=_dvistate.inpage) def _eop(self, _): self.state = _dvistate.outer del self.h, self.v, self.w, self.x, self.y, self.z, self.stack @_dispatch(141, state=_dvistate.inpage) def _push(self, _): self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z)) @_dispatch(142, state=_dvistate.inpage) def _pop(self, _): (self.h, self.v, self.w, self.x, self.y, self.z) = self.stack.pop() @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',)) def _right(self, b): self.h += b @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',)) def _right_w(self, new_w): if new_w is not None: self.w = new_w self.h += self.w @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',)) def _right_x(self, new_x): if new_x is not None: self.x = new_x self.h += self.x @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',)) def _down(self, a): self.v += a @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',)) def _down_y(self, new_y): if new_y is not None: self.y = new_y self.v += self.y @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',)) def _down_z(self, new_z): if new_z is not None: self.z = new_z self.v += self.z @_dispatch(min=171, max=234, state=_dvistate.inpage) def _fnt_num_immediate(self, k): self.f = k @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',)) def _fnt_num(self, new_f): self.f = new_f @_dispatch(min=239, max=242, args=('ulen1',)) def _xxx(self, datalen): special = self.file.read(datalen) _log.debug('Dvi._xxx: encountered special: %s', ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch for ch in special])) @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1')) def _fnt_def(self, k, c, s, d, a, l): self._fnt_def_real(k, c, s, d, a, l) def _fnt_def_real(self, k, c, s, d, a, l): n = self.file.read(a + l) fontname = n[-l:].decode('ascii') try: tfm = _tfmfile(fontname) except FileNotFoundError as exc: self.fonts[k] = exc return if c != 0 and tfm.checksum != 0 and (c != tfm.checksum): raise ValueError(f'tfm checksum mismatch: {n}') try: vf = _vffile(fontname) except FileNotFoundError: vf = None self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf) @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1')) def _pre(self, i, num, den, mag, k): self.file.read(k) if i != 2: raise ValueError(f'Unknown dvi format {i}') if num != 25400000 or den != 7227 * 2 ** 16: raise ValueError('Nonstandard units in dvi file') if mag != 1000: raise ValueError('Nonstandard magnification in dvi file') self.state = _dvistate.outer @_dispatch(248, state=_dvistate.outer) def _post(self, _): self.state = _dvistate.post_post @_dispatch(249) def _post_post(self, _): raise NotImplementedError @_dispatch(min=250, max=255) def _malformed(self, offset): raise ValueError(f'unknown command: byte {250 + offset}') class DviFont: __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm') def __init__(self, scale, tfm, texname, vf): _api.check_isinstance(bytes, texname=texname) self._scale = scale self._tfm = tfm self.texname = texname self._vf = vf self.size = scale * (72.0 / (72.27 * 2 ** 16)) try: nchars = max(tfm.width) + 1 except ValueError: nchars = 0 self.widths = [1000 * tfm.width.get(char, 0) >> 20 for char in range(nchars)] def __eq__(self, other): return type(self) is type(other) and self.texname == other.texname and (self.size == other.size) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return f'<{type(self).__name__}: {self.texname}>' def _width_of(self, char): width = self._tfm.width.get(char, None) if width is not None: return _mul2012(width, self._scale) _log.debug('No width for char %d in font %s.', char, self.texname) return 0 def _height_depth_of(self, char): result = [] for (metric, name) in ((self._tfm.height, 'height'), (self._tfm.depth, 'depth')): value = metric.get(char, None) if value is None: _log.debug('No %s for char %d in font %s', name, char, self.texname) result.append(0) else: result.append(_mul2012(value, self._scale)) if re.match(b'^cmsy\\d+$', self.texname) and char == 0: result[-1] = 0 return result class Vf(Dvi): def __init__(self, filename): super().__init__(filename, 0) try: self._first_font = None self._chars = {} self._read() finally: self.close() def __getitem__(self, code): return self._chars[code] def _read(self): packet_char = packet_ends = None packet_len = packet_width = None while True: byte = self.file.read(1)[0] if self.state is _dvistate.inpage: byte_at = self.file.tell() - 1 if byte_at == packet_ends: self._finalize_packet(packet_char, packet_width) packet_len = packet_char = packet_width = None elif byte_at > packet_ends: raise ValueError('Packet length mismatch in vf file') else: if byte in (139, 140) or byte >= 243: raise ValueError(f'Inappropriate opcode {byte} in vf file') Dvi._dtable[byte](self, byte) continue if byte < 242: packet_len = byte packet_char = self._read_arg(1) packet_width = self._read_arg(3) packet_ends = self._init_packet(byte) self.state = _dvistate.inpage elif byte == 242: packet_len = self._read_arg(4) packet_char = self._read_arg(4) packet_width = self._read_arg(4) self._init_packet(packet_len) elif 243 <= byte <= 246: k = self._read_arg(byte - 242, byte == 246) c = self._read_arg(4) s = self._read_arg(4) d = self._read_arg(4) a = self._read_arg(1) l = self._read_arg(1) self._fnt_def_real(k, c, s, d, a, l) if self._first_font is None: self._first_font = k elif byte == 247: i = self._read_arg(1) k = self._read_arg(1) x = self.file.read(k) cs = self._read_arg(4) ds = self._read_arg(4) self._pre(i, x, cs, ds) elif byte == 248: break else: raise ValueError(f'Unknown vf opcode {byte}') def _init_packet(self, pl): if self.state != _dvistate.outer: raise ValueError('Misplaced packet in vf file') self.h = self.v = self.w = self.x = self.y = self.z = 0 self.stack = [] self.text = [] self.boxes = [] self.f = self._first_font self._missing_font = None return self.file.tell() + pl def _finalize_packet(self, packet_char, packet_width): if not self._missing_font: self._chars[packet_char] = Page(text=self.text, boxes=self.boxes, width=packet_width, height=None, descent=None) self.state = _dvistate.outer def _pre(self, i, x, cs, ds): if self.state is not _dvistate.pre: raise ValueError('pre command in middle of vf file') if i != 202: raise ValueError(f'Unknown vf format {i}') if len(x): _log.debug('vf file comment: %s', x) self.state = _dvistate.outer def _mul2012(num1, num2): return num1 * num2 >> 20 class Tfm: __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth') def __init__(self, filename): _log.debug('opening tfm file %s', filename) with open(filename, 'rb') as file: header1 = file.read(24) (lh, bc, ec, nw, nh, nd) = struct.unpack('!6H', header1[2:14]) _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d', lh, bc, ec, nw, nh, nd) header2 = file.read(4 * lh) (self.checksum, self.design_size) = struct.unpack('!2I', header2[:8]) char_info = file.read(4 * (ec - bc + 1)) widths = struct.unpack(f'!{nw}i', file.read(4 * nw)) heights = struct.unpack(f'!{nh}i', file.read(4 * nh)) depths = struct.unpack(f'!{nd}i', file.read(4 * nd)) self.width = {} self.height = {} self.depth = {} for (idx, char) in enumerate(range(bc, ec + 1)): byte0 = char_info[4 * idx] byte1 = char_info[4 * idx + 1] self.width[char] = widths[byte0] self.height[char] = heights[byte1 >> 4] self.depth[char] = depths[byte1 & 15] PsFont = namedtuple('PsFont', 'texname psname effects encoding filename') class PsfontsMap: __slots__ = ('_filename', '_unparsed', '_parsed') @lru_cache def __new__(cls, filename): self = object.__new__(cls) self._filename = os.fsdecode(filename) with open(filename, 'rb') as file: self._unparsed = {} for line in file: tfmname = line.split(b' ', 1)[0] self._unparsed.setdefault(tfmname, []).append(line) self._parsed = {} return self def __getitem__(self, texname): assert isinstance(texname, bytes) if texname in self._unparsed: for line in self._unparsed.pop(texname): if self._parse_and_cache_line(line): break try: return self._parsed[texname] except KeyError: raise LookupError(f"An associated PostScript font (required by Matplotlib) could not be found for TeX font {texname.decode('ascii')!r} in {self._filename!r}; this problem can often be solved by installing a suitable PostScript font package in your TeX package manager") from None def _parse_and_cache_line(self, line): if not line or line.startswith((b' ', b'%', b'*', b';', b'#')): return tfmname = basename = special = encodingfile = fontfile = None is_subsetted = is_t1 = is_truetype = False matches = re.finditer(b'"([^"]*)(?:"|$)|(\\S+)', line) for match in matches: (quoted, unquoted) = match.groups() if unquoted: if unquoted.startswith(b'<<'): fontfile = unquoted[2:] elif unquoted.startswith(b'<['): encodingfile = unquoted[2:] elif unquoted.startswith(b'<'): word = unquoted[1:] or next(filter(None, next(matches).groups())) if word.endswith(b'.enc'): encodingfile = word else: fontfile = word is_subsetted = True elif tfmname is None: tfmname = unquoted elif basename is None: basename = unquoted elif quoted: special = quoted effects = {} if special: words = reversed(special.split()) for word in words: if word == b'SlantFont': effects['slant'] = float(next(words)) elif word == b'ExtendFont': effects['extend'] = float(next(words)) if fontfile is not None: if fontfile.endswith((b'.ttf', b'.ttc')): is_truetype = True elif not fontfile.endswith(b'.otf'): is_t1 = True elif basename is not None: is_t1 = True if is_truetype and is_subsetted and (encodingfile is None): return if not is_t1 and ('slant' in effects or 'extend' in effects): return if abs(effects.get('slant', 0)) > 1: return if abs(effects.get('extend', 0)) > 2: return if basename is None: basename = tfmname if encodingfile is not None: encodingfile = find_tex_file(encodingfile) if fontfile is not None: fontfile = find_tex_file(fontfile) self._parsed[tfmname] = PsFont(texname=tfmname, psname=basename, effects=effects, encoding=encodingfile, filename=fontfile) return True def _parse_enc(path): no_comments = re.sub('%.*', '', Path(path).read_text(encoding='ascii')) array = re.search('(?s)\\[(.*)\\]', no_comments).group(1) lines = [line for line in array.split() if line] if all((line.startswith('/') for line in lines)): return [line[1:] for line in lines] else: raise ValueError(f'Failed to parse {path} as Postscript encoding') class _LuatexKpsewhich: @lru_cache def __new__(cls): self = object.__new__(cls) self._proc = self._new_proc() return self def _new_proc(self): return subprocess.Popen(['luatex', '--luaonly', str(cbook._get_data_path('kpsewhich.lua'))], stdin=subprocess.PIPE, stdout=subprocess.PIPE) def search(self, filename): if self._proc.poll() is not None: self._proc = self._new_proc() self._proc.stdin.write(os.fsencode(filename) + b'\n') self._proc.stdin.flush() out = self._proc.stdout.readline().rstrip() return None if out == b'nil' else os.fsdecode(out) @lru_cache def find_tex_file(filename): if isinstance(filename, bytes): filename = filename.decode('utf-8', errors='replace') try: lk = _LuatexKpsewhich() except FileNotFoundError: lk = None if lk: path = lk.search(filename) else: if sys.platform == 'win32': kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'}, 'encoding': 'utf-8'} else: kwargs = {'encoding': sys.getfilesystemencoding(), 'errors': 'surrogateescape'} try: path = cbook._check_and_log_subprocess(['kpsewhich', filename], _log, **kwargs).rstrip('\n') except (FileNotFoundError, RuntimeError): path = None if path: return path else: raise FileNotFoundError(f"Matplotlib's TeX implementation searched for a file named {filename!r} in your texmf tree, but could not find it") @lru_cache def _fontfile(cls, suffix, texname): return cls(find_tex_file(texname + suffix)) _tfmfile = partial(_fontfile, Tfm, '.tfm') _vffile = partial(_fontfile, Vf, '.vf') if __name__ == '__main__': from argparse import ArgumentParser import itertools parser = ArgumentParser() parser.add_argument('filename') parser.add_argument('dpi', nargs='?', type=float, default=None) args = parser.parse_args() with Dvi(args.filename, args.dpi) as dvi: fontmap = PsfontsMap(find_tex_file('pdftex.map')) for page in dvi: print(f'=== new page === (w: {page.width}, h: {page.height}, d: {page.descent})') for (font, group) in itertools.groupby(page.text, lambda text: text.font): print(f"font: {font.texname.decode('latin-1')!r}\tscale: {font._scale / 2 ** 20}") print('x', 'y', 'glyph', 'chr', 'w', '(glyphs)', sep='\t') for text in group: print(text.x, text.y, text.glyph, chr(text.glyph) if chr(text.glyph).isprintable() else '.', text.width, sep='\t') if page.boxes: print('x', 'y', 'h', 'w', '', '(boxes)', sep='\t') for box in page.boxes: print(box.x, box.y, box.height, box.width, sep='\t') # File: matplotlib-main/lib/matplotlib/figure.py """""" from contextlib import ExitStack import inspect import itertools import functools import logging from numbers import Integral import threading import numpy as np import matplotlib as mpl from matplotlib import _blocking_input, backend_bases, _docstring, projections from matplotlib.artist import Artist, allow_rasterization, _finalize_rasterization from matplotlib.backend_bases import DrawEvent, FigureCanvasBase, NonGuiException, MouseButton, _get_renderer import matplotlib._api as _api import matplotlib.cbook as cbook import matplotlib.colorbar as cbar import matplotlib.image as mimage from matplotlib.axes import Axes from matplotlib.gridspec import GridSpec, SubplotParams from matplotlib.layout_engine import ConstrainedLayoutEngine, TightLayoutEngine, LayoutEngine, PlaceHolderLayoutEngine import matplotlib.legend as mlegend from matplotlib.patches import Rectangle from matplotlib.text import Text from matplotlib.transforms import Affine2D, Bbox, BboxTransformTo, TransformedBbox _log = logging.getLogger(__name__) def _stale_figure_callback(self, val): if (fig := self.get_figure(root=False)) is not None: fig.stale = val class _AxesStack: def __init__(self): self._axes = {} self._counter = itertools.count() def as_list(self): return [*self._axes] def remove(self, a): self._axes.pop(a) def bubble(self, a): if a not in self._axes: raise ValueError('Axes has not been added yet') self._axes[a] = next(self._counter) def add(self, a): if a not in self._axes: self._axes[a] = next(self._counter) def current(self): return max(self._axes, key=self._axes.__getitem__, default=None) def __getstate__(self): return {**vars(self), '_counter': max(self._axes.values(), default=0)} def __setstate__(self, state): next_counter = state.pop('_counter') vars(self).update(state) self._counter = itertools.count(next_counter) class FigureBase(Artist): def __init__(self, **kwargs): super().__init__() del self._axes self._suptitle = None self._supxlabel = None self._supylabel = None self._align_label_groups = {'x': cbook.Grouper(), 'y': cbook.Grouper(), 'title': cbook.Grouper()} self._localaxes = [] self.artists = [] self.lines = [] self.patches = [] self.texts = [] self.images = [] self.legends = [] self.subfigs = [] self.stale = True self.suppressComposite = None self.set(**kwargs) def _get_draw_artists(self, renderer): artists = self.get_children() artists.remove(self.patch) artists = sorted((artist for artist in artists if not artist.get_animated()), key=lambda artist: artist.get_zorder()) for ax in self._localaxes: locator = ax.get_axes_locator() ax.apply_aspect(locator(ax, renderer) if locator else None) for child in ax.get_children(): if hasattr(child, 'apply_aspect'): locator = child.get_axes_locator() child.apply_aspect(locator(child, renderer) if locator else None) return artists def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right', which='major'): _api.check_in_list(['major', 'minor', 'both'], which=which) allsubplots = all((ax.get_subplotspec() for ax in self.axes)) if len(self.axes) == 1: for label in self.axes[0].get_xticklabels(which=which): label.set_ha(ha) label.set_rotation(rotation) elif allsubplots: for ax in self.get_axes(): if ax.get_subplotspec().is_last_row(): for label in ax.get_xticklabels(which=which): label.set_ha(ha) label.set_rotation(rotation) else: for label in ax.get_xticklabels(which=which): label.set_visible(False) ax.set_xlabel('') if allsubplots: self.subplots_adjust(bottom=bottom) self.stale = True def get_children(self): return [self.patch, *self.artists, *self._localaxes, *self.lines, *self.patches, *self.texts, *self.images, *self.legends, *self.subfigs] def get_figure(self, root=None): if self._root_figure is self: return self if self._parent is self._root_figure: return self._parent if root is None: message = 'From Matplotlib 3.12 SubFigure.get_figure will by default return the direct parent figure, which may be a SubFigure. To suppress this warning, pass the root parameter. Pass `True` to maintain the old behavior and `False` to opt-in to the future behavior.' _api.warn_deprecated('3.10', message=message) root = True if root: return self._root_figure return self._parent def set_figure(self, fig): no_switch = 'The parent and root figures of a (Sub)Figure are set at instantiation and cannot be changed.' if fig is self._root_figure: _api.warn_deprecated('3.10', message=f'{no_switch} From Matplotlib 3.12 this operation will raise an exception.') return raise ValueError(no_switch) figure = property(functools.partial(get_figure, root=True), set_figure, doc='The root `Figure`. To get the parent of a `SubFigure`, use the `get_figure` method.') def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) inside = self.bbox.contains(mouseevent.x, mouseevent.y) return (inside, {}) def get_window_extent(self, renderer=None): return self.bbox def _suplabels(self, t, info, **kwargs): x = kwargs.pop('x', None) y = kwargs.pop('y', None) if info['name'] in ['_supxlabel', '_suptitle']: autopos = y is None elif info['name'] == '_supylabel': autopos = x is None if x is None: x = info['x0'] if y is None: y = info['y0'] kwargs = cbook.normalize_kwargs(kwargs, Text) kwargs.setdefault('horizontalalignment', info['ha']) kwargs.setdefault('verticalalignment', info['va']) kwargs.setdefault('rotation', info['rotation']) if 'fontproperties' not in kwargs: kwargs.setdefault('fontsize', mpl.rcParams[info['size']]) kwargs.setdefault('fontweight', mpl.rcParams[info['weight']]) suplab = getattr(self, info['name']) if suplab is not None: suplab.set_text(t) suplab.set_position((x, y)) suplab.set(**kwargs) else: suplab = self.text(x, y, t, **kwargs) setattr(self, info['name'], suplab) suplab._autopos = autopos self.stale = True return suplab @_docstring.Substitution(x0=0.5, y0=0.98, name='suptitle', ha='center', va='top', rc='title') @_docstring.copy(_suplabels) def suptitle(self, t, **kwargs): info = {'name': '_suptitle', 'x0': 0.5, 'y0': 0.98, 'ha': 'center', 'va': 'top', 'rotation': 0, 'size': 'figure.titlesize', 'weight': 'figure.titleweight'} return self._suplabels(t, info, **kwargs) def get_suptitle(self): text_obj = self._suptitle return '' if text_obj is None else text_obj.get_text() @_docstring.Substitution(x0=0.5, y0=0.01, name='supxlabel', ha='center', va='bottom', rc='label') @_docstring.copy(_suplabels) def supxlabel(self, t, **kwargs): info = {'name': '_supxlabel', 'x0': 0.5, 'y0': 0.01, 'ha': 'center', 'va': 'bottom', 'rotation': 0, 'size': 'figure.labelsize', 'weight': 'figure.labelweight'} return self._suplabels(t, info, **kwargs) def get_supxlabel(self): text_obj = self._supxlabel return '' if text_obj is None else text_obj.get_text() @_docstring.Substitution(x0=0.02, y0=0.5, name='supylabel', ha='left', va='center', rc='label') @_docstring.copy(_suplabels) def supylabel(self, t, **kwargs): info = {'name': '_supylabel', 'x0': 0.02, 'y0': 0.5, 'ha': 'left', 'va': 'center', 'rotation': 'vertical', 'rotation_mode': 'anchor', 'size': 'figure.labelsize', 'weight': 'figure.labelweight'} return self._suplabels(t, info, **kwargs) def get_supylabel(self): text_obj = self._supylabel return '' if text_obj is None else text_obj.get_text() def get_edgecolor(self): return self.patch.get_edgecolor() def get_facecolor(self): return self.patch.get_facecolor() def get_frameon(self): return self.patch.get_visible() def set_linewidth(self, linewidth): self.patch.set_linewidth(linewidth) def get_linewidth(self): return self.patch.get_linewidth() def set_edgecolor(self, color): self.patch.set_edgecolor(color) def set_facecolor(self, color): self.patch.set_facecolor(color) def set_frameon(self, b): self.patch.set_visible(b) self.stale = True frameon = property(get_frameon, set_frameon) def add_artist(self, artist, clip=False): artist.set_figure(self) self.artists.append(artist) artist._remove_method = self.artists.remove if not artist.is_transform_set(): artist.set_transform(self.transSubfigure) if clip and artist.get_clip_path() is None: artist.set_clip_path(self.patch) self.stale = True return artist @_docstring.dedent_interpd def add_axes(self, *args, **kwargs): if not len(args) and 'rect' not in kwargs: raise TypeError("add_axes() missing 1 required positional argument: 'rect'") elif 'rect' in kwargs: if len(args): raise TypeError("add_axes() got multiple values for argument 'rect'") args = (kwargs.pop('rect'),) if isinstance(args[0], Axes): (a, *extra_args) = args key = a._projection_init if a.get_figure(root=False) is not self: raise ValueError('The Axes must have been created in the present figure') else: (rect, *extra_args) = args if not np.isfinite(rect).all(): raise ValueError(f'all entries in rect must be finite not {rect}') (projection_class, pkw) = self._process_projection_requirements(**kwargs) a = projection_class(self, rect, **pkw) key = (projection_class, pkw) if extra_args: _api.warn_deprecated('3.8', name='Passing more than one positional argument to Figure.add_axes', addendum='Any additional positional arguments are currently ignored.') return self._add_axes_internal(a, key) @_docstring.dedent_interpd def add_subplot(self, *args, **kwargs): if 'figure' in kwargs: raise _api.kwarg_error('add_subplot', 'figure') if len(args) == 1 and isinstance(args[0], mpl.axes._base._AxesBase) and args[0].get_subplotspec(): ax = args[0] key = ax._projection_init if ax.get_figure(root=False) is not self: raise ValueError('The Axes must have been created in the present figure') else: if not args: args = (1, 1, 1) if len(args) == 1 and isinstance(args[0], Integral) and (100 <= args[0] <= 999): args = tuple(map(int, str(args[0]))) (projection_class, pkw) = self._process_projection_requirements(**kwargs) ax = projection_class(self, *args, **pkw) key = (projection_class, pkw) return self._add_axes_internal(ax, key) def _add_axes_internal(self, ax, key): self._axstack.add(ax) if ax not in self._localaxes: self._localaxes.append(ax) self.sca(ax) ax._remove_method = self.delaxes ax._projection_init = key self.stale = True ax.stale_callback = _stale_figure_callback return ax def subplots(self, nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None): gridspec_kw = dict(gridspec_kw or {}) if height_ratios is not None: if 'height_ratios' in gridspec_kw: raise ValueError("'height_ratios' must not be defined both as parameter and as key in 'gridspec_kw'") gridspec_kw['height_ratios'] = height_ratios if width_ratios is not None: if 'width_ratios' in gridspec_kw: raise ValueError("'width_ratios' must not be defined both as parameter and as key in 'gridspec_kw'") gridspec_kw['width_ratios'] = width_ratios gs = self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw) axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze, subplot_kw=subplot_kw) return axs def delaxes(self, ax): self._remove_axes(ax, owners=[self._axstack, self._localaxes]) def _remove_axes(self, ax, owners): for owner in owners: owner.remove(ax) self._axobservers.process('_axes_change_event', self) self.stale = True self._root_figure.canvas.release_mouse(ax) for name in ax._axis_names: grouper = ax._shared_axes[name] siblings = [other for other in grouper.get_siblings(ax) if other is not ax] if not siblings: continue grouper.remove(ax) remaining_axis = siblings[0]._axis_map[name] remaining_axis.get_major_formatter().set_axis(remaining_axis) remaining_axis.get_major_locator().set_axis(remaining_axis) remaining_axis.get_minor_formatter().set_axis(remaining_axis) remaining_axis.get_minor_locator().set_axis(remaining_axis) ax._twinned_axes.remove(ax) def clear(self, keep_observers=False): self.suppressComposite = None for subfig in self.subfigs: subfig.clear(keep_observers=keep_observers) self.subfigs = [] for ax in tuple(self.axes): ax.clear() self.delaxes(ax) self.artists = [] self.lines = [] self.patches = [] self.texts = [] self.images = [] self.legends = [] if not keep_observers: self._axobservers = cbook.CallbackRegistry() self._suptitle = None self._supxlabel = None self._supylabel = None self.stale = True def clf(self, keep_observers=False): return self.clear(keep_observers=keep_observers) @_docstring.dedent_interpd def legend(self, *args, **kwargs): (handles, labels, kwargs) = mlegend._parse_legend_args(self.axes, *args, **kwargs) kwargs.setdefault('bbox_transform', self.transSubfigure) l = mlegend.Legend(self, handles, labels, **kwargs) self.legends.append(l) l._remove_method = self.legends.remove self.stale = True return l @_docstring.dedent_interpd def text(self, x, y, s, fontdict=None, **kwargs): effective_kwargs = {'transform': self.transSubfigure, **(fontdict if fontdict is not None else {}), **kwargs} text = Text(x=x, y=y, text=s, **effective_kwargs) text.set_figure(self) text.stale_callback = _stale_figure_callback self.texts.append(text) text._remove_method = self.texts.remove self.stale = True return text @_docstring.dedent_interpd def colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kwargs): if ax is None: ax = getattr(mappable, 'axes', None) if cax is None: if ax is None: raise ValueError('Unable to determine Axes to steal space for Colorbar. Either provide the *cax* argument to use as the Axes for the Colorbar, provide the *ax* argument to steal space from it, or add *mappable* to an Axes.') fig = ([*ax.flat] if isinstance(ax, np.ndarray) else [*ax] if np.iterable(ax) else [ax])[0].get_figure(root=False) current_ax = fig.gca() if fig.get_layout_engine() is not None and (not fig.get_layout_engine().colorbar_gridspec): use_gridspec = False if use_gridspec and isinstance(ax, mpl.axes._base._AxesBase) and ax.get_subplotspec(): (cax, kwargs) = cbar.make_axes_gridspec(ax, **kwargs) else: (cax, kwargs) = cbar.make_axes(ax, **kwargs) fig.sca(current_ax) cax.grid(visible=False, which='both', axis='both') if hasattr(mappable, 'get_figure') and (mappable_host_fig := mappable.get_figure(root=True)) is not None: if mappable_host_fig is not self._root_figure: _api.warn_external(f'Adding colorbar to a different Figure {repr(mappable_host_fig)} than {repr(self._root_figure)} which fig.colorbar is called on.') NON_COLORBAR_KEYS = ['fraction', 'pad', 'shrink', 'aspect', 'anchor', 'panchor'] cb = cbar.Colorbar(cax, mappable, **{k: v for (k, v) in kwargs.items() if k not in NON_COLORBAR_KEYS}) cax.get_figure(root=False).stale = True return cb def subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): if self.get_layout_engine() is not None and (not self.get_layout_engine().adjust_compatible): _api.warn_external('This figure was using a layout engine that is incompatible with subplots_adjust and/or tight_layout; not calling subplots_adjust.') return self.subplotpars.update(left, bottom, right, top, wspace, hspace) for ax in self.axes: if ax.get_subplotspec() is not None: ax._set_position(ax.get_subplotspec().get_position(self)) self.stale = True def align_xlabels(self, axs=None): if axs is None: axs = self.axes axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None] for ax in axs: _log.debug(' Working on: %s', ax.get_xlabel()) rowspan = ax.get_subplotspec().rowspan pos = ax.xaxis.get_label_position() for axc in axs: if axc.xaxis.get_label_position() == pos: rowspanc = axc.get_subplotspec().rowspan if pos == 'top' and rowspan.start == rowspanc.start or (pos == 'bottom' and rowspan.stop == rowspanc.stop): self._align_label_groups['x'].join(ax, axc) def align_ylabels(self, axs=None): if axs is None: axs = self.axes axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None] for ax in axs: _log.debug(' Working on: %s', ax.get_ylabel()) colspan = ax.get_subplotspec().colspan pos = ax.yaxis.get_label_position() for axc in axs: if axc.yaxis.get_label_position() == pos: colspanc = axc.get_subplotspec().colspan if pos == 'left' and colspan.start == colspanc.start or (pos == 'right' and colspan.stop == colspanc.stop): self._align_label_groups['y'].join(ax, axc) def align_titles(self, axs=None): if axs is None: axs = self.axes axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None] for ax in axs: _log.debug(' Working on: %s', ax.get_title()) rowspan = ax.get_subplotspec().rowspan for axc in axs: rowspanc = axc.get_subplotspec().rowspan if rowspan.start == rowspanc.start: self._align_label_groups['title'].join(ax, axc) def align_labels(self, axs=None): self.align_xlabels(axs=axs) self.align_ylabels(axs=axs) def add_gridspec(self, nrows=1, ncols=1, **kwargs): _ = kwargs.pop('figure', None) gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs) return gs def subfigures(self, nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs): gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, wspace=wspace, hspace=hspace, width_ratios=width_ratios, height_ratios=height_ratios, left=0, right=1, bottom=0, top=1) sfarr = np.empty((nrows, ncols), dtype=object) for i in range(nrows): for j in range(ncols): sfarr[i, j] = self.add_subfigure(gs[i, j], **kwargs) if self.get_layout_engine() is None and (wspace is not None or hspace is not None): (bottoms, tops, lefts, rights) = gs.get_grid_positions(self) for (sfrow, bottom, top) in zip(sfarr, bottoms, tops): for (sf, left, right) in zip(sfrow, lefts, rights): bbox = Bbox.from_extents(left, bottom, right, top) sf._redo_transform_rel_fig(bbox=bbox) if squeeze: return sfarr.item() if sfarr.size == 1 else sfarr.squeeze() else: return sfarr def add_subfigure(self, subplotspec, **kwargs): sf = SubFigure(self, subplotspec, **kwargs) self.subfigs += [sf] sf._remove_method = self.subfigs.remove sf.stale_callback = _stale_figure_callback self.stale = True return sf def sca(self, a): self._axstack.bubble(a) self._axobservers.process('_axes_change_event', self) return a def gca(self): ax = self._axstack.current() return ax if ax is not None else self.add_subplot() def _gci(self): ax = self._axstack.current() if ax is None: return None im = ax._gci() if im is not None: return im for ax in reversed(self.axes): im = ax._gci() if im is not None: return im return None def _process_projection_requirements(self, *, axes_class=None, polar=False, projection=None, **kwargs): if axes_class is not None: if polar or projection is not None: raise ValueError("Cannot combine 'axes_class' and 'projection' or 'polar'") projection_class = axes_class else: if polar: if projection is not None and projection != 'polar': raise ValueError(f'polar={polar}, yet projection={projection!r}. Only one of these arguments should be supplied.') projection = 'polar' if isinstance(projection, str) or projection is None: projection_class = projections.get_projection_class(projection) elif hasattr(projection, '_as_mpl_axes'): (projection_class, extra_kwargs) = projection._as_mpl_axes() kwargs.update(**extra_kwargs) else: raise TypeError(f'projection must be a string, None or implement a _as_mpl_axes method, not {projection!r}') return (projection_class, kwargs) def get_default_bbox_extra_artists(self): bbox_artists = [artist for artist in self.get_children() if artist.get_visible() and artist.get_in_layout()] for ax in self.axes: if ax.get_visible(): bbox_artists.extend(ax.get_default_bbox_extra_artists()) return bbox_artists def get_tightbbox(self, renderer=None, *, bbox_extra_artists=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() bb = [] if bbox_extra_artists is None: artists = [artist for artist in self.get_children() if artist not in self.axes and artist.get_visible() and artist.get_in_layout()] else: artists = bbox_extra_artists for a in artists: bbox = a.get_tightbbox(renderer) if bbox is not None: bb.append(bbox) for ax in self.axes: if ax.get_visible(): try: bbox = ax.get_tightbbox(renderer, bbox_extra_artists=bbox_extra_artists) except TypeError: bbox = ax.get_tightbbox(renderer) bb.append(bbox) bb = [b for b in bb if np.isfinite(b.width) and np.isfinite(b.height) and (b.width != 0 or b.height != 0)] isfigure = hasattr(self, 'bbox_inches') if len(bb) == 0: if isfigure: return self.bbox_inches else: bb = [self.bbox] _bbox = Bbox.union(bb) if isfigure: _bbox = TransformedBbox(_bbox, self.dpi_scale_trans.inverted()) return _bbox @staticmethod def _norm_per_subplot_kw(per_subplot_kw): expanded = {} for (k, v) in per_subplot_kw.items(): if isinstance(k, tuple): for sub_key in k: if sub_key in expanded: raise ValueError(f'The key {sub_key!r} appears multiple times.') expanded[sub_key] = v else: if k in expanded: raise ValueError(f'The key {k!r} appears multiple times.') expanded[k] = v return expanded @staticmethod def _normalize_grid_string(layout): if '\n' not in layout: return [list(ln) for ln in layout.split(';')] else: layout = inspect.cleandoc(layout) return [list(ln) for ln in layout.strip('\n').split('\n')] def subplot_mosaic(self, mosaic, *, sharex=False, sharey=False, width_ratios=None, height_ratios=None, empty_sentinel='.', subplot_kw=None, per_subplot_kw=None, gridspec_kw=None): subplot_kw = subplot_kw or {} gridspec_kw = dict(gridspec_kw or {}) per_subplot_kw = per_subplot_kw or {} if height_ratios is not None: if 'height_ratios' in gridspec_kw: raise ValueError("'height_ratios' must not be defined both as parameter and as key in 'gridspec_kw'") gridspec_kw['height_ratios'] = height_ratios if width_ratios is not None: if 'width_ratios' in gridspec_kw: raise ValueError("'width_ratios' must not be defined both as parameter and as key in 'gridspec_kw'") gridspec_kw['width_ratios'] = width_ratios if isinstance(mosaic, str): mosaic = self._normalize_grid_string(mosaic) per_subplot_kw = {tuple(k): v for (k, v) in per_subplot_kw.items()} per_subplot_kw = self._norm_per_subplot_kw(per_subplot_kw) _api.check_isinstance(bool, sharex=sharex, sharey=sharey) def _make_array(inp): (r0, *rest) = inp if isinstance(r0, str): raise ValueError('List mosaic specification must be 2D') for (j, r) in enumerate(rest, start=1): if isinstance(r, str): raise ValueError('List mosaic specification must be 2D') if len(r0) != len(r): raise ValueError(f'All of the rows must be the same length, however the first row ({r0!r}) has length {len(r0)} and row {j} ({r!r}) has length {len(r)}.') out = np.zeros((len(inp), len(r0)), dtype=object) for (j, r) in enumerate(inp): for (k, v) in enumerate(r): out[j, k] = v return out def _identify_keys_and_nested(mosaic): unique_ids = cbook._OrderedSet() nested = {} for (j, row) in enumerate(mosaic): for (k, v) in enumerate(row): if v == empty_sentinel: continue elif not cbook.is_scalar_or_string(v): nested[j, k] = _make_array(v) else: unique_ids.add(v) return (tuple(unique_ids), nested) def _do_layout(gs, mosaic, unique_ids, nested): output = dict() this_level = dict() for name in unique_ids: indx = np.argwhere(mosaic == name) (start_row, start_col) = np.min(indx, axis=0) (end_row, end_col) = np.max(indx, axis=0) + 1 slc = (slice(start_row, end_row), slice(start_col, end_col)) if (mosaic[slc] != name).any(): raise ValueError(f'While trying to layout\n{mosaic!r}\nwe found that the label {name!r} specifies a non-rectangular or non-contiguous area.') this_level[start_row, start_col] = (name, slc, 'axes') for ((j, k), nested_mosaic) in nested.items(): this_level[j, k] = (None, nested_mosaic, 'nested') for key in sorted(this_level): (name, arg, method) = this_level[key] if method == 'axes': slc = arg if name in output: raise ValueError(f'There are duplicate keys {name} in the layout\n{mosaic!r}') ax = self.add_subplot(gs[slc], **{'label': str(name), **subplot_kw, **per_subplot_kw.get(name, {})}) output[name] = ax elif method == 'nested': nested_mosaic = arg (j, k) = key (rows, cols) = nested_mosaic.shape nested_output = _do_layout(gs[j, k].subgridspec(rows, cols), nested_mosaic, *_identify_keys_and_nested(nested_mosaic)) overlap = set(output) & set(nested_output) if overlap: raise ValueError(f'There are duplicate keys {overlap} between the outer layout\n{mosaic!r}\nand the nested layout\n{nested_mosaic}') output.update(nested_output) else: raise RuntimeError('This should never happen') return output mosaic = _make_array(mosaic) (rows, cols) = mosaic.shape gs = self.add_gridspec(rows, cols, **gridspec_kw) ret = _do_layout(gs, mosaic, *_identify_keys_and_nested(mosaic)) ax0 = next(iter(ret.values())) for ax in ret.values(): if sharex: ax.sharex(ax0) ax._label_outer_xaxis(skip_non_rectangular_axes=True) if sharey: ax.sharey(ax0) ax._label_outer_yaxis(skip_non_rectangular_axes=True) if (extra := (set(per_subplot_kw) - set(ret))): raise ValueError(f'The keys {extra} are in *per_subplot_kw* but not in the mosaic.') return ret def _set_artist_props(self, a): if a != self: a.set_figure(self) a.stale_callback = _stale_figure_callback a.set_transform(self.transSubfigure) @_docstring.interpd class SubFigure(FigureBase): def __init__(self, parent, subplotspec, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, **kwargs): super().__init__(**kwargs) if facecolor is None: facecolor = 'none' if edgecolor is None: edgecolor = mpl.rcParams['figure.edgecolor'] if frameon is None: frameon = mpl.rcParams['figure.frameon'] self._subplotspec = subplotspec self._parent = parent self._root_figure = parent._root_figure self._axstack = parent._axstack self.subplotpars = parent.subplotpars self.dpi_scale_trans = parent.dpi_scale_trans self._axobservers = parent._axobservers self.transFigure = parent.transFigure self.bbox_relative = Bbox.null() self._redo_transform_rel_fig() self.figbbox = self._parent.figbbox self.bbox = TransformedBbox(self.bbox_relative, self._parent.transSubfigure) self.transSubfigure = BboxTransformTo(self.bbox) self.patch = Rectangle(xy=(0, 0), width=1, height=1, visible=frameon, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, in_layout=False, transform=self.transSubfigure) self._set_artist_props(self.patch) self.patch.set_antialiased(False) @property def canvas(self): return self._parent.canvas @property def dpi(self): return self._parent.dpi @dpi.setter def dpi(self, value): self._parent.dpi = value def get_dpi(self): return self._parent.dpi def set_dpi(self, val): self._parent.dpi = val self.stale = True def _get_renderer(self): return self._parent._get_renderer() def _redo_transform_rel_fig(self, bbox=None): if bbox is not None: self.bbox_relative.p0 = bbox.p0 self.bbox_relative.p1 = bbox.p1 return gs = self._subplotspec.get_gridspec() wr = np.asarray(gs.get_width_ratios()) hr = np.asarray(gs.get_height_ratios()) dx = wr[self._subplotspec.colspan].sum() / wr.sum() dy = hr[self._subplotspec.rowspan].sum() / hr.sum() x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum() y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum() self.bbox_relative.p0 = (x0, y0) self.bbox_relative.p1 = (x0 + dx, y0 + dy) def get_constrained_layout(self): return self._parent.get_constrained_layout() def get_constrained_layout_pads(self, relative=False): return self._parent.get_constrained_layout_pads(relative=relative) def get_layout_engine(self): return self._parent.get_layout_engine() @property def axes(self): return self._localaxes[:] get_axes = axes.fget def draw(self, renderer): if not self.get_visible(): return artists = self._get_draw_artists(renderer) try: renderer.open_group('subfigure', gid=self.get_gid()) self.patch.draw(renderer) mimage._draw_list_compositing_images(renderer, self, artists, self.get_figure(root=True).suppressComposite) renderer.close_group('subfigure') finally: self.stale = False @_docstring.interpd class Figure(FigureBase): _render_lock = threading.RLock() def __str__(self): return 'Figure(%gx%g)' % tuple(self.bbox.size) def __repr__(self): return '<{clsname} size {h:g}x{w:g} with {naxes} Axes>'.format(clsname=self.__class__.__name__, h=self.bbox.size[0], w=self.bbox.size[1], naxes=len(self.axes)) def __init__(self, figsize=None, dpi=None, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, layout=None, **kwargs): super().__init__(**kwargs) self._root_figure = self self._layout_engine = None if layout is not None: if tight_layout is not None: _api.warn_external("The Figure parameters 'layout' and 'tight_layout' cannot be used together. Please use 'layout' only.") if constrained_layout is not None: _api.warn_external("The Figure parameters 'layout' and 'constrained_layout' cannot be used together. Please use 'layout' only.") self.set_layout_engine(layout=layout) elif tight_layout is not None: if constrained_layout is not None: _api.warn_external("The Figure parameters 'tight_layout' and 'constrained_layout' cannot be used together. Please use 'layout' parameter") self.set_layout_engine(layout='tight') if isinstance(tight_layout, dict): self.get_layout_engine().set(**tight_layout) elif constrained_layout is not None: if isinstance(constrained_layout, dict): self.set_layout_engine(layout='constrained') self.get_layout_engine().set(**constrained_layout) elif constrained_layout: self.set_layout_engine(layout='constrained') else: self.set_layout_engine(layout=layout) self._canvas_callbacks = cbook.CallbackRegistry(signals=FigureCanvasBase.events) connect = self._canvas_callbacks._connect_picklable self._mouse_key_ids = [connect('key_press_event', backend_bases._key_handler), connect('key_release_event', backend_bases._key_handler), connect('key_release_event', backend_bases._key_handler), connect('button_press_event', backend_bases._mouse_handler), connect('button_release_event', backend_bases._mouse_handler), connect('scroll_event', backend_bases._mouse_handler), connect('motion_notify_event', backend_bases._mouse_handler)] self._button_pick_id = connect('button_press_event', self.pick) self._scroll_pick_id = connect('scroll_event', self.pick) if figsize is None: figsize = mpl.rcParams['figure.figsize'] if dpi is None: dpi = mpl.rcParams['figure.dpi'] if facecolor is None: facecolor = mpl.rcParams['figure.facecolor'] if edgecolor is None: edgecolor = mpl.rcParams['figure.edgecolor'] if frameon is None: frameon = mpl.rcParams['figure.frameon'] if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any(): raise ValueError(f'figure size must be positive finite not {figsize}') self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.dpi_scale_trans = Affine2D().scale(dpi) self._dpi = dpi self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) self.figbbox = self.bbox self.transFigure = BboxTransformTo(self.bbox) self.transSubfigure = self.transFigure self.patch = Rectangle(xy=(0, 0), width=1, height=1, visible=frameon, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, in_layout=False) self._set_artist_props(self.patch) self.patch.set_antialiased(False) FigureCanvasBase(self) if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = _AxesStack() self.clear() def pick(self, mouseevent): if not self.canvas.widgetlock.locked(): super().pick(mouseevent) def _check_layout_engines_compat(self, old, new): if old is None or new is None: return True if old.colorbar_gridspec == new.colorbar_gridspec: return True for ax in self.axes: if hasattr(ax, '_colorbar'): return False return True def set_layout_engine(self, layout=None, **kwargs): if layout is None: if mpl.rcParams['figure.autolayout']: layout = 'tight' elif mpl.rcParams['figure.constrained_layout.use']: layout = 'constrained' else: self._layout_engine = None return if layout == 'tight': new_layout_engine = TightLayoutEngine(**kwargs) elif layout == 'constrained': new_layout_engine = ConstrainedLayoutEngine(**kwargs) elif layout == 'compressed': new_layout_engine = ConstrainedLayoutEngine(compress=True, **kwargs) elif layout == 'none': if self._layout_engine is not None: new_layout_engine = PlaceHolderLayoutEngine(self._layout_engine.adjust_compatible, self._layout_engine.colorbar_gridspec) else: new_layout_engine = None elif isinstance(layout, LayoutEngine): new_layout_engine = layout else: raise ValueError(f"Invalid value for 'layout': {layout!r}") if self._check_layout_engines_compat(self._layout_engine, new_layout_engine): self._layout_engine = new_layout_engine else: raise RuntimeError('Colorbar layout of new layout engine not compatible with old engine, and a colorbar has been created. Engine not changed.') def get_layout_engine(self): return self._layout_engine def _repr_html_(self): if 'WebAgg' in type(self.canvas).__name__: from matplotlib.backends import backend_webagg return backend_webagg.ipython_inline_display(self) def show(self, warn=True): if self.canvas.manager is None: raise AttributeError('Figure.show works only for figures managed by pyplot, normally created by pyplot.figure()') try: self.canvas.manager.show() except NonGuiException as exc: if warn: _api.warn_external(str(exc)) @property def axes(self): return self._axstack.as_list() get_axes = axes.fget def _get_renderer(self): if hasattr(self.canvas, 'get_renderer'): return self.canvas.get_renderer() else: return _get_renderer(self) def _get_dpi(self): return self._dpi def _set_dpi(self, dpi, forward=True): if dpi == self._dpi: return self._dpi = dpi self.dpi_scale_trans.clear().scale(dpi) (w, h) = self.get_size_inches() self.set_size_inches(w, h, forward=forward) dpi = property(_get_dpi, _set_dpi, doc='The resolution in dots per inch.') def get_tight_layout(self): return isinstance(self.get_layout_engine(), TightLayoutEngine) @_api.deprecated('3.6', alternative='set_layout_engine', pending=True) def set_tight_layout(self, tight): if tight is None: tight = mpl.rcParams['figure.autolayout'] _tight = 'tight' if bool(tight) else 'none' _tight_parameters = tight if isinstance(tight, dict) else {} self.set_layout_engine(_tight, **_tight_parameters) self.stale = True def get_constrained_layout(self): return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine) @_api.deprecated('3.6', alternative="set_layout_engine('constrained')", pending=True) def set_constrained_layout(self, constrained): if constrained is None: constrained = mpl.rcParams['figure.constrained_layout.use'] _constrained = 'constrained' if bool(constrained) else 'none' _parameters = constrained if isinstance(constrained, dict) else {} self.set_layout_engine(_constrained, **_parameters) self.stale = True @_api.deprecated('3.6', alternative='figure.get_layout_engine().set()', pending=True) def set_constrained_layout_pads(self, **kwargs): if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.get_layout_engine().set(**kwargs) @_api.deprecated('3.6', alternative='fig.get_layout_engine().get()', pending=True) def get_constrained_layout_pads(self, relative=False): if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): return (None, None, None, None) info = self.get_layout_engine().get() w_pad = info['w_pad'] h_pad = info['h_pad'] wspace = info['wspace'] hspace = info['hspace'] if relative and (w_pad is not None or h_pad is not None): renderer = self._get_renderer() dpi = renderer.dpi w_pad = w_pad * dpi / renderer.width h_pad = h_pad * dpi / renderer.height return (w_pad, h_pad, wspace, hspace) def set_canvas(self, canvas): self.canvas = canvas @_docstring.interpd def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs): if resize: dpi = self.get_dpi() figsize = [x / dpi for x in (X.shape[1], X.shape[0])] self.set_size_inches(figsize, forward=True) im = mimage.FigureImage(self, cmap=cmap, norm=norm, offsetx=xo, offsety=yo, origin=origin, **kwargs) im.stale_callback = _stale_figure_callback im.set_array(X) im.set_alpha(alpha) if norm is None: im.set_clim(vmin, vmax) self.images.append(im) im._remove_method = self.images.remove self.stale = True return im def set_size_inches(self, w, h=None, forward=True): if h is None: (w, h) = w size = np.array([w, h]) if not np.isfinite(size).all() or (size < 0).any(): raise ValueError(f'figure size must be positive finite not {size}') self.bbox_inches.p1 = size if forward: manager = self.canvas.manager if manager is not None: manager.resize(*(size * self.dpi).astype(int)) self.stale = True def get_size_inches(self): return np.array(self.bbox_inches.p1) def get_figwidth(self): return self.bbox_inches.width def get_figheight(self): return self.bbox_inches.height def get_dpi(self): return self.dpi def set_dpi(self, val): self.dpi = val self.stale = True def set_figwidth(self, val, forward=True): self.set_size_inches(val, self.get_figheight(), forward=forward) def set_figheight(self, val, forward=True): self.set_size_inches(self.get_figwidth(), val, forward=forward) def clear(self, keep_observers=False): super().clear(keep_observers=keep_observers) toolbar = self.canvas.toolbar if toolbar is not None: toolbar.update() @_finalize_rasterization @allow_rasterization def draw(self, renderer): if not self.get_visible(): return with self._render_lock: artists = self._get_draw_artists(renderer) try: renderer.open_group('figure', gid=self.get_gid()) if self.axes and self.get_layout_engine() is not None: try: self.get_layout_engine().execute(self) except ValueError: pass self.patch.draw(renderer) mimage._draw_list_compositing_images(renderer, self, artists, self.suppressComposite) renderer.close_group('figure') finally: self.stale = False DrawEvent('draw_event', self.canvas, renderer)._process() def draw_without_rendering(self): renderer = _get_renderer(self) with renderer._draw_disabled(): self.draw(renderer) def draw_artist(self, a): a.draw(self.canvas.get_renderer()) def __getstate__(self): state = super().__getstate__() state.pop('canvas') state['_dpi'] = state.get('_original_dpi', state['_dpi']) state['__mpl_version__'] = mpl.__version__ from matplotlib import _pylab_helpers if self.canvas.manager in _pylab_helpers.Gcf.figs.values(): state['_restore_to_pylab'] = True return state def __setstate__(self, state): version = state.pop('__mpl_version__') restore_to_pylab = state.pop('_restore_to_pylab', False) if version != mpl.__version__: _api.warn_external(f'This figure was saved with matplotlib version {version} and loaded with {mpl.__version__} so may not function correctly.') self.__dict__ = state FigureCanvasBase(self) if restore_to_pylab: import matplotlib.pyplot as plt import matplotlib._pylab_helpers as pylab_helpers allnums = plt.get_fignums() num = max(allnums) + 1 if allnums else 1 backend = plt._get_backend_mod() mgr = backend.new_figure_manager_given_figure(num, self) pylab_helpers.Gcf._set_new_active_manager(mgr) plt.draw_if_interactive() self.stale = True def add_axobserver(self, func): self._axobservers.connect('_axes_change_event', lambda arg: func(arg)) def savefig(self, fname, *, transparent=None, **kwargs): kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi']) if transparent is None: transparent = mpl.rcParams['savefig.transparent'] with ExitStack() as stack: if transparent: def _recursively_make_subfig_transparent(exit_stack, subfig): exit_stack.enter_context(subfig.patch._cm_set(facecolor='none', edgecolor='none')) for ax in subfig.axes: exit_stack.enter_context(ax.patch._cm_set(facecolor='none', edgecolor='none')) for sub_subfig in subfig.subfigs: _recursively_make_subfig_transparent(exit_stack, sub_subfig) def _recursively_make_axes_transparent(exit_stack, ax): exit_stack.enter_context(ax.patch._cm_set(facecolor='none', edgecolor='none')) for child_ax in ax.child_axes: exit_stack.enter_context(child_ax.patch._cm_set(facecolor='none', edgecolor='none')) for child_childax in ax.child_axes: _recursively_make_axes_transparent(exit_stack, child_childax) kwargs.setdefault('facecolor', 'none') kwargs.setdefault('edgecolor', 'none') for subfig in self.subfigs: _recursively_make_subfig_transparent(stack, subfig) for ax in self.axes: _recursively_make_axes_transparent(stack, ax) self.canvas.print_figure(fname, **kwargs) def ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE): clicks = [] marks = [] def handler(event): is_button = event.name == 'button_press_event' is_key = event.name == 'key_press_event' if is_button and event.button == mouse_stop or (is_key and event.key in ['escape', 'enter']): self.canvas.stop_event_loop() elif is_button and event.button == mouse_pop or (is_key and event.key in ['backspace', 'delete']): if clicks: clicks.pop() if show_clicks: marks.pop().remove() self.canvas.draw() elif is_button and event.button == mouse_add or (is_key and event.key is not None): if event.inaxes: clicks.append((event.xdata, event.ydata)) _log.info('input %i: %f, %f', len(clicks), event.xdata, event.ydata) if show_clicks: line = mpl.lines.Line2D([event.xdata], [event.ydata], marker='+', color='r') event.inaxes.add_line(line) marks.append(line) self.canvas.draw() if len(clicks) == n and n > 0: self.canvas.stop_event_loop() _blocking_input.blocking_input_loop(self, ['button_press_event', 'key_press_event'], timeout, handler) for mark in marks: mark.remove() self.canvas.draw() return clicks def waitforbuttonpress(self, timeout=-1): event = None def handler(ev): nonlocal event event = ev self.canvas.stop_event_loop() _blocking_input.blocking_input_loop(self, ['button_press_event', 'key_press_event'], timeout, handler) return None if event is None else event.name == 'key_press_event' def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None): engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) try: previous_engine = self.get_layout_engine() self.set_layout_engine(engine) engine.execute(self) if previous_engine is not None and (not isinstance(previous_engine, (TightLayoutEngine, PlaceHolderLayoutEngine))): _api.warn_external('The figure layout has changed to tight') finally: self.set_layout_engine('none') def figaspect(arg): isarray = hasattr(arg, 'shape') and (not np.isscalar(arg)) figsize_min = np.array((4.0, 2.0)) figsize_max = np.array((16.0, 16.0)) if isarray: (nr, nc) = arg.shape[:2] arr_ratio = nr / nc else: arr_ratio = arg fig_height = mpl.rcParams['figure.figsize'][1] newsize = np.array((fig_height / arr_ratio, fig_height)) newsize /= min(1.0, *newsize / figsize_min) newsize /= max(1.0, *newsize / figsize_max) newsize = np.clip(newsize, figsize_min, figsize_max) return newsize # File: matplotlib-main/lib/matplotlib/font_manager.py """""" from __future__ import annotations from base64 import b64encode from collections import namedtuple import copy import dataclasses from functools import lru_cache from io import BytesIO import json import logging from numbers import Number import os from pathlib import Path import plistlib import re import subprocess import sys import threading import matplotlib as mpl from matplotlib import _api, _afm, cbook, ft2font from matplotlib._fontconfig_pattern import parse_fontconfig_pattern, generate_fontconfig_pattern from matplotlib.rcsetup import _validators _log = logging.getLogger(__name__) font_scalings = {'xx-small': 0.579, 'x-small': 0.694, 'small': 0.833, 'medium': 1.0, 'large': 1.2, 'x-large': 1.44, 'xx-large': 1.728, 'larger': 1.2, 'smaller': 0.833, None: 1.0} stretch_dict = {'ultra-condensed': 100, 'extra-condensed': 200, 'condensed': 300, 'semi-condensed': 400, 'normal': 500, 'semi-expanded': 600, 'semi-extended': 600, 'expanded': 700, 'extended': 700, 'extra-expanded': 800, 'extra-extended': 800, 'ultra-expanded': 900, 'ultra-extended': 900} weight_dict = {'ultralight': 100, 'light': 200, 'normal': 400, 'regular': 400, 'book': 400, 'medium': 500, 'roman': 500, 'semibold': 600, 'demibold': 600, 'demi': 600, 'bold': 700, 'heavy': 800, 'extra bold': 800, 'black': 900} _weight_regexes = [('thin', 100), ('extralight', 200), ('ultralight', 200), ('demilight', 350), ('semilight', 350), ('light', 300), ('book', 380), ('regular', 400), ('normal', 400), ('medium', 500), ('demibold', 600), ('demi', 600), ('semibold', 600), ('extrabold', 800), ('superbold', 800), ('ultrabold', 800), ('bold', 700), ('ultrablack', 1000), ('superblack', 1000), ('extrablack', 1000), ('\\bultra', 1000), ('black', 900), ('heavy', 900)] font_family_aliases = {'serif', 'sans-serif', 'sans serif', 'cursive', 'fantasy', 'monospace', 'sans'} _ExceptionProxy = namedtuple('_ExceptionProxy', ['klass', 'message']) try: _HOME = Path.home() except Exception: _HOME = Path(os.devnull) MSFolders = 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders' MSFontDirectories = ['SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts', 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts'] MSUserFontDirectories = [str(_HOME / 'AppData/Local/Microsoft/Windows/Fonts'), str(_HOME / 'AppData/Roaming/Microsoft/Windows/Fonts')] X11FontDirectories = ['/usr/X11R6/lib/X11/fonts/TTF/', '/usr/X11/lib/X11/fonts', '/usr/share/fonts/', '/usr/local/share/fonts/', '/usr/lib/openoffice/share/fonts/truetype/', str(Path(os.environ.get('XDG_DATA_HOME') or _HOME / '.local/share') / 'fonts'), str(_HOME / '.fonts')] OSXFontDirectories = ['/Library/Fonts/', '/Network/Library/Fonts/', '/System/Library/Fonts/', '/opt/local/share/fonts', str(_HOME / 'Library/Fonts')] def get_fontext_synonyms(fontext): return {'afm': ['afm'], 'otf': ['otf', 'ttc', 'ttf'], 'ttc': ['otf', 'ttc', 'ttf'], 'ttf': ['otf', 'ttc', 'ttf']}[fontext] def list_fonts(directory, extensions): extensions = ['.' + ext for ext in extensions] return [os.path.join(dirpath, filename) for (dirpath, _, filenames) in os.walk(directory) for filename in filenames if Path(filename).suffix.lower() in extensions] def win32FontDirectory(): import winreg try: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user: return winreg.QueryValueEx(user, 'Fonts')[0] except OSError: return os.path.join(os.environ['WINDIR'], 'Fonts') def _get_win32_installed_fonts(): import winreg items = set() for (domain, base_dirs) in [(winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), (winreg.HKEY_CURRENT_USER, MSUserFontDirectories)]: for base_dir in base_dirs: for reg_path in MSFontDirectories: try: with winreg.OpenKey(domain, reg_path) as local: for j in range(winreg.QueryInfoKey(local)[1]): (key, value, tp) = winreg.EnumValue(local, j) if not isinstance(value, str): continue try: path = Path(base_dir, value).resolve() except RuntimeError: continue items.add(path) except (OSError, MemoryError): continue return items @lru_cache def _get_fontconfig_fonts(): try: if b'--format' not in subprocess.check_output(['fc-list', '--help']): _log.warning('Matplotlib needs fontconfig>=2.7 to query system fonts.') return [] out = subprocess.check_output(['fc-list', '--format=%{file}\\n']) except (OSError, subprocess.CalledProcessError): return [] return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')] @lru_cache def _get_macos_fonts(): try: (d,) = plistlib.loads(subprocess.check_output(['system_profiler', '-xml', 'SPFontsDataType'])) except (OSError, subprocess.CalledProcessError, plistlib.InvalidFileException): return [] return [Path(entry['path']) for entry in d['_items']] def findSystemFonts(fontpaths=None, fontext='ttf'): fontfiles = set() fontexts = get_fontext_synonyms(fontext) if fontpaths is None: if sys.platform == 'win32': installed_fonts = _get_win32_installed_fonts() fontpaths = [] else: installed_fonts = _get_fontconfig_fonts() if sys.platform == 'darwin': installed_fonts += _get_macos_fonts() fontpaths = [*X11FontDirectories, *OSXFontDirectories] else: fontpaths = X11FontDirectories fontfiles.update((str(path) for path in installed_fonts if path.suffix.lower()[1:] in fontexts)) elif isinstance(fontpaths, str): fontpaths = [fontpaths] for path in fontpaths: fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts))) return [fname for fname in fontfiles if os.path.exists(fname)] @dataclasses.dataclass(frozen=True) class FontEntry: fname: str = '' name: str = '' style: str = 'normal' variant: str = 'normal' weight: str | int = 'normal' stretch: str = 'normal' size: str = 'medium' def _repr_html_(self) -> str: png_stream = self._repr_png_() png_b64 = b64encode(png_stream).decode() return f'' def _repr_png_(self) -> bytes: from matplotlib.figure import Figure fig = Figure() font_path = Path(self.fname) if self.fname != '' else None fig.text(0, 0, self.name, font=font_path) with BytesIO() as buf: fig.savefig(buf, bbox_inches='tight', transparent=True) return buf.getvalue() def ttfFontProperty(font): name = font.family_name sfnt = font.get_sfnt() mac_key = (1, 0, 0) ms_key = (3, 1, 1033) sfnt2 = sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower() sfnt4 = sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower() if sfnt4.find('oblique') >= 0: style = 'oblique' elif sfnt4.find('italic') >= 0: style = 'italic' elif sfnt2.find('regular') >= 0: style = 'normal' elif font.style_flags & ft2font.ITALIC: style = 'italic' else: style = 'normal' if name.lower() in ['capitals', 'small-caps']: variant = 'small-caps' else: variant = 'normal' wws_subfamily = 22 typographic_subfamily = 16 font_subfamily = 2 styles = [sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'), sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'), sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'), sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'), sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'), sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be')] styles = [*filter(None, styles)] or [font.style_name] def get_weight(): os2 = font.get_sfnt_table('OS/2') if os2 and os2['version'] != 65535: return os2['usWeightClass'] try: ps_font_info_weight = font.get_ps_font_info()['weight'].replace(' ', '') or '' except ValueError: pass else: for (regex, weight) in _weight_regexes: if re.fullmatch(regex, ps_font_info_weight, re.I): return weight for style in styles: style = style.replace(' ', '') for (regex, weight) in _weight_regexes: if re.search(regex, style, re.I): return weight if font.style_flags & ft2font.BOLD: return 700 return 500 weight = int(get_weight()) if any((word in sfnt4 for word in ['narrow', 'condensed', 'cond'])): stretch = 'condensed' elif 'demi cond' in sfnt4: stretch = 'semi-condensed' elif any((word in sfnt4 for word in ['wide', 'expanded', 'extended'])): stretch = 'expanded' else: stretch = 'normal' if not font.scalable: raise NotImplementedError('Non-scalable fonts are not supported') size = 'scalable' return FontEntry(font.fname, name, style, variant, weight, stretch, size) def afmFontProperty(fontpath, font): name = font.get_familyname() fontname = font.get_fontname().lower() if font.get_angle() != 0 or 'italic' in name.lower(): style = 'italic' elif 'oblique' in name.lower(): style = 'oblique' else: style = 'normal' if name.lower() in ['capitals', 'small-caps']: variant = 'small-caps' else: variant = 'normal' weight = font.get_weight().lower() if weight not in weight_dict: weight = 'normal' if 'demi cond' in fontname: stretch = 'semi-condensed' elif any((word in fontname for word in ['narrow', 'cond'])): stretch = 'condensed' elif any((word in fontname for word in ['wide', 'expanded', 'extended'])): stretch = 'expanded' else: stretch = 'normal' size = 'scalable' return FontEntry(fontpath, name, style, variant, weight, stretch, size) class FontProperties: def __init__(self, family=None, style=None, variant=None, weight=None, stretch=None, size=None, fname=None, math_fontfamily=None): self.set_family(family) self.set_style(style) self.set_variant(variant) self.set_weight(weight) self.set_stretch(stretch) self.set_file(fname) self.set_size(size) self.set_math_fontfamily(math_fontfamily) if isinstance(family, str) and style is None and (variant is None) and (weight is None) and (stretch is None) and (size is None) and (fname is None): self.set_fontconfig_pattern(family) @classmethod def _from_any(cls, arg): if arg is None: return cls() elif isinstance(arg, cls): return arg elif isinstance(arg, os.PathLike): return cls(fname=arg) elif isinstance(arg, str): return cls(arg) else: return cls(**arg) def __hash__(self): l = (tuple(self.get_family()), self.get_slant(), self.get_variant(), self.get_weight(), self.get_stretch(), self.get_size(), self.get_file(), self.get_math_fontfamily()) return hash(l) def __eq__(self, other): return hash(self) == hash(other) def __str__(self): return self.get_fontconfig_pattern() def get_family(self): return self._family def get_name(self): return get_font(findfont(self)).family_name def get_style(self): return self._slant def get_variant(self): return self._variant def get_weight(self): return self._weight def get_stretch(self): return self._stretch def get_size(self): return self._size def get_file(self): return self._file def get_fontconfig_pattern(self): return generate_fontconfig_pattern(self) def set_family(self, family): if family is None: family = mpl.rcParams['font.family'] if isinstance(family, str): family = [family] self._family = family def set_style(self, style): if style is None: style = mpl.rcParams['font.style'] _api.check_in_list(['normal', 'italic', 'oblique'], style=style) self._slant = style def set_variant(self, variant): if variant is None: variant = mpl.rcParams['font.variant'] _api.check_in_list(['normal', 'small-caps'], variant=variant) self._variant = variant def set_weight(self, weight): if weight is None: weight = mpl.rcParams['font.weight'] if weight in weight_dict: self._weight = weight return try: weight = int(weight) except ValueError: pass else: if 0 <= weight <= 1000: self._weight = weight return raise ValueError(f'weight={weight!r} is invalid') def set_stretch(self, stretch): if stretch is None: stretch = mpl.rcParams['font.stretch'] if stretch in stretch_dict: self._stretch = stretch return try: stretch = int(stretch) except ValueError: pass else: if 0 <= stretch <= 1000: self._stretch = stretch return raise ValueError(f'stretch={stretch!r} is invalid') def set_size(self, size): if size is None: size = mpl.rcParams['font.size'] try: size = float(size) except ValueError: try: scale = font_scalings[size] except KeyError as err: raise ValueError('Size is invalid. Valid font size are ' + ', '.join(map(str, font_scalings))) from err else: size = scale * FontManager.get_default_size() if size < 1.0: _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. Setting fontsize = 1 pt', size) size = 1.0 self._size = size def set_file(self, file): self._file = os.fspath(file) if file is not None else None def set_fontconfig_pattern(self, pattern): for (key, val) in parse_fontconfig_pattern(pattern).items(): if type(val) is list: getattr(self, 'set_' + key)(val[0]) else: getattr(self, 'set_' + key)(val) def get_math_fontfamily(self): return self._math_fontfamily def set_math_fontfamily(self, fontfamily): if fontfamily is None: fontfamily = mpl.rcParams['mathtext.fontset'] else: valid_fonts = _validators['mathtext.fontset'].valid.values() _api.check_in_list(valid_fonts, math_fontfamily=fontfamily) self._math_fontfamily = fontfamily def copy(self): return copy.copy(self) set_name = set_family get_slant = get_style set_slant = set_style get_size_in_points = get_size class _JSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, FontManager): return dict(o.__dict__, __class__='FontManager') elif isinstance(o, FontEntry): d = dict(o.__dict__, __class__='FontEntry') try: d['fname'] = str(Path(d['fname']).relative_to(mpl.get_data_path())) except ValueError: pass return d else: return super().default(o) def _json_decode(o): cls = o.pop('__class__', None) if cls is None: return o elif cls == 'FontManager': r = FontManager.__new__(FontManager) r.__dict__.update(o) return r elif cls == 'FontEntry': if not os.path.isabs(o['fname']): o['fname'] = os.path.join(mpl.get_data_path(), o['fname']) r = FontEntry(**o) return r else: raise ValueError("Don't know how to deserialize __class__=%s" % cls) def json_dump(data, filename): try: with cbook._lock_path(filename), open(filename, 'w') as fh: json.dump(data, fh, cls=_JSONEncoder, indent=2) except OSError as e: _log.warning('Could not save font_manager cache %s', e) def json_load(filename): with open(filename) as fh: return json.load(fh, object_hook=_json_decode) class FontManager: __version__ = 390 def __init__(self, size=None, weight='normal'): self._version = self.__version__ self.__default_weight = weight self.default_size = size paths = [cbook._get_data_path('fonts', subdir) for subdir in ['ttf', 'afm', 'pdfcorefonts']] _log.debug('font search path %s', paths) self.defaultFamily = {'ttf': 'DejaVu Sans', 'afm': 'Helvetica'} self.afmlist = [] self.ttflist = [] timer = threading.Timer(5, lambda : _log.warning('Matplotlib is building the font cache; this may take a moment.')) timer.start() try: for fontext in ['afm', 'ttf']: for path in [*findSystemFonts(paths, fontext=fontext), *findSystemFonts(fontext=fontext)]: try: self.addfont(path) except OSError as exc: _log.info('Failed to open font file %s: %s', path, exc) except Exception as exc: _log.info('Failed to extract font properties from %s: %s', path, exc) finally: timer.cancel() def addfont(self, path): path = os.fsdecode(path) if Path(path).suffix.lower() == '.afm': with open(path, 'rb') as fh: font = _afm.AFM(fh) prop = afmFontProperty(path, font) self.afmlist.append(prop) else: font = ft2font.FT2Font(path) prop = ttfFontProperty(font) self.ttflist.append(prop) self._findfont_cached.cache_clear() @property def defaultFont(self): return {ext: self.findfont(family, fontext=ext) for (ext, family) in self.defaultFamily.items()} def get_default_weight(self): return self.__default_weight @staticmethod def get_default_size(): return mpl.rcParams['font.size'] def set_default_weight(self, weight): self.__default_weight = weight @staticmethod def _expand_aliases(family): if family in ('sans', 'sans serif'): family = 'sans-serif' return mpl.rcParams['font.' + family] def score_family(self, families, family2): if not isinstance(families, (list, tuple)): families = [families] elif len(families) == 0: return 1.0 family2 = family2.lower() step = 1 / len(families) for (i, family1) in enumerate(families): family1 = family1.lower() if family1 in font_family_aliases: options = [*map(str.lower, self._expand_aliases(family1))] if family2 in options: idx = options.index(family2) return (i + idx / len(options)) * step elif family1 == family2: return i * step return 1.0 def score_style(self, style1, style2): if style1 == style2: return 0.0 elif style1 in ('italic', 'oblique') and style2 in ('italic', 'oblique'): return 0.1 return 1.0 def score_variant(self, variant1, variant2): if variant1 == variant2: return 0.0 else: return 1.0 def score_stretch(self, stretch1, stretch2): try: stretchval1 = int(stretch1) except ValueError: stretchval1 = stretch_dict.get(stretch1, 500) try: stretchval2 = int(stretch2) except ValueError: stretchval2 = stretch_dict.get(stretch2, 500) return abs(stretchval1 - stretchval2) / 1000.0 def score_weight(self, weight1, weight2): if cbook._str_equal(weight1, weight2): return 0.0 w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1] w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2] return 0.95 * (abs(w1 - w2) / 1000) + 0.05 def score_size(self, size1, size2): if size2 == 'scalable': return 0.0 try: sizeval1 = float(size1) except ValueError: sizeval1 = self.default_size * font_scalings[size1] try: sizeval2 = float(size2) except ValueError: return 1.0 return abs(sizeval1 - sizeval2) / 72 def findfont(self, prop, fontext='ttf', directory=None, fallback_to_default=True, rebuild_if_missing=True): rc_params = tuple((tuple(mpl.rcParams[key]) for key in ['font.serif', 'font.sans-serif', 'font.cursive', 'font.fantasy', 'font.monospace'])) ret = self._findfont_cached(prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params) if isinstance(ret, _ExceptionProxy): raise ret.klass(ret.message) return ret def get_font_names(self): return list({font.name for font in self.ttflist}) def _find_fonts_by_props(self, prop, fontext='ttf', directory=None, fallback_to_default=True, rebuild_if_missing=True): prop = FontProperties._from_any(prop) fpaths = [] for family in prop.get_family(): cprop = prop.copy() cprop.set_family(family) try: fpaths.append(self.findfont(cprop, fontext, directory, fallback_to_default=False, rebuild_if_missing=rebuild_if_missing)) except ValueError: if family in font_family_aliases: _log.warning('findfont: Generic family %r not found because none of the following families were found: %s', family, ', '.join(self._expand_aliases(family))) else: _log.warning('findfont: Font family %r not found.', family) if not fpaths: if fallback_to_default: dfamily = self.defaultFamily[fontext] cprop = prop.copy() cprop.set_family(dfamily) fpaths.append(self.findfont(cprop, fontext, directory, fallback_to_default=True, rebuild_if_missing=rebuild_if_missing)) else: raise ValueError('Failed to find any font, and fallback to the default font was disabled') return fpaths @lru_cache(1024) def _findfont_cached(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params): prop = FontProperties._from_any(prop) fname = prop.get_file() if fname is not None: return fname if fontext == 'afm': fontlist = self.afmlist else: fontlist = self.ttflist best_score = 1e+64 best_font = None _log.debug('findfont: Matching %s.', prop) for font in fontlist: if directory is not None and Path(directory) not in Path(font.fname).parents: continue score = self.score_family(prop.get_family(), font.name) * 10 + self.score_style(prop.get_style(), font.style) + self.score_variant(prop.get_variant(), font.variant) + self.score_weight(prop.get_weight(), font.weight) + self.score_stretch(prop.get_stretch(), font.stretch) + self.score_size(prop.get_size(), font.size) _log.debug('findfont: score(%s) = %s', font, score) if score < best_score: best_score = score best_font = font if score == 0: break if best_font is None or best_score >= 10.0: if fallback_to_default: _log.warning('findfont: Font family %s not found. Falling back to %s.', prop.get_family(), self.defaultFamily[fontext]) for family in map(str.lower, prop.get_family()): if family in font_family_aliases: _log.warning('findfont: Generic family %r not found because none of the following families were found: %s', family, ', '.join(self._expand_aliases(family))) default_prop = prop.copy() default_prop.set_family(self.defaultFamily[fontext]) return self.findfont(default_prop, fontext, directory, fallback_to_default=False) else: return _ExceptionProxy(ValueError, f'Failed to find font {prop}, and fallback to the default font was disabled') else: _log.debug('findfont: Matching %s to %s (%r) with score of %f.', prop, best_font.name, best_font.fname, best_score) result = best_font.fname if not os.path.isfile(result): if rebuild_if_missing: _log.info('findfont: Found a missing font file. Rebuilding cache.') new_fm = _load_fontmanager(try_read_cache=False) vars(self).update(vars(new_fm)) return self.findfont(prop, fontext, directory, rebuild_if_missing=False) else: return _ExceptionProxy(ValueError, 'No valid font could be found') return _cached_realpath(result) @lru_cache def is_opentype_cff_font(filename): if os.path.splitext(filename)[1].lower() == '.otf': with open(filename, 'rb') as fd: return fd.read(4) == b'OTTO' else: return False @lru_cache(64) def _get_font(font_filepaths, hinting_factor, *, _kerning_factor, thread_id): (first_fontpath, *rest) = font_filepaths return ft2font.FT2Font(first_fontpath, hinting_factor, _fallback_list=[ft2font.FT2Font(fpath, hinting_factor, _kerning_factor=_kerning_factor) for fpath in rest], _kerning_factor=_kerning_factor) if hasattr(os, 'register_at_fork'): os.register_at_fork(after_in_child=_get_font.cache_clear) @lru_cache(64) def _cached_realpath(path): return os.path.realpath(path) def get_font(font_filepaths, hinting_factor=None): if isinstance(font_filepaths, (str, Path, bytes)): paths = (_cached_realpath(font_filepaths),) else: paths = tuple((_cached_realpath(fname) for fname in font_filepaths)) if hinting_factor is None: hinting_factor = mpl.rcParams['text.hinting_factor'] return _get_font(paths, hinting_factor, _kerning_factor=mpl.rcParams['text.kerning_factor'], thread_id=threading.get_ident()) def _load_fontmanager(*, try_read_cache=True): fm_path = Path(mpl.get_cachedir(), f'fontlist-v{FontManager.__version__}.json') if try_read_cache: try: fm = json_load(fm_path) except Exception: pass else: if getattr(fm, '_version', object()) == FontManager.__version__: _log.debug('Using fontManager instance from %s', fm_path) return fm fm = FontManager() json_dump(fm, fm_path) _log.info('generated new fontManager') return fm fontManager = _load_fontmanager() findfont = fontManager.findfont get_font_names = fontManager.get_font_names # File: matplotlib-main/lib/matplotlib/gridspec.py """""" import copy import logging from numbers import Integral import numpy as np import matplotlib as mpl from matplotlib import _api, _pylab_helpers, _tight_layout from matplotlib.transforms import Bbox _log = logging.getLogger(__name__) class GridSpecBase: def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None): if not isinstance(nrows, Integral) or nrows <= 0: raise ValueError(f'Number of rows must be a positive integer, not {nrows!r}') if not isinstance(ncols, Integral) or ncols <= 0: raise ValueError(f'Number of columns must be a positive integer, not {ncols!r}') (self._nrows, self._ncols) = (nrows, ncols) self.set_height_ratios(height_ratios) self.set_width_ratios(width_ratios) def __repr__(self): height_arg = f', height_ratios={self._row_height_ratios!r}' if len(set(self._row_height_ratios)) != 1 else '' width_arg = f', width_ratios={self._col_width_ratios!r}' if len(set(self._col_width_ratios)) != 1 else '' return '{clsname}({nrows}, {ncols}{optionals})'.format(clsname=self.__class__.__name__, nrows=self._nrows, ncols=self._ncols, optionals=height_arg + width_arg) nrows = property(lambda self: self._nrows, doc='The number of rows in the grid.') ncols = property(lambda self: self._ncols, doc='The number of columns in the grid.') def get_geometry(self): return (self._nrows, self._ncols) def get_subplot_params(self, figure=None): pass def new_subplotspec(self, loc, rowspan=1, colspan=1): (loc1, loc2) = loc subplotspec = self[loc1:loc1 + rowspan, loc2:loc2 + colspan] return subplotspec def set_width_ratios(self, width_ratios): if width_ratios is None: width_ratios = [1] * self._ncols elif len(width_ratios) != self._ncols: raise ValueError('Expected the given number of width ratios to match the number of columns of the grid') self._col_width_ratios = width_ratios def get_width_ratios(self): return self._col_width_ratios def set_height_ratios(self, height_ratios): if height_ratios is None: height_ratios = [1] * self._nrows elif len(height_ratios) != self._nrows: raise ValueError('Expected the given number of height ratios to match the number of rows of the grid') self._row_height_ratios = height_ratios def get_height_ratios(self): return self._row_height_ratios def get_grid_positions(self, fig): (nrows, ncols) = self.get_geometry() subplot_params = self.get_subplot_params(fig) left = subplot_params.left right = subplot_params.right bottom = subplot_params.bottom top = subplot_params.top wspace = subplot_params.wspace hspace = subplot_params.hspace tot_width = right - left tot_height = top - bottom cell_h = tot_height / (nrows + hspace * (nrows - 1)) sep_h = hspace * cell_h norm = cell_h * nrows / sum(self._row_height_ratios) cell_heights = [r * norm for r in self._row_height_ratios] sep_heights = [0] + [sep_h] * (nrows - 1) cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat) cell_w = tot_width / (ncols + wspace * (ncols - 1)) sep_w = wspace * cell_w norm = cell_w * ncols / sum(self._col_width_ratios) cell_widths = [r * norm for r in self._col_width_ratios] sep_widths = [0] + [sep_w] * (ncols - 1) cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat) (fig_tops, fig_bottoms) = (top - cell_hs).reshape((-1, 2)).T (fig_lefts, fig_rights) = (left + cell_ws).reshape((-1, 2)).T return (fig_bottoms, fig_tops, fig_lefts, fig_rights) @staticmethod def _check_gridspec_exists(figure, nrows, ncols): for ax in figure.get_axes(): gs = ax.get_gridspec() if gs is not None: if hasattr(gs, 'get_topmost_subplotspec'): gs = gs.get_topmost_subplotspec().get_gridspec() if gs.get_geometry() == (nrows, ncols): return gs return GridSpec(nrows, ncols, figure=figure) def __getitem__(self, key): (nrows, ncols) = self.get_geometry() def _normalize(key, size, axis): orig_key = key if isinstance(key, slice): (start, stop, _) = key.indices(size) if stop > start: return (start, stop - 1) raise IndexError('GridSpec slice would result in no space allocated for subplot') else: if key < 0: key = key + size if 0 <= key < size: return (key, key) elif axis is not None: raise IndexError(f'index {orig_key} is out of bounds for axis {axis} with size {size}') else: raise IndexError(f'index {orig_key} is out of bounds for GridSpec with size {size}') if isinstance(key, tuple): try: (k1, k2) = key except ValueError as err: raise ValueError('Unrecognized subplot spec') from err (num1, num2) = np.ravel_multi_index([_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)], (nrows, ncols)) else: (num1, num2) = _normalize(key, nrows * ncols, None) return SubplotSpec(self, num1, num2) def subplots(self, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None): figure = self.figure if figure is None: raise ValueError('GridSpec.subplots() only works for GridSpecs created with a parent figure') if not isinstance(sharex, str): sharex = 'all' if sharex else 'none' if not isinstance(sharey, str): sharey = 'all' if sharey else 'none' _api.check_in_list(['all', 'row', 'col', 'none', False, True], sharex=sharex, sharey=sharey) if subplot_kw is None: subplot_kw = {} subplot_kw = subplot_kw.copy() axarr = np.empty((self._nrows, self._ncols), dtype=object) for row in range(self._nrows): for col in range(self._ncols): shared_with = {'none': None, 'all': axarr[0, 0], 'row': axarr[row, 0], 'col': axarr[0, col]} subplot_kw['sharex'] = shared_with[sharex] subplot_kw['sharey'] = shared_with[sharey] axarr[row, col] = figure.add_subplot(self[row, col], **subplot_kw) if sharex in ['col', 'all']: for ax in axarr.flat: ax._label_outer_xaxis(skip_non_rectangular_axes=True) if sharey in ['row', 'all']: for ax in axarr.flat: ax._label_outer_yaxis(skip_non_rectangular_axes=True) if squeeze: return axarr.item() if axarr.size == 1 else axarr.squeeze() else: return axarr class GridSpec(GridSpecBase): def __init__(self, nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None): self.left = left self.bottom = bottom self.right = right self.top = top self.wspace = wspace self.hspace = hspace self.figure = figure super().__init__(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) _AllowedKeys = ['left', 'bottom', 'right', 'top', 'wspace', 'hspace'] def update(self, **kwargs): for (k, v) in kwargs.items(): if k in self._AllowedKeys: setattr(self, k, v) else: raise AttributeError(f'{k} is an unknown keyword') for figmanager in _pylab_helpers.Gcf.figs.values(): for ax in figmanager.canvas.figure.axes: if ax.get_subplotspec() is not None: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: fig = ax.get_figure(root=False) ax._set_position(ax.get_subplotspec().get_position(fig)) def get_subplot_params(self, figure=None): if figure is None: kw = {k: mpl.rcParams['figure.subplot.' + k] for k in self._AllowedKeys} subplotpars = SubplotParams(**kw) else: subplotpars = copy.copy(figure.subplotpars) subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys}) return subplotpars def locally_modified_subplot_params(self): return [k for k in self._AllowedKeys if getattr(self, k)] def tight_layout(self, figure, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): if renderer is None: renderer = figure._get_renderer() kwargs = _tight_layout.get_tight_layout_figure(figure, figure.axes, _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self), renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) if kwargs: self.update(**kwargs) class GridSpecFromSubplotSpec(GridSpecBase): def __init__(self, nrows, ncols, subplot_spec, wspace=None, hspace=None, height_ratios=None, width_ratios=None): self._wspace = wspace self._hspace = hspace if isinstance(subplot_spec, SubplotSpec): self._subplot_spec = subplot_spec else: raise TypeError('subplot_spec must be type SubplotSpec, usually from GridSpec, or axes.get_subplotspec.') self.figure = self._subplot_spec.get_gridspec().figure super().__init__(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) def get_subplot_params(self, figure=None): hspace = self._hspace if self._hspace is not None else figure.subplotpars.hspace if figure is not None else mpl.rcParams['figure.subplot.hspace'] wspace = self._wspace if self._wspace is not None else figure.subplotpars.wspace if figure is not None else mpl.rcParams['figure.subplot.wspace'] figbox = self._subplot_spec.get_position(figure) (left, bottom, right, top) = figbox.extents return SubplotParams(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace) def get_topmost_subplotspec(self): return self._subplot_spec.get_topmost_subplotspec() class SubplotSpec: def __init__(self, gridspec, num1, num2=None): self._gridspec = gridspec self.num1 = num1 self.num2 = num2 def __repr__(self): return f'{self.get_gridspec()}[{self.rowspan.start}:{self.rowspan.stop}, {self.colspan.start}:{self.colspan.stop}]' @staticmethod def _from_subplot_args(figure, args): if len(args) == 1: (arg,) = args if isinstance(arg, SubplotSpec): return arg elif not isinstance(arg, Integral): raise ValueError(f'Single argument to subplot must be a three-digit integer, not {arg!r}') try: (rows, cols, num) = map(int, str(arg)) except ValueError: raise ValueError(f'Single argument to subplot must be a three-digit integer, not {arg!r}') from None elif len(args) == 3: (rows, cols, num) = args else: raise _api.nargs_error('subplot', takes='1 or 3', given=len(args)) gs = GridSpec._check_gridspec_exists(figure, rows, cols) if gs is None: gs = GridSpec(rows, cols, figure=figure) if isinstance(num, tuple) and len(num) == 2: if not all((isinstance(n, Integral) for n in num)): raise ValueError(f'Subplot specifier tuple must contain integers, not {num}') (i, j) = num else: if not isinstance(num, Integral) or num < 1 or num > rows * cols: raise ValueError(f'num must be an integer with 1 <= num <= {rows * cols}, not {num!r}') i = j = num return gs[i - 1:j] @property def num2(self): return self.num1 if self._num2 is None else self._num2 @num2.setter def num2(self, value): self._num2 = value def get_gridspec(self): return self._gridspec def get_geometry(self): (rows, cols) = self.get_gridspec().get_geometry() return (rows, cols, self.num1, self.num2) @property def rowspan(self): ncols = self.get_gridspec().ncols return range(self.num1 // ncols, self.num2 // ncols + 1) @property def colspan(self): ncols = self.get_gridspec().ncols (c1, c2) = sorted([self.num1 % ncols, self.num2 % ncols]) return range(c1, c2 + 1) def is_first_row(self): return self.rowspan.start == 0 def is_last_row(self): return self.rowspan.stop == self.get_gridspec().nrows def is_first_col(self): return self.colspan.start == 0 def is_last_col(self): return self.colspan.stop == self.get_gridspec().ncols def get_position(self, figure): gridspec = self.get_gridspec() (nrows, ncols) = gridspec.get_geometry() (rows, cols) = np.unravel_index([self.num1, self.num2], (nrows, ncols)) (fig_bottoms, fig_tops, fig_lefts, fig_rights) = gridspec.get_grid_positions(figure) fig_bottom = fig_bottoms[rows].min() fig_top = fig_tops[rows].max() fig_left = fig_lefts[cols].min() fig_right = fig_rights[cols].max() return Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top) def get_topmost_subplotspec(self): gridspec = self.get_gridspec() if hasattr(gridspec, 'get_topmost_subplotspec'): return gridspec.get_topmost_subplotspec() else: return self def __eq__(self, other): return (self._gridspec, self.num1, self.num2) == (getattr(other, '_gridspec', object()), getattr(other, 'num1', object()), getattr(other, 'num2', object())) def __hash__(self): return hash((self._gridspec, self.num1, self.num2)) def subgridspec(self, nrows, ncols, **kwargs): return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs) class SubplotParams: def __init__(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): for key in ['left', 'bottom', 'right', 'top', 'wspace', 'hspace']: setattr(self, key, mpl.rcParams[f'figure.subplot.{key}']) self.update(left, bottom, right, top, wspace, hspace) def update(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): if (left if left is not None else self.left) >= (right if right is not None else self.right): raise ValueError('left cannot be >= right') if (bottom if bottom is not None else self.bottom) >= (top if top is not None else self.top): raise ValueError('bottom cannot be >= top') if left is not None: self.left = left if right is not None: self.right = right if bottom is not None: self.bottom = bottom if top is not None: self.top = top if wspace is not None: self.wspace = wspace if hspace is not None: self.hspace = hspace # File: matplotlib-main/lib/matplotlib/hatch.py """""" import numpy as np from matplotlib import _api from matplotlib.path import Path class HatchPatternBase: 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.0 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.0 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([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('-+|/\\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', message=f'hatch must consist of a string of "{valid}" or None, but found the following invalid values "{invalids}". Passing invalid values is deprecated since %(since)s and will become an error %(removal)s.') def get_path(hatchpattern, density=6): 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) # File: matplotlib-main/lib/matplotlib/image.py """""" import math import os import logging from pathlib import Path import warnings import numpy as np import PIL.Image import PIL.PngImagePlugin import matplotlib as mpl from matplotlib import _api, cbook, cm from matplotlib import _image from matplotlib._image import * import matplotlib.artist as martist from matplotlib.backend_bases import FigureCanvasBase import matplotlib.colors as mcolors from matplotlib.transforms import Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo, IdentityTransform, TransformedBbox _log = logging.getLogger(__name__) _interpd_ = {'auto': _image.NEAREST, 'none': _image.NEAREST, '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} interpolations_names = set(_interpd_) def composite_images(images, renderer, magnification=1.0): 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): has_images = any((isinstance(x, _ImageBase) for x in artists)) 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: 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): 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 interpolation = image_obj.get_interpolation() if interpolation in ['antialiased', 'auto']: 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) 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): 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(martist.Artist, cm.ScalarMappable): zorder = 0 def __init__(self, ax, cmap=None, norm=None, interpolation=None, origin=None, filternorm=True, filterrad=4.0, resample=False, *, interpolation_stage=None, **kwargs): martist.Artist.__init__(self) cm.ScalarMappable.__init__(self, norm, cmap) if origin is None: origin = mpl.rcParams['image.origin'] _api.check_in_list(['upper', 'lower'], origin=origin) self.origin = origin self.set_filternorm(filternorm) self.set_filterrad(filterrad) self.set_interpolation(interpolation) self.set_interpolation_stage(interpolation_stage) self.set_resample(resample) self.axes = ax self._imcache = None self._internal_update(kwargs) def __str__(self): try: shape = self.get_shape() return f'{type(self).__name__}(shape={shape!r})' except RuntimeError: return type(self).__name__ def __getstate__(self): return {**super().__getstate__(), '_imcache': None} def get_size(self): return self.get_shape()[:2] def get_shape(self): if self._A is None: raise RuntimeError('You must first set the image array') return self._A.shape def set_alpha(self, alpha): 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): return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 else self._alpha def changed(self): self._imcache = None cm.ScalarMappable.changed(self) def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0, unsampled=False, round_to_pixel_border=True): 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': 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) 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') 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 A.dtype.kind == 'f': 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} to {scaled_dtype} for imshow.') else: da = A.max().astype('f8') - A.min().astype('f8') scaled_dtype = 'f8' if da > 100000000.0 else 'f4' A_resampled = _resample(self, A.astype(scaled_dtype), out_shape, t) if isinstance(self.norm, mcolors.NoNorm): A_resampled = A_resampled.astype(A.dtype) mask = np.where(A.mask, np.float32(np.nan), np.float32(1)) if A.mask.shape == A.shape else np.ones_like(A, np.float32) out_alpha = _resample(self, mask, out_shape, t, resample=True) del mask out_mask = np.isnan(out_alpha) out_alpha[out_mask] = 1 alpha = self.get_alpha() if alpha is not None and np.ndim(alpha) > 0: out_alpha *= _resample(self, alpha, out_shape, t, resample=True) resampled_masked = np.ma.masked_array(A_resampled, out_mask) output = self.norm(resampled_masked) else: if A.ndim == 2: self.norm.autoscale_None(A) A = self.to_rgba(A) alpha = self._get_scalar_alpha() if A.shape[2] == 3: output_alpha = 255 * alpha if A.dtype == np.uint8 else alpha else: output_alpha = _resample(self, A[..., 3], out_shape, t, alpha=alpha) output = _resample(self, _rgb_to_rgba(A[..., :3]), out_shape, t, alpha=alpha) output[..., 3] = output_alpha output = self.to_rgba(output, bytes=True, norm=False) if A.ndim == 2: alpha = self._get_scalar_alpha() alpha_channel = output[:, :, 3] alpha_channel[:] = 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 = 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): raise NotImplementedError('The make_image method must be overridden') def _check_unsampled_image(self): return False @martist.allow_rasterization def draw(self, renderer): if not self.get_visible(): self.stale = False return if self.get_array().size == 0: self.stale = False return 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() 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): if self._different_canvas(mouseevent) or not self.axes.contains(mouseevent)[0]: return (False, {}) trans = self.get_transform().inverted() (x, y) = trans.transform([mouseevent.x, mouseevent.y]) (xmin, xmax, ymin, ymax) = self.get_extent() 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): 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): 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 converted to float') if A.ndim == 3 and A.shape[-1] == 1: A = A.squeeze(-1) 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: 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) if A.dtype != np.uint8 and np.issubdtype(A.dtype, np.integer): A = A.astype(np.uint8) return A def set_data(self, A): if isinstance(A, PIL.Image.Image): A = pil_to_array(A) self._A = self._normalize_image_array(A) self._imcache = None self.stale = True def set_array(self, A): self.set_data(A) def get_interpolation(self): return self._interpolation def set_interpolation(self, s): 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 self._interpolation_stage def set_interpolation_stage(self, s): 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): trans = self.get_transform() return self._interpolation != 'none' and trans.is_affine and trans.is_separable def set_resample(self, v): v = mpl._val_or_rc(v, 'image.resample') self._resample = v self.stale = True def get_resample(self): return self._resample def set_filternorm(self, filternorm): self._filternorm = bool(filternorm) self.stale = True def get_filternorm(self): return self._filternorm def set_filterrad(self, filterrad): 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 self._filterrad class AxesImage(_ImageBase): def __init__(self, ax, *, cmap=None, norm=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, 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): trans = self.get_transform() (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 self.get_interpolation() == 'none' def set_extent(self, extent, **kwargs): ((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): 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): (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) if not 0 <= i < arr.shape[0] or not 0 <= j < arr.shape[1]: return None else: return arr[i, j] class NonUniformImage(AxesImage): def __init__(self, ax, *, interpolation='nearest', **kwargs): super().__init__(ax, **kwargs) self.set_interpolation(interpolation) def _check_unsampled_image(self): return False def make_image(self, renderer, magnification=1.0, unsampled=False): 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) 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: 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), 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) 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 return (im, l, b, IdentityTransform()) def set_data(self, x, y, A): 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): 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): (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): def __init__(self, ax, x=None, y=None, A=None, *, cmap=None, norm=None, **kwargs): super().__init__(ax, norm=norm, cmap=cmap) 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): 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 = 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): A = self._normalize_image_array(A) x = np.arange(0.0, A.shape[1] + 1) if x is None else np.array(x, float).ravel() y = np.arange(0.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))) 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): (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): zorder = 0 _interpolation = 'nearest' def __init__(self, fig, *, cmap=None, norm=None, offsetx=0, offsety=0, origin=None, **kwargs): super().__init__(None, norm=norm, cmap=cmap, origin=origin) self.set_figure(fig) self.ox = offsetx self.oy = offsety self._internal_update(kwargs) self.magnification = 1.0 def get_extent(self): (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): fig = self.get_figure(root=True) fac = renderer.dpi / fig.dpi 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): cm.ScalarMappable.set_array(self, A) self.stale = True class BboxImage(_ImageBase): def __init__(self, bbox, *, cmap=None, norm=None, interpolation=None, origin=None, filternorm=True, filterrad=4.0, resample=False, **kwargs): super().__init__(None, cmap=cmap, norm=norm, 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): 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): (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): from urllib import parse if format is None: if isinstance(fname, str): parsed = parse.urlparse(fname) if len(parsed.scheme) > 1: ext = 'png' else: ext = Path(fname).suffix.lower()[1:] elif hasattr(fname, 'geturl'): 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: 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): from matplotlib.figure import Figure if isinstance(fname, os.PathLike): fname = os.fspath(fname) if format is None: format = (Path(fname).suffix[1:] if isinstance(fname, str) else mpl.rcParams['savefig.format']).lower() if format in ['pdf', 'ps', 'eps', 'svg']: 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: 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): rgba = arr else: sm = cm.ScalarMappable(cmap=cmap) sm.set_clim(vmin, vmax) rgba = sm.to_rgba(arr, bytes=True) if pil_kwargs is None: pil_kwargs = {} else: 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': 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__}, 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' 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): if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']: return np.asarray(pilImage) elif pilImage.mode.startswith('I;16'): raw = pilImage.tobytes('raw', pilImage.mode) if pilImage.mode.endswith('B'): x = np.frombuffer(raw, '>u2') else: x = np.frombuffer(raw, ' 0; it was %d' % numpoints) if scatteryoffsets is None: self._scatteryoffsets = np.array([3.0 / 8.0, 4.0 / 8.0, 2.5 / 8.0]) else: self._scatteryoffsets = np.asarray(scatteryoffsets) reps = self.scatterpoints // len(self._scatteryoffsets) + 1 self._scatteryoffsets = np.tile(self._scatteryoffsets, reps)[:self.scatterpoints] self._legend_box = None if isinstance(parent, Axes): self.isaxes = True self.axes = parent self.set_figure(parent.get_figure(root=False)) elif isinstance(parent, FigureBase): self.isaxes = False self.set_figure(parent) else: raise TypeError('Legend needs either Axes or FigureBase as parent') self.parent = parent self._mode = mode self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform) self._shadow_props = {'ox': 2, 'oy': -2} if isinstance(self.shadow, dict): self._shadow_props.update(self.shadow) self.shadow = True elif self.shadow in (0, 1, True, False): self.shadow = bool(self.shadow) else: raise ValueError(f'Legend shadow must be a dict or bool, not {self.shadow!r} of type {type(self.shadow)}.') facecolor = mpl._val_or_rc(facecolor, 'legend.facecolor') if facecolor == 'inherit': facecolor = mpl.rcParams['axes.facecolor'] edgecolor = mpl._val_or_rc(edgecolor, 'legend.edgecolor') if edgecolor == 'inherit': edgecolor = mpl.rcParams['axes.edgecolor'] fancybox = mpl._val_or_rc(fancybox, 'legend.fancybox') self.legendPatch = FancyBboxPatch(xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, alpha=framealpha if framealpha is not None else 1 if shadow else mpl.rcParams['legend.framealpha'], boxstyle='round,pad=0,rounding_size=0.2' if fancybox else 'square,pad=0', mutation_scale=self._fontsize, snap=True, visible=mpl._val_or_rc(frameon, 'legend.frameon')) self._set_artist_props(self.legendPatch) _api.check_in_list(['center', 'left', 'right'], alignment=alignment) self._alignment = alignment self._init_legend_box(handles, labels, markerfirst) self.set_loc(loc) if title_fontsize is not None and title_fontproperties is not None: raise ValueError("title_fontsize and title_fontproperties can't be specified at the same time. Only use one of them. ") title_prop_fp = FontProperties._from_any(title_fontproperties) if isinstance(title_fontproperties, dict): if 'size' not in title_fontproperties: title_fontsize = mpl.rcParams['legend.title_fontsize'] title_prop_fp.set_size(title_fontsize) elif title_fontsize is not None: title_prop_fp.set_size(title_fontsize) elif not isinstance(title_fontproperties, FontProperties): title_fontsize = mpl.rcParams['legend.title_fontsize'] title_prop_fp.set_size(title_fontsize) self.set_title(title, prop=title_prop_fp) self._draggable = None self.set_draggable(state=draggable) color_getters = {'linecolor': ['get_color', 'get_facecolor'], 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'], 'mfc': ['get_markerfacecolor', 'get_facecolor'], 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'], 'mec': ['get_markeredgecolor', 'get_edgecolor']} labelcolor = mpl._val_or_rc(labelcolor, 'legend.labelcolor') if labelcolor is None: labelcolor = mpl.rcParams['text.color'] if isinstance(labelcolor, str) and labelcolor in color_getters: getter_names = color_getters[labelcolor] for (handle, text) in zip(self.legend_handles, self.texts): try: if handle.get_array() is not None: continue except AttributeError: pass for getter_name in getter_names: try: color = getattr(handle, getter_name)() if isinstance(color, np.ndarray): if color.shape[0] == 1 or np.isclose(color, color[0]).all(): text.set_color(color[0]) else: pass else: text.set_color(color) break except AttributeError: pass elif cbook._str_equal(labelcolor, 'none'): for text in self.texts: text.set_color(labelcolor) elif np.iterable(labelcolor): for (text, color) in zip(self.texts, itertools.cycle(colors.to_rgba_array(labelcolor))): text.set_color(color) else: raise ValueError(f'Invalid labelcolor: {labelcolor!r}') def _set_artist_props(self, a): a.set_figure(self.get_figure(root=False)) if self.isaxes: a.axes = self.axes a.set_transform(self.get_transform()) @_docstring.dedent_interpd def set_loc(self, loc=None): loc0 = loc self._loc_used_default = loc is None if loc is None: loc = mpl.rcParams['legend.loc'] if not self.isaxes and loc in [0, 'best']: loc = 'upper right' type_err_message = f'loc must be string, coordinate tuple, or an integer 0-10, not {loc!r}' self._outside_loc = None if isinstance(loc, str): if loc.split()[0] == 'outside': loc = loc.split('outside ')[1] self._outside_loc = loc.replace('center ', '') self._outside_loc = self._outside_loc.split()[0] locs = loc.split() if len(locs) > 1 and locs[0] in ('right', 'left'): if locs[0] != 'center': locs = locs[::-1] loc = locs[0] + ' ' + locs[1] loc = _api.check_getitem(self.codes, loc=loc) elif np.iterable(loc): loc = tuple(loc) if len(loc) != 2 or not all((isinstance(e, numbers.Real) for e in loc)): raise ValueError(type_err_message) elif isinstance(loc, int): if loc < 0 or loc > 10: raise ValueError(type_err_message) else: raise ValueError(type_err_message) if self.isaxes and self._outside_loc: raise ValueError(f"'outside' option for loc='{loc0}' keyword argument only works for figure legends") if not self.isaxes and loc == 0: raise ValueError("Automatic legend placement (loc='best') not implemented for figure legend") tmp = self._loc_used_default self._set_loc(loc) self._loc_used_default = tmp def _set_loc(self, loc): self._loc_used_default = False self._loc_real = loc self.stale = True self._legend_box.set_offset(self._findoffset) def set_ncols(self, ncols): self._ncols = ncols def _get_loc(self): return self._loc_real _loc = property(_get_loc, _set_loc) def _findoffset(self, width, height, xdescent, ydescent, renderer): if self._loc == 0: (x, y) = self._find_best_position(width, height, renderer) elif self._loc in Legend.codes.values(): bbox = Bbox.from_bounds(0, 0, width, height) (x, y) = self._get_anchored_bbox(self._loc, bbox, self.get_bbox_to_anchor(), renderer) else: (fx, fy) = self._loc bbox = self.get_bbox_to_anchor() (x, y) = (bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy) return (x + xdescent, y + ydescent) @allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group('legend', gid=self.get_gid()) fontsize = renderer.points_to_pixels(self._fontsize) if self._mode in ['expand']: pad = 2 * (self.borderaxespad + self.borderpad) * fontsize self._legend_box.set_width(self.get_bbox_to_anchor().width - pad) bbox = self._legend_box.get_window_extent(renderer) self.legendPatch.set_bounds(bbox.bounds) self.legendPatch.set_mutation_scale(fontsize) if self.shadow: Shadow(self.legendPatch, **self._shadow_props).draw(renderer) self.legendPatch.draw(renderer) self._legend_box.draw(renderer) renderer.close_group('legend') self.stale = False _default_handler_map = {StemContainer: legend_handler.HandlerStem(), ErrorbarContainer: legend_handler.HandlerErrorbar(), Line2D: legend_handler.HandlerLine2D(), Patch: legend_handler.HandlerPatch(), StepPatch: legend_handler.HandlerStepPatch(), LineCollection: legend_handler.HandlerLineCollection(), RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(), CircleCollection: legend_handler.HandlerCircleCollection(), BarContainer: legend_handler.HandlerPatch(update_func=legend_handler.update_from_first_child), tuple: legend_handler.HandlerTuple(), PathCollection: legend_handler.HandlerPathCollection(), PolyCollection: legend_handler.HandlerPolyCollection()} @classmethod def get_default_handler_map(cls): return cls._default_handler_map @classmethod def set_default_handler_map(cls, handler_map): cls._default_handler_map = handler_map @classmethod def update_default_handler_map(cls, handler_map): cls._default_handler_map.update(handler_map) def get_legend_handler_map(self): default_handler_map = self.get_default_handler_map() return {**default_handler_map, **self._custom_handler_map} if self._custom_handler_map else default_handler_map @staticmethod def get_legend_handler(legend_handler_map, orig_handle): try: return legend_handler_map[orig_handle] except (TypeError, KeyError): pass for handle_type in type(orig_handle).mro(): try: return legend_handler_map[handle_type] except KeyError: pass return None def _init_legend_box(self, handles, labels, markerfirst=True): fontsize = self._fontsize text_list = [] handle_list = [] handles_and_labels = [] descent = 0.35 * fontsize * (self.handleheight - 0.7) height = fontsize * self.handleheight - descent legend_handler_map = self.get_legend_handler_map() for (orig_handle, label) in zip(handles, labels): handler = self.get_legend_handler(legend_handler_map, orig_handle) if handler is None: _api.warn_external(f'Legend does not support handles for {type(orig_handle).__name__} instances.\nA proxy artist may be used instead.\nSee: https://matplotlib.org/stable/users/explain/axes/legend_guide.html#controlling-the-legend-entries') handle_list.append(None) else: textbox = TextArea(label, multilinebaseline=True, textprops=dict(verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop)) handlebox = DrawingArea(width=self.handlelength * fontsize, height=height, xdescent=0.0, ydescent=descent) text_list.append(textbox._text) handle_list.append(handler.legend_artist(self, orig_handle, fontsize, handlebox)) handles_and_labels.append((handlebox, textbox)) columnbox = [] for handles_and_labels_column in filter(len, np.array_split(handles_and_labels, self._ncols)): itemboxes = [HPacker(pad=0, sep=self.handletextpad * fontsize, children=[h, t] if markerfirst else [t, h], align='baseline') for (h, t) in handles_and_labels_column] alignment = 'baseline' if markerfirst else 'right' columnbox.append(VPacker(pad=0, sep=self.labelspacing * fontsize, align=alignment, children=itemboxes)) mode = 'expand' if self._mode == 'expand' else 'fixed' sep = self.columnspacing * fontsize self._legend_handle_box = HPacker(pad=0, sep=sep, align='baseline', mode=mode, children=columnbox) self._legend_title_box = TextArea('') self._legend_box = VPacker(pad=self.borderpad * fontsize, sep=self.labelspacing * fontsize, align=self._alignment, children=[self._legend_title_box, self._legend_handle_box]) self._legend_box.set_figure(self.get_figure(root=False)) self._legend_box.axes = self.axes self.texts = text_list self.legend_handles = handle_list def _auto_legend_data(self): assert self.isaxes bboxes = [] lines = [] offsets = [] for artist in self.parent._children: if isinstance(artist, Line2D): lines.append(artist.get_transform().transform_path(artist.get_path())) elif isinstance(artist, Rectangle): bboxes.append(artist.get_bbox().transformed(artist.get_data_transform())) elif isinstance(artist, Patch): lines.append(artist.get_transform().transform_path(artist.get_path())) elif isinstance(artist, PolyCollection): lines.extend((artist.get_transform().transform_path(path) for path in artist.get_paths())) elif isinstance(artist, Collection): (transform, transOffset, hoffsets, _) = artist._prepare_points() if len(hoffsets): offsets.extend(transOffset.transform(hoffsets)) elif isinstance(artist, Text): bboxes.append(artist.get_window_extent()) return (bboxes, lines, offsets) def get_children(self): return [self._legend_box, self.get_frame()] def get_frame(self): return self.legendPatch def get_lines(self): return [h for h in self.legend_handles if isinstance(h, Line2D)] def get_patches(self): return silent_list('Patch', [h for h in self.legend_handles if isinstance(h, Patch)]) def get_texts(self): return silent_list('Text', self.texts) def set_alignment(self, alignment): _api.check_in_list(['center', 'left', 'right'], alignment=alignment) self._alignment = alignment self._legend_box.align = alignment def get_alignment(self): return self._legend_box.align def set_title(self, title, prop=None): self._legend_title_box._text.set_text(title) if title: self._legend_title_box._text.set_visible(True) self._legend_title_box.set_visible(True) else: self._legend_title_box._text.set_visible(False) self._legend_title_box.set_visible(False) if prop is not None: self._legend_title_box._text.set_fontproperties(prop) self.stale = True def get_title(self): return self._legend_title_box._text def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() return self._legend_box.get_window_extent(renderer=renderer) def get_tightbbox(self, renderer=None): return self._legend_box.get_window_extent(renderer) def get_frame_on(self): return self.legendPatch.get_visible() def set_frame_on(self, b): self.legendPatch.set_visible(b) self.stale = True draw_frame = set_frame_on def get_bbox_to_anchor(self): if self._bbox_to_anchor is None: return self.parent.bbox else: return self._bbox_to_anchor def set_bbox_to_anchor(self, bbox, transform=None): if bbox is None: self._bbox_to_anchor = None return elif 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) if transform is None: transform = BboxTransformTo(self.parent.bbox) self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor, transform) self.stale = True def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer): return offsetbox._get_anchored_bbox(loc, bbox, parentbbox, self.borderaxespad * renderer.points_to_pixels(self._fontsize)) def _find_best_position(self, width, height, renderer): assert self.isaxes start_time = time.perf_counter() (bboxes, lines, offsets) = self._auto_legend_data() bbox = Bbox.from_bounds(0, 0, width, height) candidates = [] for idx in range(1, len(self.codes)): (l, b) = self._get_anchored_bbox(idx, bbox, self.get_bbox_to_anchor(), renderer) legendBox = Bbox.from_bounds(l, b, width, height) badness = sum((legendBox.count_contains(line.vertices) for line in lines)) + legendBox.count_contains(offsets) + legendBox.count_overlaps(bboxes) + sum((line.intersects_bbox(legendBox, filled=False) for line in lines)) candidates.append((badness, idx, (l, b))) if badness == 0: break (_, _, (l, b)) = min(candidates) if self._loc_used_default and time.perf_counter() - start_time > 1: _api.warn_external('Creating legend with loc="best" can be slow with large amounts of data.') return (l, b) def contains(self, mouseevent): return self.legendPatch.contains(mouseevent) def set_draggable(self, state, use_blit=False, update='loc'): if state: if self._draggable is None: self._draggable = DraggableLegend(self, use_blit, update=update) else: if self._draggable is not None: self._draggable.disconnect() self._draggable = None return self._draggable def get_draggable(self): return self._draggable is not None def _get_legend_handles(axs, legend_handler_map=None): handles_original = [] for ax in axs: handles_original += [*(a for a in ax._children if isinstance(a, (Line2D, Patch, Collection, Text))), *ax.containers] if hasattr(ax, 'parasites'): for axx in ax.parasites: handles_original += [*(a for a in axx._children if isinstance(a, (Line2D, Patch, Collection, Text))), *axx.containers] handler_map = {**Legend.get_default_handler_map(), **(legend_handler_map or {})} has_handler = Legend.get_legend_handler for handle in handles_original: label = handle.get_label() if label != '_nolegend_' and has_handler(handler_map, handle): yield handle elif label and (not label.startswith('_')) and (not has_handler(handler_map, handle)): _api.warn_external(f'Legend does not support handles for {type(handle).__name__} instances.\nSee: https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html#implementing-a-custom-legend-handler') continue def _get_legend_handles_labels(axs, legend_handler_map=None): handles = [] labels = [] for handle in _get_legend_handles(axs, legend_handler_map): label = handle.get_label() if label and (not label.startswith('_')): handles.append(handle) labels.append(label) return (handles, labels) def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): log = logging.getLogger(__name__) handlers = kwargs.get('handler_map') if (handles is not None or labels is not None) and args: _api.warn_deprecated('3.9', message='You have mixed positional and keyword arguments, some input may be discarded. This is deprecated since %(since)s and will become an error %(removal)s.') if hasattr(handles, '__len__') and hasattr(labels, '__len__') and (len(handles) != len(labels)): _api.warn_external(f'Mismatched number of handles and labels: len(handles) = {len(handles)} len(labels) = {len(labels)}') if handles and labels: (handles, labels) = zip(*zip(handles, labels)) elif handles is not None and labels is None: labels = [handle.get_label() for handle in handles] elif labels is not None and handles is None: handles = [handle for (handle, label) in zip(_get_legend_handles(axs, handlers), labels)] elif len(args) == 0: (handles, labels) = _get_legend_handles_labels(axs, handlers) if not handles: _api.warn_external('No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.') elif len(args) == 1: (labels,) = args if any((isinstance(l, Artist) for l in labels)): raise TypeError('A single argument passed to legend() must be a list of labels, but found an Artist in there.') handles = [handle for (handle, label) in zip(_get_legend_handles(axs, handlers), labels)] elif len(args) == 2: (handles, labels) = args[:2] else: raise _api.nargs_error('legend', '0-2', len(args)) return (handles, labels, kwargs) # File: matplotlib-main/lib/matplotlib/legend_handler.py """""" from itertools import cycle import numpy as np from matplotlib import cbook from matplotlib.lines import Line2D from matplotlib.patches import Rectangle import matplotlib.collections as mcoll def update_from_first_child(tgt, src): first_child = next(iter(src.get_children()), None) if first_child is not None: tgt.update_from(first_child) class HandlerBase: def __init__(self, xpad=0.0, ypad=0.0, update_func=None): (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): (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()) for a in artists: handlebox.add_artist(a) return artists[0] def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): raise NotImplementedError('Derived must override') class HandlerNpoints(HandlerBase): def __init__(self, marker_pad=0.3, numpoints=None, **kwargs): 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: 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): def __init__(self, numpoints=None, yoffsets=None, **kwargs): 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): def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): (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) legline._legmarker = legline_marker legline.set_transform(trans) legline_marker.set_transform(trans) return [legline, legline_marker] class HandlerLine2D(HandlerNpoints): def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): (xdata, xdata_marker) = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize) markevery = None if self.get_numpoints(legend) == 1: 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): def __init__(self, patch_func=None, **kwargs): 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): 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): @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): legline = Line2D([0, width], [height / 2, height / 2], color=orig_handle.get_edgecolor(), linestyle=orig_handle.get_linestyle(), linewidth=orig_handle.get_linewidth()) legline.set_drawstyle('default') legline.set_marker('') return legline def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): 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): 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): (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): 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 = [0.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_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): (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): 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): def create_collection(self, orig_handle, sizes, offsets, offset_transform): return type(orig_handle)(sizes, offsets=offsets, offset_transform=offset_transform) class HandlerErrorbar(HandlerLine2D): 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): (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) 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): def __init__(self, marker_pad=0.3, numpoints=None, bottom=None, yoffsets=None, **kwargs): 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): (markerline, stemlines, baseline) = orig_handle 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.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: 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): legend_handle.set_color(orig_handle.get_color()[0]) legend_handle.set_linestyle(orig_handle.get_linestyle()[0]) class HandlerTuple(HandlerBase): def __init__(self, ndivide=1, pad=None, **kwargs): self._ndivide = ndivide self._pad = pad super().__init__(**kwargs) def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): 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): 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 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() legend_handle._hatch_color = orig_handle._hatch_color 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()) def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): p = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p] # File: matplotlib-main/lib/matplotlib/lines.py """""" import copy from numbers import Integral, Number, Real import logging import numpy as np import matplotlib as mpl from . import _api, cbook, colors as mcolors, _docstring from .artist import Artist, allow_rasterization from .cbook import _to_unmasked_float_array, ls_mapper, ls_mapper_r, STEP_LOOKUP_MAP from .markers import MarkerStyle from .path import Path from .transforms import Bbox, BboxTransformTo, TransformedPath from ._enums import JoinStyle, CapStyle from . import _path from .markers import CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE, TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN _log = logging.getLogger(__name__) def _get_dash_pattern(style): if isinstance(style, str): style = ls_mapper.get(style, style) if style in ['solid', 'None']: offset = 0 dashes = None elif style in ['dashed', 'dashdot', 'dotted']: offset = 0 dashes = tuple(mpl.rcParams[f'lines.{style}_pattern']) elif isinstance(style, tuple): (offset, dashes) = style if offset is None: raise ValueError(f'Unrecognized linestyle: {style!r}') else: raise ValueError(f'Unrecognized linestyle: {style!r}') if dashes is not None: dsum = sum(dashes) if dsum: offset %= dsum return (offset, dashes) def _get_inverse_dash_pattern(offset, dashes): gaps = dashes[-1:] + dashes[:-1] offset_gaps = offset + dashes[-1] return (offset_gaps, gaps) def _scale_dashes(offset, dashes, lw): if not mpl.rcParams['lines.scale_dashes']: return (offset, dashes) scaled_offset = offset * lw scaled_dashes = [x * lw if x is not None else None for x in dashes] if dashes is not None else None return (scaled_offset, scaled_dashes) def segment_hits(cx, cy, x, y, radius): if len(x) <= 1: (res,) = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2) return res (xr, yr) = (x[:-1], y[:-1]) (dx, dy) = (x[1:] - xr, y[1:] - yr) Lnorm_sq = dx ** 2 + dy ** 2 u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq candidates = (u >= 0) & (u <= 1) point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2 candidates = candidates & ~(point_hits[:-1] | point_hits[1:]) (px, py) = (xr + u * dx, yr + u * dy) line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2 line_hits = line_hits & candidates (points,) = point_hits.ravel().nonzero() (lines,) = line_hits.ravel().nonzero() return np.concatenate((points, lines)) def _mark_every_path(markevery, tpath, affine, ax): (codes, verts) = (tpath.codes, tpath.vertices) def _slice_or_none(in_v, slc): if in_v is None: return None return in_v[slc] if isinstance(markevery, Integral): markevery = (0, markevery) elif isinstance(markevery, Real): markevery = (0.0, markevery) if isinstance(markevery, tuple): if len(markevery) != 2: raise ValueError(f'`markevery` is a tuple but its len is not 2; markevery={markevery}') (start, step) = markevery if isinstance(step, Integral): if not isinstance(start, Integral): raise ValueError(f'`markevery` is a tuple with len 2 and second element is an int, but the first element is not an int; markevery={markevery}') return Path(verts[slice(start, None, step)], _slice_or_none(codes, slice(start, None, step))) elif isinstance(step, Real): if not isinstance(start, Real): raise ValueError(f'`markevery` is a tuple with len 2 and second element is a float, but the first element is not a float or an int; markevery={markevery}') if ax is None: raise ValueError('markevery is specified relative to the Axes size, but the line does not have a Axes as parent') fin = np.isfinite(verts).all(axis=1) fverts = verts[fin] disp_coords = affine.transform(fverts) delta = np.empty((len(disp_coords), 2)) delta[0, :] = 0 delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :] delta = np.hypot(*delta.T).cumsum() ((x0, y0), (x1, y1)) = ax.transAxes.transform([[0, 0], [1, 1]]) scale = np.hypot(x1 - x0, y1 - y0) marker_delta = np.arange(start * scale, delta[-1], step * scale) inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis]) inds = inds.argmin(axis=1) inds = np.unique(inds) return Path(fverts[inds], _slice_or_none(codes, inds)) else: raise ValueError(f'markevery={markevery!r} is a tuple with len 2, but its second element is not an int or a float') elif isinstance(markevery, slice): return Path(verts[markevery], _slice_or_none(codes, markevery)) elif np.iterable(markevery): try: return Path(verts[markevery], _slice_or_none(codes, markevery)) except (ValueError, IndexError) as err: raise ValueError(f'markevery={markevery!r} is iterable but not a valid numpy fancy index') from err else: raise ValueError(f'markevery={markevery!r} is not a recognized value') @_docstring.interpd @_api.define_aliases({'antialiased': ['aa'], 'color': ['c'], 'drawstyle': ['ds'], 'linestyle': ['ls'], 'linewidth': ['lw'], 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markerfacecolor': ['mfc'], 'markerfacecoloralt': ['mfcalt'], 'markersize': ['ms']}) class Line2D(Artist): lineStyles = _lineStyles = {'-': '_draw_solid', '--': '_draw_dashed', '-.': '_draw_dash_dot', ':': '_draw_dotted', 'None': '_draw_nothing', ' ': '_draw_nothing', '': '_draw_nothing'} _drawStyles_l = {'default': '_draw_lines', 'steps-mid': '_draw_steps_mid', 'steps-pre': '_draw_steps_pre', 'steps-post': '_draw_steps_post'} _drawStyles_s = {'steps': '_draw_steps_pre'} drawStyles = {**_drawStyles_l, **_drawStyles_s} drawStyleKeys = [*_drawStyles_l, *_drawStyles_s] markers = MarkerStyle.markers filled_markers = MarkerStyle.filled_markers fillStyles = MarkerStyle.fillstyles zorder = 2 _subslice_optim_min_size = 1000 def __str__(self): if self._label != '': return f'Line2D({self._label})' elif self._x is None: return 'Line2D()' elif len(self._x) > 3: return 'Line2D(({:g},{:g}),({:g},{:g}),...,({:g},{:g}))'.format(self._x[0], self._y[0], self._x[1], self._y[1], self._x[-1], self._y[-1]) else: return 'Line2D(%s)' % ','.join(map('({:g},{:g})'.format, self._x, self._y)) def __init__(self, xdata, ydata, *, linewidth=None, linestyle=None, color=None, gapcolor=None, marker=None, markersize=None, markeredgewidth=None, markeredgecolor=None, markerfacecolor=None, markerfacecoloralt='none', fillstyle=None, antialiased=None, dash_capstyle=None, solid_capstyle=None, dash_joinstyle=None, solid_joinstyle=None, pickradius=5, drawstyle=None, markevery=None, **kwargs): super().__init__() if not np.iterable(xdata): raise RuntimeError('xdata must be a sequence') if not np.iterable(ydata): raise RuntimeError('ydata must be a sequence') if linewidth is None: linewidth = mpl.rcParams['lines.linewidth'] if linestyle is None: linestyle = mpl.rcParams['lines.linestyle'] if marker is None: marker = mpl.rcParams['lines.marker'] if color is None: color = mpl.rcParams['lines.color'] if markersize is None: markersize = mpl.rcParams['lines.markersize'] if antialiased is None: antialiased = mpl.rcParams['lines.antialiased'] if dash_capstyle is None: dash_capstyle = mpl.rcParams['lines.dash_capstyle'] if dash_joinstyle is None: dash_joinstyle = mpl.rcParams['lines.dash_joinstyle'] if solid_capstyle is None: solid_capstyle = mpl.rcParams['lines.solid_capstyle'] if solid_joinstyle is None: solid_joinstyle = mpl.rcParams['lines.solid_joinstyle'] if drawstyle is None: drawstyle = 'default' self._dashcapstyle = None self._dashjoinstyle = None self._solidjoinstyle = None self._solidcapstyle = None self.set_dash_capstyle(dash_capstyle) self.set_dash_joinstyle(dash_joinstyle) self.set_solid_capstyle(solid_capstyle) self.set_solid_joinstyle(solid_joinstyle) self._linestyles = None self._drawstyle = None self._linewidth = linewidth self._unscaled_dash_pattern = (0, None) self._dash_pattern = (0, None) self.set_linewidth(linewidth) self.set_linestyle(linestyle) self.set_drawstyle(drawstyle) self._color = None self.set_color(color) if marker is None: marker = 'none' if not isinstance(marker, MarkerStyle): self._marker = MarkerStyle(marker, fillstyle) else: self._marker = marker self._gapcolor = None self.set_gapcolor(gapcolor) self._markevery = None self._markersize = None self._antialiased = None self.set_markevery(markevery) self.set_antialiased(antialiased) self.set_markersize(markersize) self._markeredgecolor = None self._markeredgewidth = None self._markerfacecolor = None self._markerfacecoloralt = None self.set_markerfacecolor(markerfacecolor) self.set_markerfacecoloralt(markerfacecoloralt) self.set_markeredgecolor(markeredgecolor) self.set_markeredgewidth(markeredgewidth) self._internal_update(kwargs) self.pickradius = pickradius self.ind_offset = 0 if isinstance(self._picker, Number) and (not isinstance(self._picker, bool)): self._pickradius = self._picker self._xorig = np.asarray([]) self._yorig = np.asarray([]) self._invalidx = True self._invalidy = True self._x = None self._y = None self._xy = None self._path = None self._transformed_path = None self._subslice = False self._x_filled = None self.set_data(xdata, ydata) def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) if self._invalidy or self._invalidx: self.recache() if len(self._xy) == 0: return (False, {}) transformed_path = self._get_transformed_path() (path, affine) = transformed_path.get_transformed_path_and_affine() path = affine.transform_path(path) xy = path.vertices xt = xy[:, 0] yt = xy[:, 1] fig = self.get_figure(root=True) if fig is None: _log.warning('no figure set when check if mouse is on line') pixels = self._pickradius else: pixels = fig.dpi / 72.0 * self._pickradius with np.errstate(all='ignore'): if self._linestyle in ['None', None]: (ind,) = np.nonzero((xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2 <= pixels ** 2) else: ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels) if self._drawstyle.startswith('steps'): ind //= 2 ind += self.ind_offset return (len(ind) > 0, dict(ind=ind)) def get_pickradius(self): return self._pickradius def set_pickradius(self, pickradius): if not isinstance(pickradius, Real) or pickradius < 0: raise ValueError('pick radius should be a distance') self._pickradius = pickradius pickradius = property(get_pickradius, set_pickradius) def get_fillstyle(self): return self._marker.get_fillstyle() def set_fillstyle(self, fs): self.set_marker(MarkerStyle(self._marker.get_marker(), fs)) self.stale = True def set_markevery(self, every): self._markevery = every self.stale = True def get_markevery(self): return self._markevery def set_picker(self, p): if not callable(p): self.set_pickradius(p) self._picker = p def get_bbox(self): bbox = Bbox([[0, 0], [0, 0]]) bbox.update_from_data_xy(self.get_xydata()) return bbox def get_window_extent(self, renderer=None): bbox = Bbox([[0, 0], [0, 0]]) trans_data_to_xy = self.get_transform().transform bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()), ignore=True) if self._marker: ms = self._markersize / 72.0 * self.get_figure(root=True).dpi * 0.5 bbox = bbox.padded(ms) return bbox def set_data(self, *args): if len(args) == 1: ((x, y),) = args else: (x, y) = args self.set_xdata(x) self.set_ydata(y) def recache_always(self): self.recache(always=True) def recache(self, always=False): if always or self._invalidx: xconv = self.convert_xunits(self._xorig) x = _to_unmasked_float_array(xconv).ravel() else: x = self._x if always or self._invalidy: yconv = self.convert_yunits(self._yorig) y = _to_unmasked_float_array(yconv).ravel() else: y = self._y self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float) (self._x, self._y) = self._xy.T self._subslice = False if self.axes and len(x) > self._subslice_optim_min_size and _path.is_sorted_and_has_non_nan(x) and (self.axes.name == 'rectilinear') and (self.axes.get_xscale() == 'linear') and (self._markevery is None) and self.get_clip_on() and (self.get_transform() == self.axes.transData): self._subslice = True nanmask = np.isnan(x) if nanmask.any(): self._x_filled = self._x.copy() indices = np.arange(len(x)) self._x_filled[nanmask] = np.interp(indices[nanmask], indices[~nanmask], self._x[~nanmask]) else: self._x_filled = self._x if self._path is not None: interpolation_steps = self._path._interpolation_steps else: interpolation_steps = 1 xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy.T) self._path = Path(np.asarray(xy).T, _interpolation_steps=interpolation_steps) self._transformed_path = None self._invalidx = False self._invalidy = False def _transform_path(self, subslice=None): if subslice is not None: xy = STEP_LOOKUP_MAP[self._drawstyle](*self._xy[subslice, :].T) _path = Path(np.asarray(xy).T, _interpolation_steps=self._path._interpolation_steps) else: _path = self._path self._transformed_path = TransformedPath(_path, self.get_transform()) def _get_transformed_path(self): if self._transformed_path is None: self._transform_path() return self._transformed_path def set_transform(self, t): self._invalidx = True self._invalidy = True super().set_transform(t) @allow_rasterization def draw(self, renderer): if not self.get_visible(): return if self._invalidy or self._invalidx: self.recache() self.ind_offset = 0 if self._subslice and self.axes: (x0, x1) = self.axes.get_xbound() i0 = self._x_filled.searchsorted(x0, 'left') i1 = self._x_filled.searchsorted(x1, 'right') subslice = slice(max(i0 - 1, 0), i1 + 1) self.ind_offset = subslice.start self._transform_path(subslice) else: subslice = None if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer) renderer.open_group('line2d', self.get_gid()) if self._lineStyles[self._linestyle] != '_draw_nothing': (tpath, affine) = self._get_transformed_path().get_transformed_path_and_affine() if len(tpath.vertices): gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_url(self.get_url()) gc.set_antialiased(self._antialiased) gc.set_linewidth(self._linewidth) if self.is_dashed(): cap = self._dashcapstyle join = self._dashjoinstyle else: cap = self._solidcapstyle join = self._solidjoinstyle gc.set_joinstyle(join) gc.set_capstyle(cap) gc.set_snap(self.get_snap()) if self.get_sketch_params() is not None: gc.set_sketch_params(*self.get_sketch_params()) if self.is_dashed() and self._gapcolor is not None: lc_rgba = mcolors.to_rgba(self._gapcolor, self._alpha) gc.set_foreground(lc_rgba, isRGBA=True) (offset_gaps, gaps) = _get_inverse_dash_pattern(*self._dash_pattern) gc.set_dashes(offset_gaps, gaps) renderer.draw_path(gc, tpath, affine.frozen()) lc_rgba = mcolors.to_rgba(self._color, self._alpha) gc.set_foreground(lc_rgba, isRGBA=True) gc.set_dashes(*self._dash_pattern) renderer.draw_path(gc, tpath, affine.frozen()) gc.restore() if self._marker and self._markersize > 0: gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_url(self.get_url()) gc.set_linewidth(self._markeredgewidth) gc.set_antialiased(self._antialiased) ec_rgba = mcolors.to_rgba(self.get_markeredgecolor(), self._alpha) fc_rgba = mcolors.to_rgba(self._get_markerfacecolor(), self._alpha) fcalt_rgba = mcolors.to_rgba(self._get_markerfacecolor(alt=True), self._alpha) if cbook._str_equal(self._markeredgecolor, 'auto') and (not cbook._str_lower_equal(self.get_markerfacecolor(), 'none')): ec_rgba = ec_rgba[:3] + (fc_rgba[3],) gc.set_foreground(ec_rgba, isRGBA=True) if self.get_sketch_params() is not None: (scale, length, randomness) = self.get_sketch_params() gc.set_sketch_params(scale / 2, length / 2, 2 * randomness) marker = self._marker if self.get_drawstyle() != 'default': with cbook._setattr_cm(self, _drawstyle='default', _transformed_path=None): self.recache() self._transform_path(subslice) (tpath, affine) = self._get_transformed_path().get_transformed_points_and_affine() else: (tpath, affine) = self._get_transformed_path().get_transformed_points_and_affine() if len(tpath.vertices): markevery = self.get_markevery() if markevery is not None: subsampled = _mark_every_path(markevery, tpath, affine, self.axes) else: subsampled = tpath snap = marker.get_snap_threshold() if isinstance(snap, Real): snap = renderer.points_to_pixels(self._markersize) >= snap gc.set_snap(snap) gc.set_joinstyle(marker.get_joinstyle()) gc.set_capstyle(marker.get_capstyle()) marker_path = marker.get_path() marker_trans = marker.get_transform() w = renderer.points_to_pixels(self._markersize) if cbook._str_equal(marker.get_marker(), ','): gc.set_linewidth(0) else: marker_trans = marker_trans.scale(w) renderer.draw_markers(gc, marker_path, marker_trans, subsampled, affine.frozen(), fc_rgba) alt_marker_path = marker.get_alt_path() if alt_marker_path: alt_marker_trans = marker.get_alt_transform() alt_marker_trans = alt_marker_trans.scale(w) renderer.draw_markers(gc, alt_marker_path, alt_marker_trans, subsampled, affine.frozen(), fcalt_rgba) gc.restore() renderer.close_group('line2d') self.stale = False def get_antialiased(self): return self._antialiased def get_color(self): return self._color def get_drawstyle(self): return self._drawstyle def get_gapcolor(self): return self._gapcolor def get_linestyle(self): return self._linestyle def get_linewidth(self): return self._linewidth def get_marker(self): return self._marker.get_marker() def get_markeredgecolor(self): mec = self._markeredgecolor if cbook._str_equal(mec, 'auto'): if mpl.rcParams['_internal.classic_mode']: if self._marker.get_marker() in ('.', ','): return self._color if self._marker.is_filled() and self._marker.get_fillstyle() != 'none': return 'k' return self._color else: return mec def get_markeredgewidth(self): return self._markeredgewidth def _get_markerfacecolor(self, alt=False): if self._marker.get_fillstyle() == 'none': return 'none' fc = self._markerfacecoloralt if alt else self._markerfacecolor if cbook._str_lower_equal(fc, 'auto'): return self._color else: return fc def get_markerfacecolor(self): return self._get_markerfacecolor(alt=False) def get_markerfacecoloralt(self): return self._get_markerfacecolor(alt=True) def get_markersize(self): return self._markersize def get_data(self, orig=True): return (self.get_xdata(orig=orig), self.get_ydata(orig=orig)) def get_xdata(self, orig=True): if orig: return self._xorig if self._invalidx: self.recache() return self._x def get_ydata(self, orig=True): if orig: return self._yorig if self._invalidy: self.recache() return self._y def get_path(self): if self._invalidy or self._invalidx: self.recache() return self._path def get_xydata(self): if self._invalidy or self._invalidx: self.recache() return self._xy def set_antialiased(self, b): if self._antialiased != b: self.stale = True self._antialiased = b def set_color(self, color): mcolors._check_color_like(color=color) self._color = color self.stale = True def set_drawstyle(self, drawstyle): if drawstyle is None: drawstyle = 'default' _api.check_in_list(self.drawStyles, drawstyle=drawstyle) if self._drawstyle != drawstyle: self.stale = True self._invalidx = True self._drawstyle = drawstyle def set_gapcolor(self, gapcolor): if gapcolor is not None: mcolors._check_color_like(color=gapcolor) self._gapcolor = gapcolor self.stale = True def set_linewidth(self, w): w = float(w) if self._linewidth != w: self.stale = True self._linewidth = w self._dash_pattern = _scale_dashes(*self._unscaled_dash_pattern, w) def set_linestyle(self, ls): if isinstance(ls, str): if ls in [' ', '', 'none']: ls = 'None' _api.check_in_list([*self._lineStyles, *ls_mapper_r], ls=ls) if ls not in self._lineStyles: ls = ls_mapper_r[ls] self._linestyle = ls else: self._linestyle = '--' self._unscaled_dash_pattern = _get_dash_pattern(ls) self._dash_pattern = _scale_dashes(*self._unscaled_dash_pattern, self._linewidth) self.stale = True @_docstring.interpd def set_marker(self, marker): self._marker = MarkerStyle(marker, self._marker.get_fillstyle()) self.stale = True def _set_markercolor(self, name, has_rcdefault, val): if val is None: val = mpl.rcParams[f'lines.{name}'] if has_rcdefault else 'auto' attr = f'_{name}' current = getattr(self, attr) if current is None: self.stale = True else: neq = current != val if neq.any() if isinstance(neq, np.ndarray) else neq: self.stale = True setattr(self, attr, val) def set_markeredgecolor(self, ec): self._set_markercolor('markeredgecolor', True, ec) def set_markerfacecolor(self, fc): self._set_markercolor('markerfacecolor', True, fc) def set_markerfacecoloralt(self, fc): self._set_markercolor('markerfacecoloralt', False, fc) def set_markeredgewidth(self, ew): if ew is None: ew = mpl.rcParams['lines.markeredgewidth'] if self._markeredgewidth != ew: self.stale = True self._markeredgewidth = ew def set_markersize(self, sz): sz = float(sz) if self._markersize != sz: self.stale = True self._markersize = sz def set_xdata(self, x): if not np.iterable(x): raise RuntimeError('x must be a sequence') self._xorig = copy.copy(x) self._invalidx = True self.stale = True def set_ydata(self, y): if not np.iterable(y): raise RuntimeError('y must be a sequence') self._yorig = copy.copy(y) self._invalidy = True self.stale = True def set_dashes(self, seq): if seq == (None, None) or len(seq) == 0: self.set_linestyle('-') else: self.set_linestyle((0, seq)) def update_from(self, other): super().update_from(other) self._linestyle = other._linestyle self._linewidth = other._linewidth self._color = other._color self._gapcolor = other._gapcolor self._markersize = other._markersize self._markerfacecolor = other._markerfacecolor self._markerfacecoloralt = other._markerfacecoloralt self._markeredgecolor = other._markeredgecolor self._markeredgewidth = other._markeredgewidth self._unscaled_dash_pattern = other._unscaled_dash_pattern self._dash_pattern = other._dash_pattern self._dashcapstyle = other._dashcapstyle self._dashjoinstyle = other._dashjoinstyle self._solidcapstyle = other._solidcapstyle self._solidjoinstyle = other._solidjoinstyle self._linestyle = other._linestyle self._marker = MarkerStyle(marker=other._marker) self._drawstyle = other._drawstyle @_docstring.interpd def set_dash_joinstyle(self, s): js = JoinStyle(s) if self._dashjoinstyle != js: self.stale = True self._dashjoinstyle = js @_docstring.interpd def set_solid_joinstyle(self, s): js = JoinStyle(s) if self._solidjoinstyle != js: self.stale = True self._solidjoinstyle = js def get_dash_joinstyle(self): return self._dashjoinstyle.name def get_solid_joinstyle(self): return self._solidjoinstyle.name @_docstring.interpd def set_dash_capstyle(self, s): cs = CapStyle(s) if self._dashcapstyle != cs: self.stale = True self._dashcapstyle = cs @_docstring.interpd def set_solid_capstyle(self, s): cs = CapStyle(s) if self._solidcapstyle != cs: self.stale = True self._solidcapstyle = cs def get_dash_capstyle(self): return self._dashcapstyle.name def get_solid_capstyle(self): return self._solidcapstyle.name def is_dashed(self): return self._linestyle in ('--', '-.', ':') class AxLine(Line2D): def __init__(self, xy1, xy2, slope, **kwargs): super().__init__([0, 1], [0, 1], **kwargs) if xy2 is None and slope is None or (xy2 is not None and slope is not None): raise TypeError("Exactly one of 'xy2' and 'slope' must be given") self._slope = slope self._xy1 = xy1 self._xy2 = xy2 def get_transform(self): ax = self.axes points_transform = self._transform - ax.transData + ax.transScale if self._xy2 is not None: ((x1, y1), (x2, y2)) = points_transform.transform([self._xy1, self._xy2]) dx = x2 - x1 dy = y2 - y1 if np.allclose(x1, x2): if np.allclose(y1, y2): raise ValueError(f'Cannot draw a line through two identical points (x={(x1, x2)}, y={(y1, y2)})') slope = np.inf else: slope = dy / dx else: (x1, y1) = points_transform.transform(self._xy1) slope = self._slope ((vxlo, vylo), (vxhi, vyhi)) = ax.transScale.transform(ax.viewLim) if np.isclose(slope, 0): start = (vxlo, y1) stop = (vxhi, y1) elif np.isinf(slope): start = (x1, vylo) stop = (x1, vyhi) else: (_, start, stop, _) = sorted([(vxlo, y1 + (vxlo - x1) * slope), (vxhi, y1 + (vxhi - x1) * slope), (x1 + (vylo - y1) / slope, vylo), (x1 + (vyhi - y1) / slope, vyhi)]) return BboxTransformTo(Bbox([start, stop])) + ax.transLimits + ax.transAxes def draw(self, renderer): self._transformed_path = None super().draw(renderer) def get_xy1(self): return self._xy1 def get_xy2(self): return self._xy2 def get_slope(self): return self._slope def set_xy1(self, x, y): self._xy1 = (x, y) def set_xy2(self, x, y): if self._slope is None: self._xy2 = (x, y) else: raise ValueError("Cannot set an 'xy2' value while 'slope' is set; they differ but their functionalities overlap") def set_slope(self, slope): if self._xy2 is None: self._slope = slope else: raise ValueError("Cannot set a 'slope' value while 'xy2' is set; they differ but their functionalities overlap") class VertexSelector: def __init__(self, line): if line.axes is None: raise RuntimeError('You must first add the line to the Axes') if line.get_picker() is None: raise RuntimeError('You must first set the picker property of the line') self.axes = line.axes self.line = line self.cid = self.canvas.callbacks._connect_picklable('pick_event', self.onpick) self.ind = set() canvas = property(lambda self: self.axes.get_figure(root=True).canvas) def process_selected(self, ind, xs, ys): pass def onpick(self, event): if event.artist is not self.line: return self.ind ^= set(event.ind) ind = sorted(self.ind) (xdata, ydata) = self.line.get_data() self.process_selected(ind, xdata[ind], ydata[ind]) lineStyles = Line2D._lineStyles lineMarkers = MarkerStyle.markers drawStyles = Line2D.drawStyles fillStyles = MarkerStyle.fillstyles # File: matplotlib-main/lib/matplotlib/markers.py """""" import copy from collections.abc import Sized import numpy as np import matplotlib as mpl from . import _api, cbook from .path import Path from .transforms import IdentityTransform, Affine2D from ._enums import JoinStyle, CapStyle (TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN, CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = range(12) _empty_path = Path(np.empty((0, 2))) class MarkerStyle: 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'} 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): 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 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): 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): 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 self._path def get_transform(self): if self._user_transform is None: return self._transform.frozen() else: return (self._transform + self._user_transform).frozen() def get_alt_path(self): return self._alt_path def get_alt_transform(self): 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): if self._user_transform is not None: return self._user_transform.frozen() def transformed(self, 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): 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): 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)) 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): from matplotlib.text import TextPath 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.0) def _set_point(self): self._set_circle(size=0.5) def _set_pixel(self): self._path = Path.unit_rectangle() self._transform = Affine2D().translate(-0.49999, -0.49999) self._snap_threshold = None _triangle_path = Path._create_closed([[0, 1], [-1, -1], [1, -1]]) _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: 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.0 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 x = np.abs(np.cos(5 * np.pi / 6.0)) 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 (x, y) = (np.sqrt(3) / 4, 3 / 4.0) 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.0) / 4.0 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: 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: 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) # File: matplotlib-main/lib/matplotlib/mathtext.py """""" import functools import logging import matplotlib as mpl from matplotlib import _api, _mathtext from matplotlib.ft2font import LOAD_NO_HINTING from matplotlib.font_manager import FontProperties from ._mathtext import RasterParse, VectorParse, get_unicode_index _log = logging.getLogger(__name__) get_unicode_index.__module__ = __name__ class MathTextParser: _parser = None _font_type_mapping = {'cm': _mathtext.BakomaFonts, 'dejavuserif': _mathtext.DejaVuSerifFonts, 'dejavusans': _mathtext.DejaVuSansFonts, 'stix': _mathtext.StixFonts, 'stixsans': _mathtext.StixSansFonts, 'custom': _mathtext.UnicodeFonts} def __init__(self, output): self._output_type = _api.check_getitem({'path': 'vector', 'agg': 'raster', 'macosx': 'raster'}, output=output.lower()) def parse(self, s, dpi=72, prop=None, *, antialiased=None): prop = prop.copy() if prop is not None else None antialiased = mpl._val_or_rc(antialiased, 'text.antialiased') from matplotlib.backends import backend_agg load_glyph_flags = {'vector': LOAD_NO_HINTING, 'raster': backend_agg.get_hinting_flag()}[self._output_type] return self._parse_cached(s, dpi, prop, antialiased, load_glyph_flags) @functools.lru_cache(50) def _parse_cached(self, s, dpi, prop, antialiased, load_glyph_flags): if prop is None: prop = FontProperties() fontset_class = _api.check_getitem(self._font_type_mapping, fontset=prop.get_math_fontfamily()) fontset = fontset_class(prop, load_glyph_flags) fontsize = prop.get_size_in_points() if self._parser is None: self.__class__._parser = _mathtext.Parser() box = self._parser.parse(s, fontset, fontsize, dpi) output = _mathtext.ship(box) if self._output_type == 'vector': return output.to_vector() elif self._output_type == 'raster': return output.to_raster(antialiased=antialiased) def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None, *, color=None): from matplotlib import figure parser = MathTextParser('path') (width, height, depth, _, _) = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth / height, s, fontproperties=prop, color=color) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth # File: matplotlib-main/lib/matplotlib/mlab.py """""" import functools from numbers import Number import numpy as np from matplotlib import _api, _docstring, cbook def window_hanning(x): return np.hanning(len(x)) * x def window_none(x): return x def detrend(x, key=None, axis=None): 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: 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', 'constant', 'mean', 'linear', or a function") def detrend_mean(x, axis=None): 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 def detrend_linear(y): y = np.asarray(y) if y.ndim > 1: raise ValueError('y cannot have ndim > 1') if not y.ndim: return np.array(0.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): if y is None: same_data = True else: 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 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'") 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) 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 if sides == 'twosided': numFreqs = pad_to if pad_to % 2: freqcenter = (pad_to - 1) // 2 + 1 else: freqcenter = pad_to // 2 scaling_factor = 1.0 elif sides == 'onesided': if pad_to % 2: numFreqs = (pad_to + 1) // 2 else: numFreqs = pad_to // 2 + 1 scaling_factor = 2.0 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: 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': result = np.angle(result) elif mode == 'complex': result /= window.sum() if mode == 'psd': if not NFFT % 2: slc = slice(1, -1, None) else: slc = slice(1, None, None) result[slc] *= scaling_factor if scale_by_freq: result /= Fs result /= (window ** 2).sum() else: result /= window.sum() ** 2 t = np.arange(NFFT / 2, len(x) - NFFT / 2 + 1, NFFT - noverlap) / Fs if sides == 'twosided': freqs = np.roll(freqs, -freqcenter, axis=0) result = np.roll(result, -freqcenter, axis=0) elif not pad_to % 2: freqs[-1] *= -1 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): _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) _docstring.interpd.update(Spectral="Fs : float, default: 2\n The sampling frequency (samples per time unit). It is used to calculate\n the Fourier frequencies, *freqs*, in cycles per time unit.\n\nwindow : callable or ndarray, default: `.window_hanning`\n A function or a vector of length *NFFT*. To create window vectors see\n `.window_hanning`, `.window_none`, `numpy.blackman`, `numpy.hamming`,\n `numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc. If a\n function is passed as the argument, it must take a data segment as an\n argument and return the windowed version of the segment.\n\nsides : {'default', 'onesided', 'twosided'}, optional\n Which sides of the spectrum to return. 'default' is one-sided for real\n data and two-sided for complex data. 'onesided' forces the return of a\n one-sided spectrum, while 'twosided' forces two-sided.", Single_Spectrum='pad_to : int, optional\n The number of points to which the data segment is padded when performing\n the FFT. While not increasing the actual resolution of the spectrum (the\n minimum distance between resolvable peaks), this can give more points in\n the plot, allowing for more detail. This corresponds to the *n* parameter\n in the call to `~numpy.fft.fft`. The default is None, which sets *pad_to*\n equal to the length of the input signal (i.e. no padding).', PSD="pad_to : int, optional\n The number of points to which the data segment is padded when performing\n the FFT. This can be different from *NFFT*, which specifies the number\n of data points used. While not increasing the actual resolution of the\n spectrum (the minimum distance between resolvable peaks), this can give\n more points in the plot, allowing for more detail. This corresponds to\n the *n* parameter in the call to `~numpy.fft.fft`. The default is None,\n which sets *pad_to* equal to *NFFT*\n\nNFFT : int, default: 256\n The number of data points used in each block for the FFT. A power 2 is\n most efficient. This should *NOT* be used to get zero padding, or the\n scaling of the result will be incorrect; use *pad_to* for this instead.\n\ndetrend : {'none', 'mean', 'linear'} or callable, default: 'none'\n The function applied to each segment before fft-ing, designed to remove\n the mean or linear trend. Unlike in MATLAB, where the *detrend* parameter\n is a vector, in Matplotlib it is a function. The :mod:`~matplotlib.mlab`\n module defines `.detrend_none`, `.detrend_mean`, and `.detrend_linear`,\n but you can use a custom function as well. You can also use a string to\n choose one of the functions: 'none' calls `.detrend_none`. 'mean' calls\n `.detrend_mean`. 'linear' calls `.detrend_linear`.\n\nscale_by_freq : bool, default: True\n Whether the resulting density values should be scaled by the scaling\n frequency, which gives density in units of 1/Hz. This allows for\n integration over the returned frequency values. The default is True for\n MATLAB compatibility.") @_docstring.dedent_interpd def psd(x, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None): (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.dedent_interpd def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None): 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*.\nData is padded to a length of *pad_to* and the windowing function *window* is\napplied to the signal.\n\nParameters\n----------\nx : 1-D array or sequence\n Array or sequence containing the data\n\n{Spectral}\n\n{Single_Spectrum}\n\nReturns\n-------\nspectrum : 1-D array\n The {quantity}.\nfreqs : 1-D array\n The frequencies corresponding to the elements in *spectrum*.\n\nSee Also\n--------\npsd\n Returns the power spectral density.\ncomplex_spectrum\n Returns the complex-valued frequency spectrum.\nmagnitude_spectrum\n Returns the absolute value of the `complex_spectrum`.\nangle_spectrum\n Returns the angle of the `complex_spectrum`.\nphase_spectrum\n Returns the phase (unwrapped angle) of the `complex_spectrum`.\nspecgram\n Can return the complex spectrum of segments within the signal.\n' 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.dedent_interpd def specgram(x, NFFT=None, Fs=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, mode=None): if noverlap is None: noverlap = 128 if NFFT is None: NFFT = 256 if len(x) <= NFFT: _api.warn_external(f'Only one segment is calculated since parameter 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 return (spec, freqs, t) @_docstring.dedent_interpd def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None): 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: 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") self.factor = self.covariance_factor() 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.0 / (self.dim + 4)) def silverman_factor(self): return np.power(self.num_dp * (self.dim + 2.0) / 4.0, -1.0 / (self.dim + 4)) covariance_factor = scotts_factor def evaluate(self, points): 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 dimension {self.dim}') result = np.zeros(num_m) if num_m >= self.num_dp: 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: 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__ = evaluate # File: matplotlib-main/lib/matplotlib/offsetbox.py """""" import functools import numpy as np import matplotlib as mpl from matplotlib import _api, _docstring import matplotlib.artist as martist import matplotlib.path as mpath import matplotlib.text as mtext import matplotlib.transforms as mtransforms from matplotlib.font_manager import FontProperties from matplotlib.image import BboxImage from matplotlib.patches import FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist from matplotlib.transforms import Bbox, BboxBase, TransformedBbox DEBUG = False def _compat_get_offset(meth): 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 def _bbox_artist(*args, **kwargs): if DEBUG: mbbox_artist(*args, **kwargs) def _get_packed_offsets(widths, total, sep, mode='fixed'): _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': 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'): _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)) * 0.5 - y0 for (y0, y1) in yspans] return (yspan, offsets) class OffsetBox(martist.Artist): def __init__(self, *args, **kwargs): super().__init__(*args) self._internal_update(kwargs) self.set_clip_on(False) self._children = [] self._offset = (0, 0) def set_figure(self, fig): super().set_figure(fig) for c in self.get_children(): c.set_figure(fig) @martist.Artist.axes.setter def axes(self, ax): martist.Artist.axes.fset(self, ax) for c in self.get_children(): if c is not None: c.axes = ax def contains(self, mouseevent): 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): self._offset = xy self.stale = True @_compat_get_offset def get_offset(self, bbox, renderer): return self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer) if callable(self._offset) else self._offset def set_width(self, width): self.width = width self.stale = True def set_height(self, height): self.height = height self.stale = True def get_visible_children(self): return [c for c in self._children if c.get_visible()] def get_children(self): return self._children def _get_bbox_and_child_offsets(self, renderer): raise NotImplementedError('get_bbox_and_offsets must be overridden in derived classes') def get_bbox(self, renderer): (bbox, offsets) = self._get_bbox_and_child_offsets(renderer) return bbox def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() bbox = self.get_bbox(renderer) try: (px, py) = self.get_offset(bbox, renderer) except TypeError: (px, py) = self.get_offset() return bbox.translated(px, py) def draw(self, 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.0)) self.stale = False class PackerBase(OffsetBox): def __init__(self, pad=0.0, sep=0.0, width=None, height=None, align='baseline', mode='fixed', children=None): 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): def _get_bbox_and_child_offsets(self, renderer): dpicor = renderer.points_to_pixels(1.0) 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): def _get_bbox_and_child_offsets(self, renderer): dpicor = renderer.points_to_pixels(1.0) 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): def __init__(self, child, pad=0.0, *, draw_frame=False, patch_attrs=None): super().__init__() self.pad = pad self._children = [child] self.patch = FancyBboxPatch(xy=(0.0, 0.0), width=1.0, height=1.0, facecolor='w', edgecolor='k', mutation_scale=1, 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): pad = self.pad * renderer.points_to_pixels(1.0) return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)]) def draw(self, 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)) 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): self.update_frame(self.get_window_extent(renderer)) self.patch.draw(renderer) class DrawingArea(OffsetBox): def __init__(self, width, height, xdescent=0.0, ydescent=0.0, clip=False): 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): 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 self.dpi_transform + self.offset_transform def set_transform(self, t): def set_offset(self, xy): self._offset = xy self.offset_transform.clear() self.offset_transform.translate(xy[0], xy[1]) self.stale = True def get_offset(self): return self._offset def get_bbox(self, renderer): dpi_cor = renderer.points_to_pixels(1.0) 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): 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): dpi_cor = renderer.points_to_pixels(1.0) self.dpi_transform.clear() self.dpi_transform.scale(dpi_cor) 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.0)) self.stale = False class TextArea(OffsetBox): def __init__(self, s, *, textprops=None, multilinebaseline=False): 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): self._text.set_text(s) self.stale = True def get_text(self): return self._text.get_text() def set_multilinebaseline(self, t): self._multilinebaseline = t self.stale = True def get_multilinebaseline(self): return self._multilinebaseline def set_transform(self, t): def set_offset(self, xy): self._offset = xy self.offset_transform.clear() self.offset_transform.translate(xy[0], xy[1]) self.stale = True def get_offset(self): return self._offset def get_bbox(self, renderer): (_, h_, d_) = renderer.get_text_width_height_descent('lp', self._text._fontproperties, ismath='TeX' if self._text.get_usetex() else False) (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: 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): self._text.draw(renderer) _bbox_artist(self, renderer, fill=False, props=dict(pad=0.0)) self.stale = False class AuxTransformBox(OffsetBox): def __init__(self, aux_transform): self.aux_transform = aux_transform super().__init__() self.offset_transform = mtransforms.Affine2D() self.ref_offset_transform = mtransforms.Affine2D() def add_artist(self, a): self._children.append(a) a.set_transform(self.get_transform()) self.stale = True def get_transform(self): return self.aux_transform + self.ref_offset_transform + self.offset_transform def set_transform(self, t): def set_offset(self, xy): self._offset = xy self.offset_transform.clear() self.offset_transform.translate(xy[0], xy[1]) self.stale = True def get_offset(self): return self._offset def get_bbox(self, renderer): _off = self.offset_transform.get_matrix() self.ref_offset_transform.clear() self.offset_transform.clear() bboxes = [c.get_window_extent(renderer) for c in self._children] ub = Bbox.union(bboxes) self.ref_offset_transform.translate(-ub.x0, -ub.y0) self.offset_transform.set_matrix(_off) return Bbox.from_bounds(0, 0, ub.width, ub.height) def draw(self, renderer): for c in self._children: c.draw(renderer) _bbox_artist(self, renderer, fill=False, props=dict(pad=0.0)) self.stale = False class AnchoredOffsetbox(OffsetBox): zorder = 5 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): 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.0, height=1.0, 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): self._child = child if child is not None: child.axes = self.axes self.stale = True def get_child(self): return self._child def get_children(self): return [self._child] def get_bbox(self, renderer): 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): 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): 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): 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): if not self.get_visible(): return 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): 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): def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs): 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 self._offset def get_children(self): return [self.image] def get_bbox(self, renderer): dpi_cor = renderer.points_to_pixels(1.0) if self._dpi_cor else 1.0 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): self.image.draw(renderer) self.stale = False class AnnotationBbox(martist.Artist, mtext._AnnotationBase): zorder = 3 def __str__(self): return f'AnnotationBbox({self.xy[0]:g},{self.xy[1]:g})' @_docstring.dedent_interpd def __init__(self, offsetbox, xy, xybox=None, xycoords='data', boxcoords=None, *, frameon=True, pad=0.4, annotation_clip=None, box_alignment=(0.5, 0.5), bboxprops=None, arrowprops=None, fontsize=None, **kwargs): 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(xy=(0.0, 0.0), width=1.0, height=1.0, 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) 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): if s is None: s = mpl.rcParams['legend.fontsize'] self.prop = FontProperties(size=s) self.stale = True def get_fontsize(self): return self.prop.get_size_in_points() def get_window_extent(self, renderer=None): 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): 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): (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: arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos arrow_end = self._get_position_xy(renderer) 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']) 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): 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: def __init__(self, ref_artist, use_blit=False): self.ref_artist = ref_artist if not ref_artist.pickable(): ref_artist.set_picker(True) 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)]] 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): 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)) # File: matplotlib-main/lib/matplotlib/patches.py """""" import functools import inspect import math from numbers import Number, Real import textwrap from types import SimpleNamespace from collections import namedtuple from matplotlib.transforms import Affine2D import numpy as np import matplotlib as mpl from . import _api, artist, cbook, colors, _docstring, hatch as mhatch, lines as mlines, transforms from .bezier import NonIntersectingPathException, get_cos_sin, get_intersection, get_parallels, inside_circle, make_wedged_bezier2, split_bezier_intersecting_with_closedpath, split_path_inout from .path import Path from ._enums import JoinStyle, CapStyle @_docstring.interpd @_api.define_aliases({'antialiased': ['aa'], 'edgecolor': ['ec'], 'facecolor': ['fc'], 'linestyle': ['ls'], 'linewidth': ['lw']}) class Patch(artist.Artist): zorder = 1 _edge_default = False def __init__(self, *, edgecolor=None, facecolor=None, color=None, linewidth=None, linestyle=None, antialiased=None, hatch=None, fill=True, capstyle=None, joinstyle=None, **kwargs): super().__init__() if linestyle is None: linestyle = 'solid' if capstyle is None: capstyle = CapStyle.butt if joinstyle is None: joinstyle = JoinStyle.miter self._hatch_color = colors.to_rgba(mpl.rcParams['hatch.color']) self._fill = bool(fill) if color is not None: if edgecolor is not None or facecolor is not None: _api.warn_external("Setting the 'color' property will override the edgecolor or facecolor properties.") self.set_color(color) else: self.set_edgecolor(edgecolor) self.set_facecolor(facecolor) self._linewidth = 0 self._unscaled_dash_pattern = (0, None) self._dash_pattern = (0, None) self.set_linestyle(linestyle) self.set_linewidth(linewidth) self.set_antialiased(antialiased) self.set_hatch(hatch) self.set_capstyle(capstyle) self.set_joinstyle(joinstyle) if len(kwargs): self._internal_update(kwargs) def get_verts(self): trans = self.get_transform() path = self.get_path() polygons = path.to_polygons(trans) if len(polygons): return polygons[0] return [] def _process_radius(self, radius): if radius is not None: return radius if isinstance(self._picker, Number): _radius = self._picker elif self.get_edgecolor()[3] == 0: _radius = 0 else: _radius = self.get_linewidth() return _radius def contains(self, mouseevent, radius=None): if self._different_canvas(mouseevent): return (False, {}) radius = self._process_radius(radius) codes = self.get_path().codes if codes is not None: vertices = self.get_path().vertices (idxs,) = np.where(codes == Path.MOVETO) idxs = idxs[1:] subpaths = map(Path, np.split(vertices, idxs), np.split(codes, idxs)) else: subpaths = [self.get_path()] inside = any((subpath.contains_point((mouseevent.x, mouseevent.y), self.get_transform(), radius) for subpath in subpaths)) return (inside, {}) def contains_point(self, point, radius=None): radius = self._process_radius(radius) return self.get_path().contains_point(point, self.get_transform(), radius) def contains_points(self, points, radius=None): radius = self._process_radius(radius) return self.get_path().contains_points(points, self.get_transform(), radius) def update_from(self, other): super().update_from(other) self._edgecolor = other._edgecolor self._facecolor = other._facecolor self._original_edgecolor = other._original_edgecolor self._original_facecolor = other._original_facecolor self._fill = other._fill self._hatch = other._hatch self._hatch_color = other._hatch_color self._unscaled_dash_pattern = other._unscaled_dash_pattern self.set_linewidth(other._linewidth) self.set_transform(other.get_data_transform()) self._transformSet = other.is_transform_set() def get_extents(self): return self.get_path().get_extents(self.get_transform()) def get_transform(self): return self.get_patch_transform() + artist.Artist.get_transform(self) def get_data_transform(self): return artist.Artist.get_transform(self) def get_patch_transform(self): return transforms.IdentityTransform() def get_antialiased(self): return self._antialiased def get_edgecolor(self): return self._edgecolor def get_facecolor(self): return self._facecolor def get_linewidth(self): return self._linewidth def get_linestyle(self): return self._linestyle def set_antialiased(self, aa): if aa is None: aa = mpl.rcParams['patch.antialiased'] self._antialiased = aa self.stale = True def _set_edgecolor(self, color): set_hatch_color = True if color is None: if mpl.rcParams['patch.force_edgecolor'] or not self._fill or self._edge_default: color = mpl.rcParams['patch.edgecolor'] else: color = 'none' set_hatch_color = False self._edgecolor = colors.to_rgba(color, self._alpha) if set_hatch_color: self._hatch_color = self._edgecolor self.stale = True def set_edgecolor(self, color): self._original_edgecolor = color self._set_edgecolor(color) def _set_facecolor(self, color): if color is None: color = mpl.rcParams['patch.facecolor'] alpha = self._alpha if self._fill else 0 self._facecolor = colors.to_rgba(color, alpha) self.stale = True def set_facecolor(self, color): self._original_facecolor = color self._set_facecolor(color) def set_color(self, c): self.set_facecolor(c) self.set_edgecolor(c) def set_alpha(self, alpha): super().set_alpha(alpha) self._set_facecolor(self._original_facecolor) self._set_edgecolor(self._original_edgecolor) def set_linewidth(self, w): if w is None: w = mpl.rcParams['patch.linewidth'] self._linewidth = float(w) self._dash_pattern = mlines._scale_dashes(*self._unscaled_dash_pattern, w) self.stale = True def set_linestyle(self, ls): if ls is None: ls = 'solid' if ls in [' ', '', 'none']: ls = 'None' self._linestyle = ls self._unscaled_dash_pattern = mlines._get_dash_pattern(ls) self._dash_pattern = mlines._scale_dashes(*self._unscaled_dash_pattern, self._linewidth) self.stale = True def set_fill(self, b): self._fill = bool(b) self._set_facecolor(self._original_facecolor) self._set_edgecolor(self._original_edgecolor) self.stale = True def get_fill(self): return self._fill fill = property(get_fill, set_fill) @_docstring.interpd def set_capstyle(self, s): cs = CapStyle(s) self._capstyle = cs self.stale = True def get_capstyle(self): return self._capstyle.name @_docstring.interpd def set_joinstyle(self, s): js = JoinStyle(s) self._joinstyle = js self.stale = True def get_joinstyle(self): return self._joinstyle.name def set_hatch(self, hatch): mhatch._validate_hatch_pattern(hatch) self._hatch = hatch self.stale = True def get_hatch(self): return self._hatch def _draw_paths_with_artist_properties(self, renderer, draw_path_args_list): renderer.open_group('patch', self.get_gid()) gc = renderer.new_gc() gc.set_foreground(self._edgecolor, isRGBA=True) lw = self._linewidth if self._edgecolor[3] == 0 or self._linestyle == 'None': lw = 0 gc.set_linewidth(lw) gc.set_dashes(*self._dash_pattern) gc.set_capstyle(self._capstyle) gc.set_joinstyle(self._joinstyle) gc.set_antialiased(self._antialiased) self._set_gc_clip(gc) gc.set_url(self._url) gc.set_snap(self.get_snap()) gc.set_alpha(self._alpha) if self._hatch: gc.set_hatch(self._hatch) gc.set_hatch_color(self._hatch_color) if self.get_sketch_params() is not None: gc.set_sketch_params(*self.get_sketch_params()) if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer) for draw_path_args in draw_path_args_list: renderer.draw_path(gc, *draw_path_args) gc.restore() renderer.close_group('patch') self.stale = False @artist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return path = self.get_path() transform = self.get_transform() tpath = transform.transform_path_non_affine(path) affine = transform.get_affine() self._draw_paths_with_artist_properties(renderer, [(tpath, affine, self._facecolor if self._facecolor[3] else None)]) def get_path(self): raise NotImplementedError('Derived must override') def get_window_extent(self, renderer=None): return self.get_path().get_extents(self.get_transform()) def _convert_xy_units(self, xy): x = self.convert_xunits(xy[0]) y = self.convert_yunits(xy[1]) return (x, y) class Shadow(Patch): def __str__(self): return f'Shadow({self.patch})' @_docstring.dedent_interpd def __init__(self, patch, ox, oy, *, shade=0.7, **kwargs): super().__init__() self.patch = patch (self._ox, self._oy) = (ox, oy) self._shadow_transform = transforms.Affine2D() self.update_from(self.patch) if not 0 <= shade <= 1: raise ValueError('shade must be between 0 and 1.') color = (1 - shade) * np.asarray(colors.to_rgb(self.patch.get_facecolor())) self.update({'facecolor': color, 'edgecolor': color, 'alpha': 0.5, 'zorder': np.nextafter(self.patch.zorder, -np.inf), **kwargs}) def _update_transform(self, renderer): ox = renderer.points_to_pixels(self._ox) oy = renderer.points_to_pixels(self._oy) self._shadow_transform.clear().translate(ox, oy) def get_path(self): return self.patch.get_path() def get_patch_transform(self): return self.patch.get_patch_transform() + self._shadow_transform def draw(self, renderer): self._update_transform(renderer) super().draw(renderer) class Rectangle(Patch): def __str__(self): pars = (self._x0, self._y0, self._width, self._height, self.angle) fmt = 'Rectangle(xy=(%g, %g), width=%g, height=%g, angle=%g)' return fmt % pars @_docstring.dedent_interpd def __init__(self, xy, width, height, *, angle=0.0, rotation_point='xy', **kwargs): super().__init__(**kwargs) self._x0 = xy[0] self._y0 = xy[1] self._width = width self._height = height self.angle = float(angle) self.rotation_point = rotation_point self._aspect_ratio_correction = 1.0 self._convert_units() def get_path(self): return Path.unit_rectangle() def _convert_units(self): x0 = self.convert_xunits(self._x0) y0 = self.convert_yunits(self._y0) x1 = self.convert_xunits(self._x0 + self._width) y1 = self.convert_yunits(self._y0 + self._height) return (x0, y0, x1, y1) def get_patch_transform(self): bbox = self.get_bbox() if self.rotation_point == 'center': (width, height) = (bbox.x1 - bbox.x0, bbox.y1 - bbox.y0) rotation_point = (bbox.x0 + width / 2.0, bbox.y0 + height / 2.0) elif self.rotation_point == 'xy': rotation_point = (bbox.x0, bbox.y0) else: rotation_point = self.rotation_point return transforms.BboxTransformTo(bbox) + transforms.Affine2D().translate(-rotation_point[0], -rotation_point[1]).scale(1, self._aspect_ratio_correction).rotate_deg(self.angle).scale(1, 1 / self._aspect_ratio_correction).translate(*rotation_point) @property def rotation_point(self): return self._rotation_point @rotation_point.setter def rotation_point(self, value): if value in ['center', 'xy'] or (isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], Real) and isinstance(value[1], Real)): self._rotation_point = value else: raise ValueError("`rotation_point` must be one of {'xy', 'center', (number, number)}.") def get_x(self): return self._x0 def get_y(self): return self._y0 def get_xy(self): return (self._x0, self._y0) def get_corners(self): return self.get_patch_transform().transform([(0, 0), (1, 0), (1, 1), (0, 1)]) def get_center(self): return self.get_patch_transform().transform((0.5, 0.5)) def get_width(self): return self._width def get_height(self): return self._height def get_angle(self): return self.angle def set_x(self, x): self._x0 = x self.stale = True def set_y(self, y): self._y0 = y self.stale = True def set_angle(self, angle): self.angle = angle self.stale = True def set_xy(self, xy): (self._x0, self._y0) = xy self.stale = True def set_width(self, w): self._width = w self.stale = True def set_height(self, h): self._height = h self.stale = True def set_bounds(self, *args): if len(args) == 1: (l, b, w, h) = args[0] else: (l, b, w, h) = args self._x0 = l self._y0 = b self._width = w self._height = h self.stale = True def get_bbox(self): return transforms.Bbox.from_extents(*self._convert_units()) xy = property(get_xy, set_xy) class RegularPolygon(Patch): def __str__(self): s = 'RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)' return s % (self.xy[0], self.xy[1], self.numvertices, self.radius, self.orientation) @_docstring.dedent_interpd def __init__(self, xy, numVertices, *, radius=5, orientation=0, **kwargs): self.xy = xy self.numvertices = numVertices self.orientation = orientation self.radius = radius self._path = Path.unit_regular_polygon(numVertices) self._patch_transform = transforms.Affine2D() super().__init__(**kwargs) def get_path(self): return self._path def get_patch_transform(self): return self._patch_transform.clear().scale(self.radius).rotate(self.orientation).translate(*self.xy) class PathPatch(Patch): _edge_default = True def __str__(self): s = 'PathPatch%d((%g, %g) ...)' return s % (len(self._path.vertices), *tuple(self._path.vertices[0])) @_docstring.dedent_interpd def __init__(self, path, **kwargs): super().__init__(**kwargs) self._path = path def get_path(self): return self._path def set_path(self, path): self._path = path class StepPatch(PathPatch): _edge_default = False @_docstring.dedent_interpd def __init__(self, values, edges, *, orientation='vertical', baseline=0, **kwargs): self.orientation = orientation self._edges = np.asarray(edges) self._values = np.asarray(values) self._baseline = np.asarray(baseline) if baseline is not None else None self._update_path() super().__init__(self._path, **kwargs) def _update_path(self): if np.isnan(np.sum(self._edges)): raise ValueError('Nan values in "edges" are disallowed') if self._edges.size - 1 != self._values.size: raise ValueError(f'Size mismatch between "values" and "edges". Expected `len(values) + 1 == len(edges)`, but `len(values) = {self._values.size}` and `len(edges) = {self._edges.size}`.') (verts, codes) = ([np.empty((0, 2))], [np.empty(0, dtype=Path.code_type)]) _nan_mask = np.isnan(self._values) if self._baseline is not None: _nan_mask |= np.isnan(self._baseline) for (idx0, idx1) in cbook.contiguous_regions(~_nan_mask): x = np.repeat(self._edges[idx0:idx1 + 1], 2) y = np.repeat(self._values[idx0:idx1], 2) if self._baseline is None: y = np.concatenate([y[:1], y, y[-1:]]) elif self._baseline.ndim == 0: y = np.concatenate([[self._baseline], y, [self._baseline]]) elif self._baseline.ndim == 1: base = np.repeat(self._baseline[idx0:idx1], 2)[::-1] x = np.concatenate([x, x[::-1]]) y = np.concatenate([base[-1:], y, base[:1], base[:1], base, base[-1:]]) else: raise ValueError('Invalid `baseline` specified') if self.orientation == 'vertical': xy = np.column_stack([x, y]) else: xy = np.column_stack([y, x]) verts.append(xy) codes.append([Path.MOVETO] + [Path.LINETO] * (len(xy) - 1)) self._path = Path(np.concatenate(verts), np.concatenate(codes)) def get_data(self): StairData = namedtuple('StairData', 'values edges baseline') return StairData(self._values, self._edges, self._baseline) def set_data(self, values=None, edges=None, baseline=None): if values is None and edges is None and (baseline is None): raise ValueError('Must set *values*, *edges* or *baseline*.') if values is not None: self._values = np.asarray(values) if edges is not None: self._edges = np.asarray(edges) if baseline is not None: self._baseline = np.asarray(baseline) self._update_path() self.stale = True class Polygon(Patch): def __str__(self): if len(self._path.vertices): s = 'Polygon%d((%g, %g) ...)' return s % (len(self._path.vertices), *self._path.vertices[0]) else: return 'Polygon0()' @_docstring.dedent_interpd def __init__(self, xy, *, closed=True, **kwargs): super().__init__(**kwargs) self._closed = closed self.set_xy(xy) def get_path(self): return self._path def get_closed(self): return self._closed def set_closed(self, closed): if self._closed == bool(closed): return self._closed = bool(closed) self.set_xy(self.get_xy()) self.stale = True def get_xy(self): return self._path.vertices def set_xy(self, xy): xy = np.asarray(xy) (nverts, _) = xy.shape if self._closed: if nverts == 1 or (nverts > 1 and (xy[0] != xy[-1]).any()): xy = np.concatenate([xy, [xy[0]]]) elif nverts > 2 and (xy[0] == xy[-1]).all(): xy = xy[:-1] self._path = Path(xy, closed=self._closed) self.stale = True xy = property(get_xy, set_xy, doc='The vertices of the path as a (N, 2) array.') class Wedge(Patch): def __str__(self): pars = (self.center[0], self.center[1], self.r, self.theta1, self.theta2, self.width) fmt = 'Wedge(center=(%g, %g), r=%g, theta1=%g, theta2=%g, width=%s)' return fmt % pars @_docstring.dedent_interpd def __init__(self, center, r, theta1, theta2, *, width=None, **kwargs): super().__init__(**kwargs) self.center = center (self.r, self.width) = (r, width) (self.theta1, self.theta2) = (theta1, theta2) self._patch_transform = transforms.IdentityTransform() self._recompute_path() def _recompute_path(self): if abs(self.theta2 - self.theta1 - 360) <= 1e-12: (theta1, theta2) = (0, 360) connector = Path.MOVETO else: (theta1, theta2) = (self.theta1, self.theta2) connector = Path.LINETO arc = Path.arc(theta1, theta2) if self.width is not None: v1 = arc.vertices v2 = arc.vertices[::-1] * (self.r - self.width) / self.r v = np.concatenate([v1, v2, [(0, 0)]]) c = [*arc.codes, connector, *arc.codes[1:], Path.CLOSEPOLY] else: v = np.concatenate([arc.vertices, [(0, 0), (0, 0)]]) c = [*arc.codes, connector, Path.CLOSEPOLY] self._path = Path(v * self.r + self.center, c) def set_center(self, center): self._path = None self.center = center self.stale = True def set_radius(self, radius): self._path = None self.r = radius self.stale = True def set_theta1(self, theta1): self._path = None self.theta1 = theta1 self.stale = True def set_theta2(self, theta2): self._path = None self.theta2 = theta2 self.stale = True def set_width(self, width): self._path = None self.width = width self.stale = True def get_path(self): if self._path is None: self._recompute_path() return self._path class Arrow(Patch): def __str__(self): return 'Arrow()' _path = Path._create_closed([[0.0, 0.1], [0.0, -0.1], [0.8, -0.1], [0.8, -0.3], [1.0, 0.0], [0.8, 0.3], [0.8, 0.1]]) @_docstring.dedent_interpd def __init__(self, x, y, dx, dy, *, width=1.0, **kwargs): super().__init__(**kwargs) self.set_data(x, y, dx, dy, width) def get_path(self): return self._path def get_patch_transform(self): return self._patch_transform def set_data(self, x=None, y=None, dx=None, dy=None, width=None): if x is not None: self._x = x if y is not None: self._y = y if dx is not None: self._dx = dx if dy is not None: self._dy = dy if width is not None: self._width = width self._patch_transform = transforms.Affine2D().scale(np.hypot(self._dx, self._dy), self._width).rotate(np.arctan2(self._dy, self._dx)).translate(self._x, self._y).frozen() class FancyArrow(Polygon): _edge_default = True def __str__(self): return 'FancyArrow()' @_docstring.dedent_interpd def __init__(self, x, y, dx, dy, *, width=0.001, length_includes_head=False, head_width=None, head_length=None, shape='full', overhang=0, head_starts_at_zero=False, **kwargs): self._x = x self._y = y self._dx = dx self._dy = dy self._width = width self._length_includes_head = length_includes_head self._head_width = head_width self._head_length = head_length self._shape = shape self._overhang = overhang self._head_starts_at_zero = head_starts_at_zero self._make_verts() super().__init__(self.verts, closed=True, **kwargs) def set_data(self, *, x=None, y=None, dx=None, dy=None, width=None, head_width=None, head_length=None): if x is not None: self._x = x if y is not None: self._y = y if dx is not None: self._dx = dx if dy is not None: self._dy = dy if width is not None: self._width = width if head_width is not None: self._head_width = head_width if head_length is not None: self._head_length = head_length self._make_verts() self.set_xy(self.verts) def _make_verts(self): if self._head_width is None: head_width = 3 * self._width else: head_width = self._head_width if self._head_length is None: head_length = 1.5 * head_width else: head_length = self._head_length distance = np.hypot(self._dx, self._dy) if self._length_includes_head: length = distance else: length = distance + head_length if not length: self.verts = np.empty([0, 2]) else: (hw, hl) = (head_width, head_length) (hs, lw) = (self._overhang, self._width) left_half_arrow = np.array([[0.0, 0.0], [-hl, -hw / 2], [-hl * (1 - hs), -lw / 2], [-length, -lw / 2], [-length, 0]]) if not self._length_includes_head: left_half_arrow += [head_length, 0] if self._head_starts_at_zero: left_half_arrow += [head_length / 2, 0] if self._shape == 'left': coords = left_half_arrow else: right_half_arrow = left_half_arrow * [1, -1] if self._shape == 'right': coords = right_half_arrow elif self._shape == 'full': coords = np.concatenate([left_half_arrow[:-1], right_half_arrow[-2::-1]]) else: raise ValueError(f'Got unknown shape: {self._shape!r}') if distance != 0: cx = self._dx / distance sx = self._dy / distance else: (cx, sx) = (0, 1) M = [[cx, sx], [-sx, cx]] self.verts = np.dot(coords, M) + [self._x + self._dx, self._y + self._dy] _docstring.interpd.update(FancyArrow='\n'.join((inspect.getdoc(FancyArrow.__init__) or '').splitlines()[2:])) class CirclePolygon(RegularPolygon): def __str__(self): s = 'CirclePolygon((%g, %g), radius=%g, resolution=%d)' return s % (self.xy[0], self.xy[1], self.radius, self.numvertices) @_docstring.dedent_interpd def __init__(self, xy, radius=5, *, resolution=20, **kwargs): super().__init__(xy, resolution, radius=radius, orientation=0, **kwargs) class Ellipse(Patch): def __str__(self): pars = (self._center[0], self._center[1], self.width, self.height, self.angle) fmt = 'Ellipse(xy=(%s, %s), width=%s, height=%s, angle=%s)' return fmt % pars @_docstring.dedent_interpd def __init__(self, xy, width, height, *, angle=0, **kwargs): super().__init__(**kwargs) self._center = xy (self._width, self._height) = (width, height) self._angle = angle self._path = Path.unit_circle() self._aspect_ratio_correction = 1.0 self._patch_transform = transforms.IdentityTransform() def _recompute_transform(self): 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 = transforms.Affine2D().scale(width * 0.5, height * 0.5 * self._aspect_ratio_correction).rotate_deg(self.angle).scale(1, 1 / self._aspect_ratio_correction).translate(*center) def get_path(self): return self._path def get_patch_transform(self): self._recompute_transform() return self._patch_transform def set_center(self, xy): self._center = xy self.stale = True def get_center(self): return self._center center = property(get_center, set_center) def set_width(self, width): self._width = width self.stale = True def get_width(self): return self._width width = property(get_width, set_width) def set_height(self, height): self._height = height self.stale = True def get_height(self): return self._height height = property(get_height, set_height) def set_angle(self, angle): self._angle = angle self.stale = True def get_angle(self): return self._angle angle = property(get_angle, set_angle) def get_corners(self): return self.get_patch_transform().transform([(-1, -1), (1, -1), (1, 1), (-1, 1)]) def get_vertices(self): if self.width < self.height: ret = self.get_patch_transform().transform([(0, 1), (0, -1)]) else: ret = self.get_patch_transform().transform([(1, 0), (-1, 0)]) return [tuple(x) for x in ret] def get_co_vertices(self): if self.width < self.height: ret = self.get_patch_transform().transform([(1, 0), (-1, 0)]) else: ret = self.get_patch_transform().transform([(0, 1), (0, -1)]) return [tuple(x) for x in ret] class Annulus(Patch): @_docstring.dedent_interpd def __init__(self, xy, r, width, angle=0.0, **kwargs): super().__init__(**kwargs) self.set_radii(r) self.center = xy self.width = width self.angle = angle self._path = None def __str__(self): if self.a == self.b: r = self.a else: r = (self.a, self.b) return 'Annulus(xy=(%s, %s), r=%s, width=%s, angle=%s)' % (*self.center, r, self.width, self.angle) def set_center(self, xy): self._center = xy self._path = None self.stale = True def get_center(self): return self._center center = property(get_center, set_center) def set_width(self, width): if width > min(self.a, self.b): raise ValueError('Width of annulus must be less than or equal to semi-minor axis') self._width = width self._path = None self.stale = True def get_width(self): return self._width width = property(get_width, set_width) def set_angle(self, angle): self._angle = angle self._path = None self.stale = True def get_angle(self): return self._angle angle = property(get_angle, set_angle) def set_semimajor(self, a): self.a = float(a) self._path = None self.stale = True def set_semiminor(self, b): self.b = float(b) self._path = None self.stale = True def set_radii(self, r): if np.shape(r) == (2,): (self.a, self.b) = r elif np.shape(r) == (): self.a = self.b = float(r) else: raise ValueError("Parameter 'r' must be one or two floats.") self._path = None self.stale = True def get_radii(self): return (self.a, self.b) radii = property(get_radii, set_radii) def _transform_verts(self, verts, a, b): return transforms.Affine2D().scale(*self._convert_xy_units((a, b))).rotate_deg(self.angle).translate(*self._convert_xy_units(self.center)).transform(verts) def _recompute_path(self): arc = Path.arc(0, 360) (a, b, w) = (self.a, self.b, self.width) v1 = self._transform_verts(arc.vertices, a, b) v2 = self._transform_verts(arc.vertices[::-1], a - w, b - w) v = np.vstack([v1, v2, v1[0, :], (0, 0)]) c = np.hstack([arc.codes, Path.MOVETO, arc.codes[1:], Path.MOVETO, Path.CLOSEPOLY]) self._path = Path(v, c) def get_path(self): if self._path is None: self._recompute_path() return self._path class Circle(Ellipse): def __str__(self): pars = (self.center[0], self.center[1], self.radius) fmt = 'Circle(xy=(%g, %g), radius=%g)' return fmt % pars @_docstring.dedent_interpd def __init__(self, xy, radius=5, **kwargs): super().__init__(xy, radius * 2, radius * 2, **kwargs) self.radius = radius def set_radius(self, radius): self.width = self.height = 2 * radius self.stale = True def get_radius(self): return self.width / 2.0 radius = property(get_radius, set_radius) class Arc(Ellipse): def __str__(self): pars = (self.center[0], self.center[1], self.width, self.height, self.angle, self.theta1, self.theta2) fmt = 'Arc(xy=(%g, %g), width=%g, height=%g, angle=%g, theta1=%g, theta2=%g)' return fmt % pars @_docstring.dedent_interpd def __init__(self, xy, width, height, *, angle=0.0, theta1=0.0, theta2=360.0, **kwargs): fill = kwargs.setdefault('fill', False) if fill: raise ValueError('Arc objects cannot be filled') super().__init__(xy, width, height, angle=angle, **kwargs) self.theta1 = theta1 self.theta2 = theta2 (self._theta1, self._theta2, self._stretched_width, self._stretched_height) = self._theta_stretch() self._path = Path.arc(self._theta1, self._theta2) @artist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return self._recompute_transform() self._update_path() data_to_screen_trans = self.get_data_transform() (pwidth, pheight) = data_to_screen_trans.transform((self._stretched_width, self._stretched_height)) - data_to_screen_trans.transform((0, 0)) inv_error = 1.0 / 1.89818e-06 * 0.5 if pwidth < inv_error and pheight < inv_error: return Patch.draw(self, renderer) def line_circle_intersect(x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 dr2 = dx * dx + dy * dy D = x0 * y1 - x1 * y0 D2 = D * D discrim = dr2 - D2 if discrim >= 0.0: sign_dy = np.copysign(1, dy) sqrt_discrim = np.sqrt(discrim) return np.array([[(D * dy + sign_dy * dx * sqrt_discrim) / dr2, (-D * dx + abs(dy) * sqrt_discrim) / dr2], [(D * dy - sign_dy * dx * sqrt_discrim) / dr2, (-D * dx - abs(dy) * sqrt_discrim) / dr2]]) else: return np.empty((0, 2)) def segment_circle_intersect(x0, y0, x1, y1): epsilon = 1e-09 if x1 < x0: (x0e, x1e) = (x1, x0) else: (x0e, x1e) = (x0, x1) if y1 < y0: (y0e, y1e) = (y1, y0) else: (y0e, y1e) = (y0, y1) xys = line_circle_intersect(x0, y0, x1, y1) (xs, ys) = xys.T return xys[(x0e - epsilon < xs) & (xs < x1e + epsilon) & (y0e - epsilon < ys) & (ys < y1e + epsilon)] box_path_transform = transforms.BboxTransformTo((self.axes or self.get_figure(root=False)).bbox) - self.get_transform() box_path = Path.unit_rectangle().transformed(box_path_transform) thetas = set() for (p0, p1) in zip(box_path.vertices[:-1], box_path.vertices[1:]): xy = segment_circle_intersect(*p0, *p1) (x, y) = xy.T theta = (np.rad2deg(np.arctan2(y, x)) + 360) % 360 thetas.update(theta[(self._theta1 < theta) & (theta < self._theta2)]) thetas = sorted(thetas) + [self._theta2] last_theta = self._theta1 theta1_rad = np.deg2rad(self._theta1) inside = box_path.contains_point((np.cos(theta1_rad), np.sin(theta1_rad))) path_original = self._path for theta in thetas: if inside: self._path = Path.arc(last_theta, theta, 8) Patch.draw(self, renderer) inside = False else: inside = True last_theta = theta self._path = path_original def _update_path(self): stretched = self._theta_stretch() if any((a != b for (a, b) in zip(stretched, (self._theta1, self._theta2, self._stretched_width, self._stretched_height)))): (self._theta1, self._theta2, self._stretched_width, self._stretched_height) = stretched self._path = Path.arc(self._theta1, self._theta2) def _theta_stretch(self): def theta_stretch(theta, scale): theta = np.deg2rad(theta) x = np.cos(theta) y = np.sin(theta) stheta = np.rad2deg(np.arctan2(scale * y, x)) return (stheta + 360) % 360 width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) if width != height and (not (self.theta1 != self.theta2 and self.theta1 % 360 == self.theta2 % 360)): theta1 = theta_stretch(self.theta1, width / height) theta2 = theta_stretch(self.theta2, width / height) return (theta1, theta2, width, height) return (self.theta1, self.theta2, width, height) def bbox_artist(artist, renderer, props=None, fill=True): if props is None: props = {} props = props.copy() pad = props.pop('pad', 4) pad = renderer.points_to_pixels(pad) bbox = artist.get_window_extent(renderer) r = Rectangle(xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2), width=bbox.width + pad, height=bbox.height + pad, fill=fill, transform=transforms.IdentityTransform(), clip_on=False) r.update(props) r.draw(renderer) def draw_bbox(bbox, renderer, color='k', trans=None): r = Rectangle(xy=bbox.p0, width=bbox.width, height=bbox.height, edgecolor=color, fill=False, clip_on=False) if trans is not None: r.set_transform(trans) r.draw(renderer) class _Style: def __init_subclass__(cls): _docstring.interpd.update({f'{cls.__name__}:table': cls.pprint_styles(), f'{cls.__name__}:table_and_accepts': cls.pprint_styles() + '\n\n .. ACCEPTS: [' + '|'.join(map(" '{}' ".format, cls._style_list)) + ']'}) def __new__(cls, stylename, **kwargs): _list = stylename.replace(' ', '').split(',') _name = _list[0].lower() try: _cls = cls._style_list[_name] except KeyError as err: raise ValueError(f'Unknown style: {stylename!r}') from err try: _args_pair = [cs.split('=') for cs in _list[1:]] _args = {k: float(v) for (k, v) in _args_pair} except ValueError as err: raise ValueError(f'Incorrect style argument: {stylename!r}') from err return _cls(**{**_args, **kwargs}) @classmethod def get_styles(cls): return cls._style_list @classmethod def pprint_styles(cls): table = [('Class', 'Name', 'Attrs'), *[(cls.__name__, f'``{name}``', str(inspect.signature(cls))[1:-1] or 'None') for (name, cls) in cls._style_list.items()]] col_len = [max((len(cell) for cell in column)) for column in zip(*table)] table_formatstr = ' '.join(('=' * cl for cl in col_len)) rst_table = '\n'.join(['', table_formatstr, ' '.join((cell.ljust(cl) for (cell, cl) in zip(table[0], col_len))), table_formatstr, *[' '.join((cell.ljust(cl) for (cell, cl) in zip(row, col_len))) for row in table[1:]], table_formatstr]) return textwrap.indent(rst_table, prefix=' ' * 4) @classmethod @_api.deprecated('3.10.0', message='This method is never used internally.', alternative='No replacement. Please open an issue if you use this.') def register(cls, name, style): if not issubclass(style, cls._Base): raise ValueError(f'{style} must be a subclass of {cls._Base}') cls._style_list[name] = style def _register_style(style_list, cls=None, *, name=None): if cls is None: return functools.partial(_register_style, style_list, name=name) style_list[name or cls.__name__.lower()] = cls return cls @_docstring.dedent_interpd class BoxStyle(_Style): _style_list = {} @_register_style(_style_list) class Square: def __init__(self, pad=0.3): self.pad = pad def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad (width, height) = (width + 2 * pad, height + 2 * pad) (x0, y0) = (x0 - pad, y0 - pad) (x1, y1) = (x0 + width, y0 + height) return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) @_register_style(_style_list) class Circle: def __init__(self, pad=0.3): self.pad = pad def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad (width, height) = (width + 2 * pad, height + 2 * pad) (x0, y0) = (x0 - pad, y0 - pad) return Path.circle((x0 + width / 2, y0 + height / 2), max(width, height) / 2) @_register_style(_style_list) class Ellipse: def __init__(self, pad=0.3): self.pad = pad def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad (width, height) = (width + 2 * pad, height + 2 * pad) (x0, y0) = (x0 - pad, y0 - pad) a = width / math.sqrt(2) b = height / math.sqrt(2) trans = Affine2D().scale(a, b).translate(x0 + width / 2, y0 + height / 2) return trans.transform_path(Path.unit_circle()) @_register_style(_style_list) class LArrow: def __init__(self, pad=0.3): self.pad = pad def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad (width, height) = (width + 2 * pad, height + 2 * pad) (x0, y0) = (x0 - pad, y0 - pad) (x1, y1) = (x0 + width, y0 + height) dx = (y1 - y0) / 2 dxx = dx / 2 x0 = x0 + pad / 1.4 return Path._create_closed([(x0 + dxx, y0), (x1, y0), (x1, y1), (x0 + dxx, y1), (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx), (x0 + dxx, y0 - dxx), (x0 + dxx, y0)]) @_register_style(_style_list) class RArrow(LArrow): def __call__(self, x0, y0, width, height, mutation_size): p = BoxStyle.LArrow.__call__(self, x0, y0, width, height, mutation_size) p.vertices[:, 0] = 2 * x0 + width - p.vertices[:, 0] return p @_register_style(_style_list) class DArrow: def __init__(self, pad=0.3): self.pad = pad def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad height = height + 2 * pad (x0, y0) = (x0 - pad, y0 - pad) (x1, y1) = (x0 + width, y0 + height) dx = (y1 - y0) / 2 dxx = dx / 2 x0 = x0 + pad / 1.4 return Path._create_closed([(x0 + dxx, y0), (x1, y0), (x1, y0 - dxx), (x1 + dx + dxx, y0 + dx), (x1, y1 + dxx), (x1, y1), (x0 + dxx, y1), (x0 + dxx, y1 + dxx), (x0 - dx, y0 + dx), (x0 + dxx, y0 - dxx), (x0 + dxx, y0)]) @_register_style(_style_list) class Round: def __init__(self, pad=0.3, rounding_size=None): self.pad = pad self.rounding_size = rounding_size def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad if self.rounding_size: dr = mutation_size * self.rounding_size else: dr = pad (width, height) = (width + 2 * pad, height + 2 * pad) (x0, y0) = (x0 - pad, y0 - pad) (x1, y1) = (x0 + width, y0 + height) cp = [(x0 + dr, y0), (x1 - dr, y0), (x1, y0), (x1, y0 + dr), (x1, y1 - dr), (x1, y1), (x1 - dr, y1), (x0 + dr, y1), (x0, y1), (x0, y1 - dr), (x0, y0 + dr), (x0, y0), (x0 + dr, y0), (x0 + dr, y0)] com = [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY] return Path(cp, com) @_register_style(_style_list) class Round4: def __init__(self, pad=0.3, rounding_size=None): self.pad = pad self.rounding_size = rounding_size def __call__(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad if self.rounding_size: dr = mutation_size * self.rounding_size else: dr = pad / 2.0 width = width + 2 * pad - 2 * dr height = height + 2 * pad - 2 * dr (x0, y0) = (x0 - pad + dr, y0 - pad + dr) (x1, y1) = (x0 + width, y0 + height) cp = [(x0, y0), (x0 + dr, y0 - dr), (x1 - dr, y0 - dr), (x1, y0), (x1 + dr, y0 + dr), (x1 + dr, y1 - dr), (x1, y1), (x1 - dr, y1 + dr), (x0 + dr, y1 + dr), (x0, y1), (x0 - dr, y1 - dr), (x0 - dr, y0 + dr), (x0, y0), (x0, y0)] com = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY] return Path(cp, com) @_register_style(_style_list) class Sawtooth: def __init__(self, pad=0.3, tooth_size=None): self.pad = pad self.tooth_size = tooth_size def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad if self.tooth_size is None: tooth_size = self.pad * 0.5 * mutation_size else: tooth_size = self.tooth_size * mutation_size hsz = tooth_size / 2 width = width + 2 * pad - tooth_size height = height + 2 * pad - tooth_size dsx_n = round((width - tooth_size) / (tooth_size * 2)) * 2 dsy_n = round((height - tooth_size) / (tooth_size * 2)) * 2 (x0, y0) = (x0 - pad + hsz, y0 - pad + hsz) (x1, y1) = (x0 + width, y0 + height) xs = [x0, *np.linspace(x0 + hsz, x1 - hsz, 2 * dsx_n + 1), *([x1, x1 + hsz, x1, x1 - hsz] * dsy_n)[:2 * dsy_n + 2], x1, *np.linspace(x1 - hsz, x0 + hsz, 2 * dsx_n + 1), *([x0, x0 - hsz, x0, x0 + hsz] * dsy_n)[:2 * dsy_n + 2]] ys = [*([y0, y0 - hsz, y0, y0 + hsz] * dsx_n)[:2 * dsx_n + 2], y0, *np.linspace(y0 + hsz, y1 - hsz, 2 * dsy_n + 1), *([y1, y1 + hsz, y1, y1 - hsz] * dsx_n)[:2 * dsx_n + 2], y1, *np.linspace(y1 - hsz, y0 + hsz, 2 * dsy_n + 1)] return [*zip(xs, ys), (xs[0], ys[0])] def __call__(self, x0, y0, width, height, mutation_size): saw_vertices = self._get_sawtooth_vertices(x0, y0, width, height, mutation_size) return Path(saw_vertices, closed=True) @_register_style(_style_list) class Roundtooth(Sawtooth): def __call__(self, x0, y0, width, height, mutation_size): saw_vertices = self._get_sawtooth_vertices(x0, y0, width, height, mutation_size) saw_vertices = np.concatenate([saw_vertices, [saw_vertices[0]]]) codes = [Path.MOVETO] + [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices) - 1) // 2) + [Path.CLOSEPOLY] return Path(saw_vertices, codes) @_docstring.dedent_interpd class ConnectionStyle(_Style): _style_list = {} class _Base: def _in_patch(self, patch): return lambda xy: patch.contains(SimpleNamespace(x=xy[0], y=xy[1]))[0] def _clip(self, path, in_start, in_stop): if in_start: try: (_, path) = split_path_inout(path, in_start) except ValueError: pass if in_stop: try: (path, _) = split_path_inout(path, in_stop) except ValueError: pass return path def __call__(self, posA, posB, shrinkA=2.0, shrinkB=2.0, patchA=None, patchB=None): path = self.connect(posA, posB) path = self._clip(path, self._in_patch(patchA) if patchA else None, self._in_patch(patchB) if patchB else None) path = self._clip(path, inside_circle(*path.vertices[0], shrinkA) if shrinkA else None, inside_circle(*path.vertices[-1], shrinkB) if shrinkB else None) return path @_register_style(_style_list) class Arc3(_Base): def __init__(self, rad=0.0): self.rad = rad def connect(self, posA, posB): (x1, y1) = posA (x2, y2) = posB (x12, y12) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0) (dx, dy) = (x2 - x1, y2 - y1) f = self.rad (cx, cy) = (x12 + f * dy, y12 - f * dx) vertices = [(x1, y1), (cx, cy), (x2, y2)] codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] return Path(vertices, codes) @_register_style(_style_list) class Angle3(_Base): def __init__(self, angleA=90, angleB=0): self.angleA = angleA self.angleB = angleB def connect(self, posA, posB): (x1, y1) = posA (x2, y2) = posB cosA = math.cos(math.radians(self.angleA)) sinA = math.sin(math.radians(self.angleA)) cosB = math.cos(math.radians(self.angleB)) sinB = math.sin(math.radians(self.angleB)) (cx, cy) = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) vertices = [(x1, y1), (cx, cy), (x2, y2)] codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3] return Path(vertices, codes) @_register_style(_style_list) class Angle(_Base): def __init__(self, angleA=90, angleB=0, rad=0.0): self.angleA = angleA self.angleB = angleB self.rad = rad def connect(self, posA, posB): (x1, y1) = posA (x2, y2) = posB cosA = math.cos(math.radians(self.angleA)) sinA = math.sin(math.radians(self.angleA)) cosB = math.cos(math.radians(self.angleB)) sinB = math.sin(math.radians(self.angleB)) (cx, cy) = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) vertices = [(x1, y1)] codes = [Path.MOVETO] if self.rad == 0.0: vertices.append((cx, cy)) codes.append(Path.LINETO) else: (dx1, dy1) = (x1 - cx, y1 - cy) d1 = np.hypot(dx1, dy1) f1 = self.rad / d1 (dx2, dy2) = (x2 - cx, y2 - cy) d2 = np.hypot(dx2, dy2) f2 = self.rad / d2 vertices.extend([(cx + dx1 * f1, cy + dy1 * f1), (cx, cy), (cx + dx2 * f2, cy + dy2 * f2)]) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) vertices.append((x2, y2)) codes.append(Path.LINETO) return Path(vertices, codes) @_register_style(_style_list) class Arc(_Base): def __init__(self, angleA=0, angleB=0, armA=None, armB=None, rad=0.0): self.angleA = angleA self.angleB = angleB self.armA = armA self.armB = armB self.rad = rad def connect(self, posA, posB): (x1, y1) = posA (x2, y2) = posB vertices = [(x1, y1)] rounded = [] codes = [Path.MOVETO] if self.armA: cosA = math.cos(math.radians(self.angleA)) sinA = math.sin(math.radians(self.angleA)) d = self.armA - self.rad rounded.append((x1 + d * cosA, y1 + d * sinA)) d = self.armA rounded.append((x1 + d * cosA, y1 + d * sinA)) if self.armB: cosB = math.cos(math.radians(self.angleB)) sinB = math.sin(math.radians(self.angleB)) (x_armB, y_armB) = (x2 + self.armB * cosB, y2 + self.armB * sinB) if rounded: (xp, yp) = rounded[-1] (dx, dy) = (x_armB - xp, y_armB - yp) dd = (dx * dx + dy * dy) ** 0.5 rounded.append((xp + self.rad * dx / dd, yp + self.rad * dy / dd)) vertices.extend(rounded) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) else: (xp, yp) = vertices[-1] (dx, dy) = (x_armB - xp, y_armB - yp) dd = (dx * dx + dy * dy) ** 0.5 d = dd - self.rad rounded = [(xp + d * dx / dd, yp + d * dy / dd), (x_armB, y_armB)] if rounded: (xp, yp) = rounded[-1] (dx, dy) = (x2 - xp, y2 - yp) dd = (dx * dx + dy * dy) ** 0.5 rounded.append((xp + self.rad * dx / dd, yp + self.rad * dy / dd)) vertices.extend(rounded) codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3]) vertices.append((x2, y2)) codes.append(Path.LINETO) return Path(vertices, codes) @_register_style(_style_list) class Bar(_Base): def __init__(self, armA=0.0, armB=0.0, fraction=0.3, angle=None): self.armA = armA self.armB = armB self.fraction = fraction self.angle = angle def connect(self, posA, posB): (x1, y1) = posA (x20, y20) = (x2, y2) = posB theta1 = math.atan2(y2 - y1, x2 - x1) (dx, dy) = (x2 - x1, y2 - y1) dd = (dx * dx + dy * dy) ** 0.5 (ddx, ddy) = (dx / dd, dy / dd) (armA, armB) = (self.armA, self.armB) if self.angle is not None: theta0 = np.deg2rad(self.angle) dtheta = theta1 - theta0 dl = dd * math.sin(dtheta) dL = dd * math.cos(dtheta) (x2, y2) = (x1 + dL * math.cos(theta0), y1 + dL * math.sin(theta0)) armB = armB - dl (dx, dy) = (x2 - x1, y2 - y1) dd2 = (dx * dx + dy * dy) ** 0.5 (ddx, ddy) = (dx / dd2, dy / dd2) arm = max(armA, armB) f = self.fraction * dd + arm (cx1, cy1) = (x1 + f * ddy, y1 - f * ddx) (cx2, cy2) = (x2 + f * ddy, y2 - f * ddx) vertices = [(x1, y1), (cx1, cy1), (cx2, cy2), (x20, y20)] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO] return Path(vertices, codes) def _point_along_a_line(x0, y0, x1, y1, d): (dx, dy) = (x0 - x1, y0 - y1) ff = d / (dx * dx + dy * dy) ** 0.5 (x2, y2) = (x0 - ff * dx, y0 - ff * dy) return (x2, y2) @_docstring.dedent_interpd class ArrowStyle(_Style): _style_list = {} class _Base: @staticmethod def ensure_quadratic_bezier(path): segments = list(path.iter_segments()) if len(segments) != 2 or segments[0][1] != Path.MOVETO or segments[1][1] != Path.CURVE3: raise ValueError("'path' is not a valid quadratic Bezier curve") return [*segments[0][0], *segments[1][0]] def transmute(self, path, mutation_size, linewidth): raise NotImplementedError('Derived must override') def __call__(self, path, mutation_size, linewidth, aspect_ratio=1.0): if aspect_ratio is not None: vertices = path.vertices / [1, aspect_ratio] path_shrunk = Path(vertices, path.codes) (path_mutated, fillable) = self.transmute(path_shrunk, mutation_size, linewidth) if np.iterable(fillable): path_list = [Path(p.vertices * [1, aspect_ratio], p.codes) for p in path_mutated] return (path_list, fillable) else: return (path_mutated, fillable) else: return self.transmute(path, mutation_size, linewidth) class _Curve(_Base): arrow = '-' fillbegin = fillend = False def __init__(self, head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None): (self.head_length, self.head_width) = (head_length, head_width) (self.widthA, self.widthB) = (widthA, widthB) (self.lengthA, self.lengthB) = (lengthA, lengthB) (self.angleA, self.angleB) = (angleA, angleB) (self.scaleA, self.scaleB) = (scaleA, scaleB) self._beginarrow_head = False self._beginarrow_bracket = False self._endarrow_head = False self._endarrow_bracket = False if '-' not in self.arrow: raise ValueError("arrow must have the '-' between the two heads") (beginarrow, endarrow) = self.arrow.split('-', 1) if beginarrow == '<': self._beginarrow_head = True self._beginarrow_bracket = False elif beginarrow == '<|': self._beginarrow_head = True self._beginarrow_bracket = False self.fillbegin = True elif beginarrow in (']', '|'): self._beginarrow_head = False self._beginarrow_bracket = True if endarrow == '>': self._endarrow_head = True self._endarrow_bracket = False elif endarrow == '|>': self._endarrow_head = True self._endarrow_bracket = False self.fillend = True elif endarrow in ('[', '|'): self._endarrow_head = False self._endarrow_bracket = True super().__init__() def _get_arrow_wedge(self, x0, y0, x1, y1, head_dist, cos_t, sin_t, linewidth): (dx, dy) = (x0 - x1, y0 - y1) cp_distance = np.hypot(dx, dy) pad_projected = 0.5 * linewidth / sin_t if cp_distance == 0: cp_distance = 1 ddx = pad_projected * dx / cp_distance ddy = pad_projected * dy / cp_distance dx = dx / cp_distance * head_dist dy = dy / cp_distance * head_dist (dx1, dy1) = (cos_t * dx + sin_t * dy, -sin_t * dx + cos_t * dy) (dx2, dy2) = (cos_t * dx - sin_t * dy, sin_t * dx + cos_t * dy) vertices_arrow = [(x1 + ddx + dx1, y1 + ddy + dy1), (x1 + ddx, y1 + ddy), (x1 + ddx + dx2, y1 + ddy + dy2)] codes_arrow = [Path.MOVETO, Path.LINETO, Path.LINETO] return (vertices_arrow, codes_arrow, ddx, ddy) def _get_bracket(self, x0, y0, x1, y1, width, length, angle): (cos_t, sin_t) = get_cos_sin(x1, y1, x0, y0) from matplotlib.bezier import get_normal_points (x1, y1, x2, y2) = get_normal_points(x0, y0, cos_t, sin_t, width) (dx, dy) = (length * cos_t, length * sin_t) vertices_arrow = [(x1 + dx, y1 + dy), (x1, y1), (x2, y2), (x2 + dx, y2 + dy)] codes_arrow = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO] if angle: trans = transforms.Affine2D().rotate_deg_around(x0, y0, angle) vertices_arrow = trans.transform(vertices_arrow) return (vertices_arrow, codes_arrow) def transmute(self, path, mutation_size, linewidth): if self._beginarrow_head or self._endarrow_head: head_length = self.head_length * mutation_size head_width = self.head_width * mutation_size head_dist = np.hypot(head_length, head_width) (cos_t, sin_t) = (head_length / head_dist, head_width / head_dist) scaleA = mutation_size if self.scaleA is None else self.scaleA scaleB = mutation_size if self.scaleB is None else self.scaleB (x0, y0) = path.vertices[0] (x1, y1) = path.vertices[1] has_begin_arrow = self._beginarrow_head and (x0, y0) != (x1, y1) (verticesA, codesA, ddxA, ddyA) = self._get_arrow_wedge(x1, y1, x0, y0, head_dist, cos_t, sin_t, linewidth) if has_begin_arrow else ([], [], 0, 0) (x2, y2) = path.vertices[-2] (x3, y3) = path.vertices[-1] has_end_arrow = self._endarrow_head and (x2, y2) != (x3, y3) (verticesB, codesB, ddxB, ddyB) = self._get_arrow_wedge(x2, y2, x3, y3, head_dist, cos_t, sin_t, linewidth) if has_end_arrow else ([], [], 0, 0) paths = [Path(np.concatenate([[(x0 + ddxA, y0 + ddyA)], path.vertices[1:-1], [(x3 + ddxB, y3 + ddyB)]]), path.codes)] fills = [False] if has_begin_arrow: if self.fillbegin: paths.append(Path([*verticesA, (0, 0)], [*codesA, Path.CLOSEPOLY])) fills.append(True) else: paths.append(Path(verticesA, codesA)) fills.append(False) elif self._beginarrow_bracket: (x0, y0) = path.vertices[0] (x1, y1) = path.vertices[1] (verticesA, codesA) = self._get_bracket(x0, y0, x1, y1, self.widthA * scaleA, self.lengthA * scaleA, self.angleA) paths.append(Path(verticesA, codesA)) fills.append(False) if has_end_arrow: if self.fillend: fills.append(True) paths.append(Path([*verticesB, (0, 0)], [*codesB, Path.CLOSEPOLY])) else: fills.append(False) paths.append(Path(verticesB, codesB)) elif self._endarrow_bracket: (x0, y0) = path.vertices[-1] (x1, y1) = path.vertices[-2] (verticesB, codesB) = self._get_bracket(x0, y0, x1, y1, self.widthB * scaleB, self.lengthB * scaleB, self.angleB) paths.append(Path(verticesB, codesB)) fills.append(False) return (paths, fills) @_register_style(_style_list, name='-') class Curve(_Curve): def __init__(self): super().__init__(head_length=0.2, head_width=0.1) @_register_style(_style_list, name='<-') class CurveA(_Curve): arrow = '<-' @_register_style(_style_list, name='->') class CurveB(_Curve): arrow = '->' @_register_style(_style_list, name='<->') class CurveAB(_Curve): arrow = '<->' @_register_style(_style_list, name='<|-') class CurveFilledA(_Curve): arrow = '<|-' @_register_style(_style_list, name='-|>') class CurveFilledB(_Curve): arrow = '-|>' @_register_style(_style_list, name='<|-|>') class CurveFilledAB(_Curve): arrow = '<|-|>' @_register_style(_style_list, name=']-') class BracketA(_Curve): arrow = ']-' def __init__(self, widthA=1.0, lengthA=0.2, angleA=0): super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA) @_register_style(_style_list, name='-[') class BracketB(_Curve): arrow = '-[' def __init__(self, widthB=1.0, lengthB=0.2, angleB=0): super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB) @_register_style(_style_list, name=']-[') class BracketAB(_Curve): arrow = ']-[' def __init__(self, widthA=1.0, lengthA=0.2, angleA=0, widthB=1.0, lengthB=0.2, angleB=0): super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA, widthB=widthB, lengthB=lengthB, angleB=angleB) @_register_style(_style_list, name='|-|') class BarAB(_Curve): arrow = '|-|' def __init__(self, widthA=1.0, angleA=0, widthB=1.0, angleB=0): super().__init__(widthA=widthA, lengthA=0, angleA=angleA, widthB=widthB, lengthB=0, angleB=angleB) @_register_style(_style_list, name=']->') class BracketCurve(_Curve): arrow = ']->' def __init__(self, widthA=1.0, lengthA=0.2, angleA=None): super().__init__(widthA=widthA, lengthA=lengthA, angleA=angleA) @_register_style(_style_list, name='<-[') class CurveBracket(_Curve): arrow = '<-[' def __init__(self, widthB=1.0, lengthB=0.2, angleB=None): super().__init__(widthB=widthB, lengthB=lengthB, angleB=angleB) @_register_style(_style_list) class Simple(_Base): def __init__(self, head_length=0.5, head_width=0.5, tail_width=0.2): (self.head_length, self.head_width, self.tail_width) = (head_length, head_width, tail_width) super().__init__() def transmute(self, path, mutation_size, linewidth): (x0, y0, x1, y1, x2, y2) = self.ensure_quadratic_bezier(path) head_length = self.head_length * mutation_size in_f = inside_circle(x2, y2, head_length) arrow_path = [(x0, y0), (x1, y1), (x2, y2)] try: (arrow_out, arrow_in) = split_bezier_intersecting_with_closedpath(arrow_path, in_f) except NonIntersectingPathException: (x0, y0) = _point_along_a_line(x2, y2, x1, y1, head_length) (x1n, y1n) = (0.5 * (x0 + x2), 0.5 * (y0 + y2)) arrow_in = [(x0, y0), (x1n, y1n), (x2, y2)] arrow_out = None head_width = self.head_width * mutation_size (head_left, head_right) = make_wedged_bezier2(arrow_in, head_width / 2.0, wm=0.5) if arrow_out is not None: tail_width = self.tail_width * mutation_size (tail_left, tail_right) = get_parallels(arrow_out, tail_width / 2.0) patch_path = [(Path.MOVETO, tail_right[0]), (Path.CURVE3, tail_right[1]), (Path.CURVE3, tail_right[2]), (Path.LINETO, head_right[0]), (Path.CURVE3, head_right[1]), (Path.CURVE3, head_right[2]), (Path.CURVE3, head_left[1]), (Path.CURVE3, head_left[0]), (Path.LINETO, tail_left[2]), (Path.CURVE3, tail_left[1]), (Path.CURVE3, tail_left[0]), (Path.LINETO, tail_right[0]), (Path.CLOSEPOLY, tail_right[0])] else: patch_path = [(Path.MOVETO, head_right[0]), (Path.CURVE3, head_right[1]), (Path.CURVE3, head_right[2]), (Path.CURVE3, head_left[1]), (Path.CURVE3, head_left[0]), (Path.CLOSEPOLY, head_left[0])] path = Path([p for (c, p) in patch_path], [c for (c, p) in patch_path]) return (path, True) @_register_style(_style_list) class Fancy(_Base): def __init__(self, head_length=0.4, head_width=0.4, tail_width=0.4): (self.head_length, self.head_width, self.tail_width) = (head_length, head_width, tail_width) super().__init__() def transmute(self, path, mutation_size, linewidth): (x0, y0, x1, y1, x2, y2) = self.ensure_quadratic_bezier(path) head_length = self.head_length * mutation_size arrow_path = [(x0, y0), (x1, y1), (x2, y2)] in_f = inside_circle(x2, y2, head_length) try: (path_out, path_in) = split_bezier_intersecting_with_closedpath(arrow_path, in_f) except NonIntersectingPathException: (x0, y0) = _point_along_a_line(x2, y2, x1, y1, head_length) (x1n, y1n) = (0.5 * (x0 + x2), 0.5 * (y0 + y2)) arrow_path = [(x0, y0), (x1n, y1n), (x2, y2)] path_head = arrow_path else: path_head = path_in in_f = inside_circle(x2, y2, head_length * 0.8) (path_out, path_in) = split_bezier_intersecting_with_closedpath(arrow_path, in_f) path_tail = path_out head_width = self.head_width * mutation_size (head_l, head_r) = make_wedged_bezier2(path_head, head_width / 2.0, wm=0.6) tail_width = self.tail_width * mutation_size (tail_left, tail_right) = make_wedged_bezier2(path_tail, tail_width * 0.5, w1=1.0, wm=0.6, w2=0.3) in_f = inside_circle(x0, y0, tail_width * 0.3) (path_in, path_out) = split_bezier_intersecting_with_closedpath(arrow_path, in_f) tail_start = path_in[-1] (head_right, head_left) = (head_r, head_l) patch_path = [(Path.MOVETO, tail_start), (Path.LINETO, tail_right[0]), (Path.CURVE3, tail_right[1]), (Path.CURVE3, tail_right[2]), (Path.LINETO, head_right[0]), (Path.CURVE3, head_right[1]), (Path.CURVE3, head_right[2]), (Path.CURVE3, head_left[1]), (Path.CURVE3, head_left[0]), (Path.LINETO, tail_left[2]), (Path.CURVE3, tail_left[1]), (Path.CURVE3, tail_left[0]), (Path.LINETO, tail_start), (Path.CLOSEPOLY, tail_start)] path = Path([p for (c, p) in patch_path], [c for (c, p) in patch_path]) return (path, True) @_register_style(_style_list) class Wedge(_Base): def __init__(self, tail_width=0.3, shrink_factor=0.5): self.tail_width = tail_width self.shrink_factor = shrink_factor super().__init__() def transmute(self, path, mutation_size, linewidth): (x0, y0, x1, y1, x2, y2) = self.ensure_quadratic_bezier(path) arrow_path = [(x0, y0), (x1, y1), (x2, y2)] (b_plus, b_minus) = make_wedged_bezier2(arrow_path, self.tail_width * mutation_size / 2.0, wm=self.shrink_factor) patch_path = [(Path.MOVETO, b_plus[0]), (Path.CURVE3, b_plus[1]), (Path.CURVE3, b_plus[2]), (Path.LINETO, b_minus[2]), (Path.CURVE3, b_minus[1]), (Path.CURVE3, b_minus[0]), (Path.CLOSEPOLY, b_minus[0])] path = Path([p for (c, p) in patch_path], [c for (c, p) in patch_path]) return (path, True) class FancyBboxPatch(Patch): _edge_default = True def __str__(self): s = self.__class__.__name__ + '((%g, %g), width=%g, height=%g)' return s % (self._x, self._y, self._width, self._height) @_docstring.dedent_interpd def __init__(self, xy, width, height, boxstyle='round', *, mutation_scale=1, mutation_aspect=1, **kwargs): super().__init__(**kwargs) (self._x, self._y) = xy self._width = width self._height = height self.set_boxstyle(boxstyle) self._mutation_scale = mutation_scale self._mutation_aspect = mutation_aspect self.stale = True @_docstring.dedent_interpd def set_boxstyle(self, boxstyle=None, **kwargs): if boxstyle is None: return BoxStyle.pprint_styles() self._bbox_transmuter = BoxStyle(boxstyle, **kwargs) if isinstance(boxstyle, str) else boxstyle self.stale = True def get_boxstyle(self): return self._bbox_transmuter def set_mutation_scale(self, scale): self._mutation_scale = scale self.stale = True def get_mutation_scale(self): return self._mutation_scale def set_mutation_aspect(self, aspect): self._mutation_aspect = aspect self.stale = True def get_mutation_aspect(self): return self._mutation_aspect if self._mutation_aspect is not None else 1 def get_path(self): boxstyle = self.get_boxstyle() m_aspect = self.get_mutation_aspect() path = boxstyle(self._x, self._y / m_aspect, self._width, self._height / m_aspect, self.get_mutation_scale()) return Path(path.vertices * [1, m_aspect], path.codes) def get_x(self): return self._x def get_y(self): return self._y def get_width(self): return self._width def get_height(self): return self._height def set_x(self, x): self._x = x self.stale = True def set_y(self, y): self._y = y self.stale = True def set_width(self, w): self._width = w self.stale = True def set_height(self, h): self._height = h self.stale = True def set_bounds(self, *args): if len(args) == 1: (l, b, w, h) = args[0] else: (l, b, w, h) = args self._x = l self._y = b self._width = w self._height = h self.stale = True def get_bbox(self): return transforms.Bbox.from_bounds(self._x, self._y, self._width, self._height) class FancyArrowPatch(Patch): _edge_default = True def __str__(self): if self._posA_posB is not None: ((x1, y1), (x2, y2)) = self._posA_posB return f'{type(self).__name__}(({x1:g}, {y1:g})->({x2:g}, {y2:g}))' else: return f'{type(self).__name__}({self._path_original})' @_docstring.dedent_interpd def __init__(self, posA=None, posB=None, *, path=None, arrowstyle='simple', connectionstyle='arc3', patchA=None, patchB=None, shrinkA=2, shrinkB=2, mutation_scale=1, mutation_aspect=1, **kwargs): kwargs.setdefault('joinstyle', JoinStyle.round) kwargs.setdefault('capstyle', CapStyle.round) super().__init__(**kwargs) if posA is not None and posB is not None and (path is None): self._posA_posB = [posA, posB] if connectionstyle is None: connectionstyle = 'arc3' self.set_connectionstyle(connectionstyle) elif posA is None and posB is None and (path is not None): self._posA_posB = None else: raise ValueError('Either posA and posB, or path need to provided') self.patchA = patchA self.patchB = patchB self.shrinkA = shrinkA self.shrinkB = shrinkB self._path_original = path self.set_arrowstyle(arrowstyle) self._mutation_scale = mutation_scale self._mutation_aspect = mutation_aspect self._dpi_cor = 1.0 def set_positions(self, posA, posB): if posA is not None: self._posA_posB[0] = posA if posB is not None: self._posA_posB[1] = posB self.stale = True def set_patchA(self, patchA): self.patchA = patchA self.stale = True def set_patchB(self, patchB): self.patchB = patchB self.stale = True @_docstring.dedent_interpd def set_connectionstyle(self, connectionstyle=None, **kwargs): if connectionstyle is None: return ConnectionStyle.pprint_styles() self._connector = ConnectionStyle(connectionstyle, **kwargs) if isinstance(connectionstyle, str) else connectionstyle self.stale = True def get_connectionstyle(self): return self._connector @_docstring.dedent_interpd def set_arrowstyle(self, arrowstyle=None, **kwargs): if arrowstyle is None: return ArrowStyle.pprint_styles() self._arrow_transmuter = ArrowStyle(arrowstyle, **kwargs) if isinstance(arrowstyle, str) else arrowstyle self.stale = True def get_arrowstyle(self): return self._arrow_transmuter def set_mutation_scale(self, scale): self._mutation_scale = scale self.stale = True def get_mutation_scale(self): return self._mutation_scale def set_mutation_aspect(self, aspect): self._mutation_aspect = aspect self.stale = True def get_mutation_aspect(self): return self._mutation_aspect if self._mutation_aspect is not None else 1 def get_path(self): (_path, fillable) = self._get_path_in_displaycoord() if np.iterable(fillable): _path = Path.make_compound_path(*_path) return self.get_transform().inverted().transform_path(_path) def _get_path_in_displaycoord(self): dpi_cor = self._dpi_cor if self._posA_posB is not None: posA = self._convert_xy_units(self._posA_posB[0]) posB = self._convert_xy_units(self._posA_posB[1]) (posA, posB) = self.get_transform().transform((posA, posB)) _path = self.get_connectionstyle()(posA, posB, patchA=self.patchA, patchB=self.patchB, shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor) else: _path = self.get_transform().transform_path(self._path_original) (_path, fillable) = self.get_arrowstyle()(_path, self.get_mutation_scale() * dpi_cor, self.get_linewidth() * dpi_cor, self.get_mutation_aspect()) return (_path, fillable) def draw(self, renderer): if not self.get_visible(): return self._dpi_cor = renderer.points_to_pixels(1.0) (path, fillable) = self._get_path_in_displaycoord() if not np.iterable(fillable): path = [path] fillable = [fillable] affine = transforms.IdentityTransform() self._draw_paths_with_artist_properties(renderer, [(p, affine, self._facecolor if f and self._facecolor[3] else None) for (p, f) in zip(path, fillable)]) class ConnectionPatch(FancyArrowPatch): def __str__(self): return 'ConnectionPatch((%g, %g), (%g, %g))' % (self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1]) @_docstring.dedent_interpd def __init__(self, xyA, xyB, coordsA, coordsB=None, *, axesA=None, axesB=None, arrowstyle='-', connectionstyle='arc3', patchA=None, patchB=None, shrinkA=0.0, shrinkB=0.0, mutation_scale=10.0, mutation_aspect=None, clip_on=False, **kwargs): if coordsB is None: coordsB = coordsA self.xy1 = xyA self.xy2 = xyB self.coords1 = coordsA self.coords2 = coordsB self.axesA = axesA self.axesB = axesB super().__init__(posA=(0, 0), posB=(1, 1), arrowstyle=arrowstyle, connectionstyle=connectionstyle, patchA=patchA, patchB=patchB, shrinkA=shrinkA, shrinkB=shrinkB, mutation_scale=mutation_scale, mutation_aspect=mutation_aspect, clip_on=clip_on, **kwargs) self._annotation_clip = None def _get_xy(self, xy, s, axes=None): s0 = s if axes is None: axes = self.axes xy = np.array(xy) fig = self.get_figure(root=False) if s in ['figure points', 'axes points']: xy *= fig.dpi / 72 s = s.replace('points', 'pixels') elif s == 'figure fraction': s = fig.transFigure elif s == 'subfigure fraction': s = fig.transSubfigure elif s == 'axes fraction': s = axes.transAxes (x, y) = xy if s == 'data': trans = axes.transData x = float(self.convert_xunits(x)) y = float(self.convert_yunits(y)) return trans.transform((x, y)) elif s == 'offset points': if self.xycoords == 'offset points': return self._get_xy(self.xy, 'data') return self._get_xy(self.xy, self.xycoords) + xy * self.get_figure(root=True).dpi / 72 elif s == 'polar': (theta, r) = (x, y) x = r * np.cos(theta) y = r * np.sin(theta) trans = axes.transData return trans.transform((x, y)) elif s == 'figure pixels': bb = self.get_figure(root=False).figbbox x = bb.x0 + x if x >= 0 else bb.x1 + x y = bb.y0 + y if y >= 0 else bb.y1 + y return (x, y) elif s == 'subfigure pixels': bb = self.get_figure(root=False).bbox x = bb.x0 + x if x >= 0 else bb.x1 + x y = bb.y0 + y if y >= 0 else bb.y1 + y return (x, y) elif s == 'axes pixels': bb = axes.bbox x = bb.x0 + x if x >= 0 else bb.x1 + x y = bb.y0 + y if y >= 0 else bb.y1 + y return (x, y) elif isinstance(s, transforms.Transform): return s.transform(xy) else: raise ValueError(f'{s0} is not a valid coordinate transformation') def set_annotation_clip(self, b): self._annotation_clip = b self.stale = True def get_annotation_clip(self): return self._annotation_clip def _get_path_in_displaycoord(self): dpi_cor = self._dpi_cor posA = self._get_xy(self.xy1, self.coords1, self.axesA) posB = self._get_xy(self.xy2, self.coords2, self.axesB) path = self.get_connectionstyle()(posA, posB, patchA=self.patchA, patchB=self.patchB, shrinkA=self.shrinkA * dpi_cor, shrinkB=self.shrinkB * dpi_cor) (path, fillable) = self.get_arrowstyle()(path, self.get_mutation_scale() * dpi_cor, self.get_linewidth() * dpi_cor, self.get_mutation_aspect()) return (path, fillable) def _check_xy(self, renderer): b = self.get_annotation_clip() if b or (b is None and self.coords1 == 'data'): xy_pixel = self._get_xy(self.xy1, self.coords1, self.axesA) if self.axesA is None: axes = self.axes else: axes = self.axesA if not axes.contains_point(xy_pixel): return False if b or (b is None and self.coords2 == 'data'): xy_pixel = self._get_xy(self.xy2, self.coords2, self.axesB) if self.axesB is None: axes = self.axes else: axes = self.axesB if not axes.contains_point(xy_pixel): return False return True def draw(self, renderer): if not self.get_visible() or not self._check_xy(renderer): return super().draw(renderer) # File: matplotlib-main/lib/matplotlib/path.py """""" import copy from functools import lru_cache from weakref import WeakValueDictionary import numpy as np import matplotlib as mpl from . import _api, _path from .cbook import _to_unmasked_float_array, simple_linear_interpolation from .bezier import BezierSegment class Path: code_type = np.uint8 STOP = code_type(0) MOVETO = code_type(1) LINETO = code_type(2) CURVE3 = code_type(3) CURVE4 = code_type(4) CLOSEPOLY = code_type(79) NUM_VERTICES_FOR_CODE = {STOP: 1, MOVETO: 1, LINETO: 1, CURVE3: 2, CURVE4: 3, CLOSEPOLY: 1} def __init__(self, vertices, codes=None, _interpolation_steps=1, closed=False, readonly=False): vertices = _to_unmasked_float_array(vertices) _api.check_shape((None, 2), vertices=vertices) if codes is not None and len(vertices): codes = np.asarray(codes, self.code_type) if codes.ndim != 1 or len(codes) != len(vertices): raise ValueError(f"'codes' must be a 1D list or array with the same length of 'vertices'. Your vertices have shape {vertices.shape} but your codes have shape {codes.shape}") if len(codes) and codes[0] != self.MOVETO: raise ValueError(f"The first element of 'code' must be equal to 'MOVETO' ({self.MOVETO}). Your first code is {codes[0]}") elif closed and len(vertices): codes = np.empty(len(vertices), dtype=self.code_type) codes[0] = self.MOVETO codes[1:-1] = self.LINETO codes[-1] = self.CLOSEPOLY self._vertices = vertices self._codes = codes self._interpolation_steps = _interpolation_steps self._update_values() if readonly: self._vertices.flags.writeable = False if self._codes is not None: self._codes.flags.writeable = False self._readonly = True else: self._readonly = False @classmethod def _fast_from_codes_and_verts(cls, verts, codes, internals_from=None): pth = cls.__new__(cls) pth._vertices = _to_unmasked_float_array(verts) pth._codes = codes pth._readonly = False if internals_from is not None: pth._should_simplify = internals_from._should_simplify pth._simplify_threshold = internals_from._simplify_threshold pth._interpolation_steps = internals_from._interpolation_steps else: pth._should_simplify = True pth._simplify_threshold = mpl.rcParams['path.simplify_threshold'] pth._interpolation_steps = 1 return pth @classmethod def _create_closed(cls, vertices): v = _to_unmasked_float_array(vertices) return cls(np.concatenate([v, v[:1]]), closed=True) def _update_values(self): self._simplify_threshold = mpl.rcParams['path.simplify_threshold'] self._should_simplify = self._simplify_threshold > 0 and mpl.rcParams['path.simplify'] and (len(self._vertices) >= 128) and (self._codes is None or np.all(self._codes <= Path.LINETO)) @property def vertices(self): return self._vertices @vertices.setter def vertices(self, vertices): if self._readonly: raise AttributeError("Can't set vertices on a readonly Path") self._vertices = vertices self._update_values() @property def codes(self): return self._codes @codes.setter def codes(self, codes): if self._readonly: raise AttributeError("Can't set codes on a readonly Path") self._codes = codes self._update_values() @property def simplify_threshold(self): return self._simplify_threshold @simplify_threshold.setter def simplify_threshold(self, threshold): self._simplify_threshold = threshold @property def should_simplify(self): return self._should_simplify @should_simplify.setter def should_simplify(self, should_simplify): self._should_simplify = should_simplify @property def readonly(self): return self._readonly def copy(self): return copy.copy(self) def __deepcopy__(self, memo=None): p = copy.deepcopy(super(), memo) p._readonly = False return p deepcopy = __deepcopy__ @classmethod def make_compound_path_from_polys(cls, XY): (numpolys, numsides, two) = XY.shape if two != 2: raise ValueError("The third dimension of 'XY' must be 2") stride = numsides + 1 nverts = numpolys * stride verts = np.zeros((nverts, 2)) codes = np.full(nverts, cls.LINETO, dtype=cls.code_type) codes[0::stride] = cls.MOVETO codes[numsides::stride] = cls.CLOSEPOLY for i in range(numsides): verts[i::stride] = XY[:, i] return cls(verts, codes) @classmethod def make_compound_path(cls, *args): if not args: return Path(np.empty([0, 2], dtype=np.float32)) vertices = np.concatenate([path.vertices for path in args]) codes = np.empty(len(vertices), dtype=cls.code_type) i = 0 for path in args: size = len(path.vertices) if path.codes is None: if size: codes[i] = cls.MOVETO codes[i + 1:i + size] = cls.LINETO else: codes[i:i + size] = path.codes i += size not_stop_mask = codes != cls.STOP return cls(vertices[not_stop_mask], codes[not_stop_mask]) def __repr__(self): return f'Path({self.vertices!r}, {self.codes!r})' def __len__(self): return len(self.vertices) def iter_segments(self, transform=None, remove_nans=True, clip=None, snap=False, stroke_width=1.0, simplify=None, curves=True, sketch=None): if not len(self): return cleaned = self.cleaned(transform=transform, remove_nans=remove_nans, clip=clip, snap=snap, stroke_width=stroke_width, simplify=simplify, curves=curves, sketch=sketch) NUM_VERTICES_FOR_CODE = self.NUM_VERTICES_FOR_CODE STOP = self.STOP vertices = iter(cleaned.vertices) codes = iter(cleaned.codes) for (curr_vertices, code) in zip(vertices, codes): if code == STOP: break extra_vertices = NUM_VERTICES_FOR_CODE[code] - 1 if extra_vertices: for i in range(extra_vertices): next(codes) curr_vertices = np.append(curr_vertices, next(vertices)) yield (curr_vertices, code) def iter_bezier(self, **kwargs): first_vert = None prev_vert = None for (verts, code) in self.iter_segments(**kwargs): if first_vert is None: if code != Path.MOVETO: raise ValueError('Malformed path, must start with MOVETO.') if code == Path.MOVETO: first_vert = verts yield (BezierSegment(np.array([first_vert])), code) elif code == Path.LINETO: yield (BezierSegment(np.array([prev_vert, verts])), code) elif code == Path.CURVE3: yield (BezierSegment(np.array([prev_vert, verts[:2], verts[2:]])), code) elif code == Path.CURVE4: yield (BezierSegment(np.array([prev_vert, verts[:2], verts[2:4], verts[4:]])), code) elif code == Path.CLOSEPOLY: yield (BezierSegment(np.array([prev_vert, first_vert])), code) elif code == Path.STOP: return else: raise ValueError(f'Invalid Path.code_type: {code}') prev_vert = verts[-2:] def _iter_connected_components(self): if self.codes is None: yield self else: idxs = np.append((self.codes == Path.MOVETO).nonzero()[0], len(self.codes)) for sl in map(slice, idxs, idxs[1:]): yield Path._fast_from_codes_and_verts(self.vertices[sl], self.codes[sl], self) def cleaned(self, transform=None, remove_nans=False, clip=None, *, simplify=False, curves=False, stroke_width=1.0, snap=False, sketch=None): (vertices, codes) = _path.cleanup_path(self, transform, remove_nans, clip, snap, stroke_width, simplify, curves, sketch) pth = Path._fast_from_codes_and_verts(vertices, codes, self) if not simplify: pth._should_simplify = False return pth def transformed(self, transform): return Path(transform.transform(self.vertices), self.codes, self._interpolation_steps) def contains_point(self, point, transform=None, radius=0.0): if transform is not None: transform = transform.frozen() if transform and (not transform.is_affine): self = transform.transform_path(self) transform = None return _path.point_in_path(point[0], point[1], radius, self, transform) def contains_points(self, points, transform=None, radius=0.0): if transform is not None: transform = transform.frozen() result = _path.points_in_path(points, radius, self, transform) return result.astype('bool') def contains_path(self, path, transform=None): if transform is not None: transform = transform.frozen() return _path.path_in_path(self, None, path, transform) def get_extents(self, transform=None, **kwargs): from .transforms import Bbox if transform is not None: self = transform.transform_path(self) if self.codes is None: xys = self.vertices elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0: xys = self.vertices[np.isin(self.codes, [Path.MOVETO, Path.LINETO])] else: xys = [] for (curve, code) in self.iter_bezier(**kwargs): (_, dzeros) = curve.axis_aligned_extrema() xys.append(curve([0, *dzeros, 1])) xys = np.concatenate(xys) if len(xys): return Bbox([xys.min(axis=0), xys.max(axis=0)]) else: return Bbox.null() def intersects_path(self, other, filled=True): return _path.path_intersects_path(self, other, filled) def intersects_bbox(self, bbox, filled=True): return _path.path_intersects_rectangle(self, bbox.x0, bbox.y0, bbox.x1, bbox.y1, filled) def interpolated(self, steps): if steps == 1: return self vertices = simple_linear_interpolation(self.vertices, steps) codes = self.codes if codes is not None: new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO, dtype=self.code_type) new_codes[0::steps] = codes else: new_codes = None return Path(vertices, new_codes) def to_polygons(self, transform=None, width=0, height=0, closed_only=True): if len(self.vertices) == 0: return [] if transform is not None: transform = transform.frozen() if self.codes is None and (width == 0 or height == 0): vertices = self.vertices if closed_only: if len(vertices) < 3: return [] elif np.any(vertices[0] != vertices[-1]): vertices = [*vertices, vertices[0]] if transform is None: return [vertices] else: return [transform.transform(vertices)] return _path.convert_path_to_polygons(self, transform, width, height, closed_only) _unit_rectangle = None @classmethod def unit_rectangle(cls): if cls._unit_rectangle is None: cls._unit_rectangle = cls([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]], closed=True, readonly=True) return cls._unit_rectangle _unit_regular_polygons = WeakValueDictionary() @classmethod def unit_regular_polygon(cls, numVertices): if numVertices <= 16: path = cls._unit_regular_polygons.get(numVertices) else: path = None if path is None: theta = 2 * np.pi / numVertices * np.arange(numVertices + 1) + np.pi / 2 verts = np.column_stack((np.cos(theta), np.sin(theta))) path = cls(verts, closed=True, readonly=True) if numVertices <= 16: cls._unit_regular_polygons[numVertices] = path return path _unit_regular_stars = WeakValueDictionary() @classmethod def unit_regular_star(cls, numVertices, innerCircle=0.5): if numVertices <= 16: path = cls._unit_regular_stars.get((numVertices, innerCircle)) else: path = None if path is None: ns2 = numVertices * 2 theta = 2 * np.pi / ns2 * np.arange(ns2 + 1) theta += np.pi / 2.0 r = np.ones(ns2 + 1) r[1::2] = innerCircle verts = (r * np.vstack((np.cos(theta), np.sin(theta)))).T path = cls(verts, closed=True, readonly=True) if numVertices <= 16: cls._unit_regular_stars[numVertices, innerCircle] = path return path @classmethod def unit_regular_asterisk(cls, numVertices): return cls.unit_regular_star(numVertices, 0.0) _unit_circle = None @classmethod def unit_circle(cls): if cls._unit_circle is None: cls._unit_circle = cls.circle(center=(0, 0), radius=1, readonly=True) return cls._unit_circle @classmethod def circle(cls, center=(0.0, 0.0), radius=1.0, readonly=False): MAGIC = 0.2652031 SQRTHALF = np.sqrt(0.5) MAGIC45 = SQRTHALF * MAGIC vertices = np.array([[0.0, -1.0], [MAGIC, -1.0], [SQRTHALF - MAGIC45, -SQRTHALF - MAGIC45], [SQRTHALF, -SQRTHALF], [SQRTHALF + MAGIC45, -SQRTHALF + MAGIC45], [1.0, -MAGIC], [1.0, 0.0], [1.0, MAGIC], [SQRTHALF + MAGIC45, SQRTHALF - MAGIC45], [SQRTHALF, SQRTHALF], [SQRTHALF - MAGIC45, SQRTHALF + MAGIC45], [MAGIC, 1.0], [0.0, 1.0], [-MAGIC, 1.0], [-SQRTHALF + MAGIC45, SQRTHALF + MAGIC45], [-SQRTHALF, SQRTHALF], [-SQRTHALF - MAGIC45, SQRTHALF - MAGIC45], [-1.0, MAGIC], [-1.0, 0.0], [-1.0, -MAGIC], [-SQRTHALF - MAGIC45, -SQRTHALF + MAGIC45], [-SQRTHALF, -SQRTHALF], [-SQRTHALF + MAGIC45, -SQRTHALF - MAGIC45], [-MAGIC, -1.0], [0.0, -1.0], [0.0, -1.0]], dtype=float) codes = [cls.CURVE4] * 26 codes[0] = cls.MOVETO codes[-1] = cls.CLOSEPOLY return Path(vertices * radius + center, codes, readonly=readonly) _unit_circle_righthalf = None @classmethod def unit_circle_righthalf(cls): if cls._unit_circle_righthalf is None: MAGIC = 0.2652031 SQRTHALF = np.sqrt(0.5) MAGIC45 = SQRTHALF * MAGIC vertices = np.array([[0.0, -1.0], [MAGIC, -1.0], [SQRTHALF - MAGIC45, -SQRTHALF - MAGIC45], [SQRTHALF, -SQRTHALF], [SQRTHALF + MAGIC45, -SQRTHALF + MAGIC45], [1.0, -MAGIC], [1.0, 0.0], [1.0, MAGIC], [SQRTHALF + MAGIC45, SQRTHALF - MAGIC45], [SQRTHALF, SQRTHALF], [SQRTHALF - MAGIC45, SQRTHALF + MAGIC45], [MAGIC, 1.0], [0.0, 1.0], [0.0, -1.0]], float) codes = np.full(14, cls.CURVE4, dtype=cls.code_type) codes[0] = cls.MOVETO codes[-1] = cls.CLOSEPOLY cls._unit_circle_righthalf = cls(vertices, codes, readonly=True) return cls._unit_circle_righthalf @classmethod def arc(cls, theta1, theta2, n=None, is_wedge=False): halfpi = np.pi * 0.5 eta1 = theta1 eta2 = theta2 - 360 * np.floor((theta2 - theta1) / 360) if theta2 != theta1 and eta2 <= eta1: eta2 += 360 (eta1, eta2) = np.deg2rad([eta1, eta2]) if n is None: n = int(2 ** np.ceil((eta2 - eta1) / halfpi)) if n < 1: raise ValueError('n must be >= 1 or None') deta = (eta2 - eta1) / n t = np.tan(0.5 * deta) alpha = np.sin(deta) * (np.sqrt(4.0 + 3.0 * t * t) - 1) / 3.0 steps = np.linspace(eta1, eta2, n + 1, True) cos_eta = np.cos(steps) sin_eta = np.sin(steps) xA = cos_eta[:-1] yA = sin_eta[:-1] xA_dot = -yA yA_dot = xA xB = cos_eta[1:] yB = sin_eta[1:] xB_dot = -yB yB_dot = xB if is_wedge: length = n * 3 + 4 vertices = np.zeros((length, 2), float) codes = np.full(length, cls.CURVE4, dtype=cls.code_type) vertices[1] = [xA[0], yA[0]] codes[0:2] = [cls.MOVETO, cls.LINETO] codes[-2:] = [cls.LINETO, cls.CLOSEPOLY] vertex_offset = 2 end = length - 2 else: length = n * 3 + 1 vertices = np.empty((length, 2), float) codes = np.full(length, cls.CURVE4, dtype=cls.code_type) vertices[0] = [xA[0], yA[0]] codes[0] = cls.MOVETO vertex_offset = 1 end = length vertices[vertex_offset:end:3, 0] = xA + alpha * xA_dot vertices[vertex_offset:end:3, 1] = yA + alpha * yA_dot vertices[vertex_offset + 1:end:3, 0] = xB - alpha * xB_dot vertices[vertex_offset + 1:end:3, 1] = yB - alpha * yB_dot vertices[vertex_offset + 2:end:3, 0] = xB vertices[vertex_offset + 2:end:3, 1] = yB return cls(vertices, codes, readonly=True) @classmethod def wedge(cls, theta1, theta2, n=None): return cls.arc(theta1, theta2, n, True) @staticmethod @lru_cache(8) def hatch(hatchpattern, density=6): from matplotlib.hatch import get_path return get_path(hatchpattern, density) if hatchpattern is not None else None def clip_to_bbox(self, bbox, inside=True): verts = _path.clip_path_to_rect(self, bbox, inside) paths = [Path(poly) for poly in verts] return self.make_compound_path(*paths) def get_path_collection_extents(master_transform, paths, transforms, offsets, offset_transform): from .transforms import Bbox if len(paths) == 0: raise ValueError('No paths provided') if len(offsets) == 0: _api.warn_deprecated('3.8', message='Calling get_path_collection_extents() with an empty offsets list is deprecated since %(since)s. Support will be removed %(removal)s.') (extents, minpos) = _path.get_path_collection_extents(master_transform, paths, np.atleast_3d(transforms), offsets, offset_transform) return Bbox.from_extents(*extents, minpos=minpos) # File: matplotlib-main/lib/matplotlib/patheffects.py """""" from matplotlib.backend_bases import RendererBase from matplotlib import colors as mcolors from matplotlib import patches as mpatches from matplotlib import transforms as mtransforms from matplotlib.path import Path import numpy as np class AbstractPathEffect: def __init__(self, offset=(0.0, 0.0)): self._offset = offset def _offset_transform(self, renderer): return mtransforms.Affine2D().translate(*map(renderer.points_to_pixels, self._offset)) def _update_gc(self, gc, new_gc_dict): new_gc_dict = new_gc_dict.copy() dashes = new_gc_dict.pop('dashes', None) if dashes: gc.set_dashes(**dashes) for (k, v) in new_gc_dict.items(): set_method = getattr(gc, 'set_' + k, None) if not callable(set_method): raise AttributeError(f'Unknown property {k}') set_method(v) return gc def draw_path(self, renderer, gc, tpath, affine, rgbFace=None): if isinstance(renderer, PathEffectRenderer): renderer = renderer._renderer return renderer.draw_path(gc, tpath, affine, rgbFace) class PathEffectRenderer(RendererBase): def __init__(self, path_effects, renderer): self._path_effects = path_effects self._renderer = renderer def copy_with_path_effect(self, path_effects): return self.__class__(path_effects, self._renderer) def __getattribute__(self, name): if name in ['flipy', 'get_canvas_width_height', 'new_gc', 'points_to_pixels', '_text2path', 'height', 'width']: return getattr(self._renderer, name) else: return object.__getattribute__(self, name) def draw_path(self, gc, tpath, affine, rgbFace=None): for path_effect in self._path_effects: path_effect.draw_path(self._renderer, gc, tpath, affine, rgbFace) def draw_markers(self, gc, marker_path, marker_trans, path, *args, **kwargs): if len(self._path_effects) == 1: return super().draw_markers(gc, marker_path, marker_trans, path, *args, **kwargs) for path_effect in self._path_effects: renderer = self.copy_with_path_effect([path_effect]) renderer.draw_markers(gc, marker_path, marker_trans, path, *args, **kwargs) def draw_path_collection(self, gc, master_transform, paths, *args, **kwargs): if len(self._path_effects) == 1: return super().draw_path_collection(gc, master_transform, paths, *args, **kwargs) for path_effect in self._path_effects: renderer = self.copy_with_path_effect([path_effect]) renderer.draw_path_collection(gc, master_transform, paths, *args, **kwargs) def open_group(self, s, gid=None): return self._renderer.open_group(s, gid) def close_group(self, s): return self._renderer.close_group(s) class Normal(AbstractPathEffect): def _subclass_with_normal(effect_class): class withEffect(effect_class): def draw_path(self, renderer, gc, tpath, affine, rgbFace): super().draw_path(renderer, gc, tpath, affine, rgbFace) renderer.draw_path(gc, tpath, affine, rgbFace) withEffect.__name__ = f'with{effect_class.__name__}' withEffect.__qualname__ = f'with{effect_class.__name__}' withEffect.__doc__ = f'\n A shortcut PathEffect for applying `.{effect_class.__name__}` and then\n drawing the original Artist.\n\n With this class you can use ::\n\n artist.set_path_effects([patheffects.with{effect_class.__name__}()])\n\n as a shortcut for ::\n\n artist.set_path_effects([patheffects.{effect_class.__name__}(),\n patheffects.Normal()])\n ' withEffect.draw_path.__doc__ = effect_class.draw_path.__doc__ return withEffect class Stroke(AbstractPathEffect): def __init__(self, offset=(0, 0), **kwargs): super().__init__(offset) self._gc = kwargs def draw_path(self, renderer, gc, tpath, affine, rgbFace): gc0 = renderer.new_gc() gc0.copy_properties(gc) gc0 = self._update_gc(gc0, self._gc) renderer.draw_path(gc0, tpath, affine + self._offset_transform(renderer), rgbFace) gc0.restore() withStroke = _subclass_with_normal(effect_class=Stroke) class SimplePatchShadow(AbstractPathEffect): def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): super().__init__(offset) if shadow_rgbFace is None: self._shadow_rgbFace = shadow_rgbFace else: self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace) if alpha is None: alpha = 0.3 self._alpha = alpha self._rho = rho self._gc = kwargs def draw_path(self, renderer, gc, tpath, affine, rgbFace): gc0 = renderer.new_gc() gc0.copy_properties(gc) if self._shadow_rgbFace is None: (r, g, b) = (rgbFace or (1.0, 1.0, 1.0))[:3] shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho) else: shadow_rgbFace = self._shadow_rgbFace gc0.set_foreground('none') gc0.set_alpha(self._alpha) gc0.set_linewidth(0) gc0 = self._update_gc(gc0, self._gc) renderer.draw_path(gc0, tpath, affine + self._offset_transform(renderer), shadow_rgbFace) gc0.restore() withSimplePatchShadow = _subclass_with_normal(effect_class=SimplePatchShadow) class SimpleLineShadow(AbstractPathEffect): def __init__(self, offset=(2, -2), shadow_color='k', alpha=0.3, rho=0.3, **kwargs): super().__init__(offset) if shadow_color is None: self._shadow_color = shadow_color else: self._shadow_color = mcolors.to_rgba(shadow_color) self._alpha = alpha self._rho = rho self._gc = kwargs def draw_path(self, renderer, gc, tpath, affine, rgbFace): gc0 = renderer.new_gc() gc0.copy_properties(gc) if self._shadow_color is None: (r, g, b) = (gc0.get_foreground() or (1.0, 1.0, 1.0))[:3] shadow_rgbFace = (r * self._rho, g * self._rho, b * self._rho) else: shadow_rgbFace = self._shadow_color gc0.set_foreground(shadow_rgbFace) gc0.set_alpha(self._alpha) gc0 = self._update_gc(gc0, self._gc) renderer.draw_path(gc0, tpath, affine + self._offset_transform(renderer)) gc0.restore() class PathPatchEffect(AbstractPathEffect): def __init__(self, offset=(0, 0), **kwargs): super().__init__(offset=offset) self.patch = mpatches.PathPatch([], **kwargs) def draw_path(self, renderer, gc, tpath, affine, rgbFace): self.patch._path = tpath self.patch.set_transform(affine + self._offset_transform(renderer)) self.patch.set_clip_box(gc.get_clip_rectangle()) clip_path = gc.get_clip_path() if clip_path and self.patch.get_clip_path() is None: self.patch.set_clip_path(*clip_path) self.patch.draw(renderer) class TickedStroke(AbstractPathEffect): def __init__(self, offset=(0, 0), spacing=10.0, angle=45.0, length=np.sqrt(2), **kwargs): super().__init__(offset) self._spacing = spacing self._angle = angle self._length = length self._gc = kwargs def draw_path(self, renderer, gc, tpath, affine, rgbFace): gc0 = renderer.new_gc() gc0.copy_properties(gc) gc0 = self._update_gc(gc0, self._gc) trans = affine + self._offset_transform(renderer) theta = -np.radians(self._angle) trans_matrix = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) spacing_px = renderer.points_to_pixels(self._spacing) transpath = affine.transform_path(tpath) polys = transpath.to_polygons(closed_only=False) for p in polys: x = p[:, 0] y = p[:, 1] if x.size < 2: continue ds = np.hypot(x[1:] - x[:-1], y[1:] - y[:-1]) s = np.concatenate(([0.0], np.cumsum(ds))) s_total = s[-1] num = int(np.ceil(s_total / spacing_px)) - 1 s_tick = np.linspace(spacing_px / 2, s_total - spacing_px / 2, num) x_tick = np.interp(s_tick, s, x) y_tick = np.interp(s_tick, s, y) delta_s = self._spacing * 0.001 u = (np.interp(s_tick + delta_s, s, x) - x_tick) / delta_s v = (np.interp(s_tick + delta_s, s, y) - y_tick) / delta_s n = np.hypot(u, v) mask = n == 0 n[mask] = 1.0 uv = np.array([u / n, v / n]).T uv[mask] = np.array([0, 0]).T dxy = np.dot(uv, trans_matrix) * self._length * spacing_px x_end = x_tick + dxy[:, 0] y_end = y_tick + dxy[:, 1] xyt = np.empty((2 * num, 2), dtype=x_tick.dtype) xyt[0::2, 0] = x_tick xyt[1::2, 0] = x_end xyt[0::2, 1] = y_tick xyt[1::2, 1] = y_end codes = np.tile([Path.MOVETO, Path.LINETO], num) h = Path(xyt, codes) renderer.draw_path(gc0, h, affine.inverted() + trans, rgbFace) gc0.restore() withTickedStroke = _subclass_with_normal(effect_class=TickedStroke) # File: matplotlib-main/lib/matplotlib/projections/__init__.py """""" from .. import axes, _docstring from .geo import AitoffAxes, HammerAxes, LambertAxes, MollweideAxes from .polar import PolarAxes try: from mpl_toolkits.mplot3d import Axes3D except Exception: import warnings warnings.warn('Unable to import Axes3D. This may be due to multiple versions of Matplotlib being installed (e.g. as a system package and as a pip package). As a result, the 3D projection is not available.') Axes3D = None class ProjectionRegistry: def __init__(self): self._all_projection_types = {} def register(self, *projections): for projection in projections: name = projection.name self._all_projection_types[name] = projection def get_projection_class(self, name): return self._all_projection_types[name] def get_projection_names(self): return sorted(self._all_projection_types) projection_registry = ProjectionRegistry() projection_registry.register(axes.Axes, PolarAxes, AitoffAxes, HammerAxes, LambertAxes, MollweideAxes) if Axes3D is not None: projection_registry.register(Axes3D) else: del Axes3D def register_projection(cls): projection_registry.register(cls) def get_projection_class(projection=None): if projection is None: projection = 'rectilinear' try: return projection_registry.get_projection_class(projection) except KeyError as err: raise ValueError('Unknown projection %r' % projection) from err get_projection_names = projection_registry.get_projection_names _docstring.interpd.update(projection_names=get_projection_names()) # File: matplotlib-main/lib/matplotlib/projections/geo.py import numpy as np import matplotlib as mpl from matplotlib import _api from matplotlib.axes import Axes import matplotlib.axis as maxis from matplotlib.patches import Circle from matplotlib.path import Path import matplotlib.spines as mspines from matplotlib.ticker import Formatter, NullLocator, FixedLocator, NullFormatter from matplotlib.transforms import Affine2D, BboxTransformTo, Transform class GeoAxes(Axes): class ThetaFormatter(Formatter): def __init__(self, round_to=1.0): self._round_to = round_to def __call__(self, x, pos=None): degrees = round(np.rad2deg(x) / self._round_to) * self._round_to return f'{degrees:0.0f}°' RESOLUTION = 75 def _init_axis(self): self.xaxis = maxis.XAxis(self, clear=False) self.yaxis = maxis.YAxis(self, clear=False) self.spines['geo'].register_axis(self.yaxis) def clear(self): super().clear() self.set_longitude_grid(30) self.set_latitude_grid(15) self.set_longitude_grid_ends(75) self.xaxis.set_minor_locator(NullLocator()) self.yaxis.set_minor_locator(NullLocator()) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) self.grid(mpl.rcParams['axes.grid']) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0) def _set_lim_and_transforms(self): self.transProjection = self._get_core_transform(self.RESOLUTION) self.transAffine = self._get_affine_transform() self.transAxes = BboxTransformTo(self.bbox) self.transData = self.transProjection + self.transAffine + self.transAxes self._xaxis_pretransform = Affine2D().scale(1, self._longitude_cap * 2).translate(0, -self._longitude_cap) self._xaxis_transform = self._xaxis_pretransform + self.transData self._xaxis_text1_transform = Affine2D().scale(1, 0) + self.transData + Affine2D().translate(0, 4) self._xaxis_text2_transform = Affine2D().scale(1, 0) + self.transData + Affine2D().translate(0, -4) yaxis_stretch = Affine2D().scale(np.pi * 2, 1).translate(-np.pi, 0) yaxis_space = Affine2D().scale(1, 1.1) self._yaxis_transform = yaxis_stretch + self.transData yaxis_text_base = yaxis_stretch + self.transProjection + (yaxis_space + self.transAffine + self.transAxes) self._yaxis_text1_transform = yaxis_text_base + Affine2D().translate(-8, 0) self._yaxis_text2_transform = yaxis_text_base + Affine2D().translate(8, 0) def _get_affine_transform(self): transform = self._get_core_transform(1) (xscale, _) = transform.transform((np.pi, 0)) (_, yscale) = transform.transform((0, np.pi / 2)) return Affine2D().scale(0.5 / xscale, 0.5 / yscale).translate(0.5, 0.5) def get_xaxis_transform(self, which='grid'): _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return (self._xaxis_text1_transform, 'bottom', 'center') def get_xaxis_text2_transform(self, pad): return (self._xaxis_text2_transform, 'top', 'center') def get_yaxis_transform(self, which='grid'): _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) return self._yaxis_transform def get_yaxis_text1_transform(self, pad): return (self._yaxis_text1_transform, 'center', 'right') def get_yaxis_text2_transform(self, pad): return (self._yaxis_text2_transform, 'center', 'left') def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} def set_yscale(self, *args, **kwargs): if args[0] != 'linear': raise NotImplementedError set_xscale = set_yscale def set_xlim(self, *args, **kwargs): raise TypeError('Changing axes limits of a geographic projection is not supported. Please consider using Cartopy.') set_ylim = set_xlim set_xbound = set_xlim set_ybound = set_ylim def invert_xaxis(self): raise TypeError('Changing axes limits of a geographic projection is not supported. Please consider using Cartopy.') invert_yaxis = invert_xaxis def format_coord(self, lon, lat): (lon, lat) = np.rad2deg([lon, lat]) ns = 'N' if lat >= 0.0 else 'S' ew = 'E' if lon >= 0.0 else 'W' return '%f°%s, %f°%s' % (abs(lat), ns, abs(lon), ew) def set_longitude_grid(self, degrees): grid = np.arange(-180 + degrees, 180, degrees) self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.xaxis.set_major_formatter(self.ThetaFormatter(degrees)) def set_latitude_grid(self, degrees): grid = np.arange(-90 + degrees, 90, degrees) self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.yaxis.set_major_formatter(self.ThetaFormatter(degrees)) def set_longitude_grid_ends(self, degrees): self._longitude_cap = np.deg2rad(degrees) self._xaxis_pretransform.clear().scale(1.0, self._longitude_cap * 2.0).translate(0.0, -self._longitude_cap) def get_data_ratio(self): return 1.0 def can_zoom(self): return False def can_pan(self): return False def start_pan(self, x, y, button): pass def end_pan(self): pass def drag_pan(self, button, key, x, y): pass class _GeoTransform(Transform): input_dims = output_dims = 2 def __init__(self, resolution): super().__init__() self._resolution = resolution def __str__(self): return f'{type(self).__name__}({self._resolution})' def transform_path_non_affine(self, path): ipath = path.interpolated(self._resolution) return Path(self.transform(ipath.vertices), ipath.codes) class AitoffAxes(GeoAxes): name = 'aitoff' class AitoffTransform(_GeoTransform): def transform_non_affine(self, values): (longitude, latitude) = values.T half_long = longitude / 2.0 cos_latitude = np.cos(latitude) alpha = np.arccos(cos_latitude * np.cos(half_long)) sinc_alpha = np.sinc(alpha / np.pi) x = cos_latitude * np.sin(half_long) / sinc_alpha y = np.sin(latitude) / sinc_alpha return np.column_stack([x, y]) def inverted(self): return AitoffAxes.InvertedAitoffTransform(self._resolution) class InvertedAitoffTransform(_GeoTransform): def transform_non_affine(self, values): return np.full_like(values, np.nan) def inverted(self): return AitoffAxes.AitoffTransform(self._resolution) def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 super().__init__(*args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.clear() def _get_core_transform(self, resolution): return self.AitoffTransform(resolution) class HammerAxes(GeoAxes): name = 'hammer' class HammerTransform(_GeoTransform): def transform_non_affine(self, values): (longitude, latitude) = values.T half_long = longitude / 2.0 cos_latitude = np.cos(latitude) sqrt2 = np.sqrt(2.0) alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long)) x = 2.0 * sqrt2 * (cos_latitude * np.sin(half_long)) / alpha y = sqrt2 * np.sin(latitude) / alpha return np.column_stack([x, y]) def inverted(self): return HammerAxes.InvertedHammerTransform(self._resolution) class InvertedHammerTransform(_GeoTransform): def transform_non_affine(self, values): (x, y) = values.T z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2) longitude = 2 * np.arctan(z * x / (2 * (2 * z ** 2 - 1))) latitude = np.arcsin(y * z) return np.column_stack([longitude, latitude]) def inverted(self): return HammerAxes.HammerTransform(self._resolution) def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 super().__init__(*args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.clear() def _get_core_transform(self, resolution): return self.HammerTransform(resolution) class MollweideAxes(GeoAxes): name = 'mollweide' class MollweideTransform(_GeoTransform): def transform_non_affine(self, values): def d(theta): delta = -(theta + np.sin(theta) - pi_sin_l) / (1 + np.cos(theta)) return (delta, np.abs(delta) > 0.001) (longitude, latitude) = values.T clat = np.pi / 2 - np.abs(latitude) ihigh = clat < 0.087 ilow = ~ihigh aux = np.empty(latitude.shape, dtype=float) if ilow.any(): pi_sin_l = np.pi * np.sin(latitude[ilow]) theta = 2.0 * latitude[ilow] (delta, large_delta) = d(theta) while np.any(large_delta): theta[large_delta] += delta[large_delta] (delta, large_delta) = d(theta) aux[ilow] = theta / 2 if ihigh.any(): e = clat[ihigh] d = 0.5 * (3 * np.pi * e ** 2) ** (1.0 / 3) aux[ihigh] = (np.pi / 2 - d) * np.sign(latitude[ihigh]) xy = np.empty(values.shape, dtype=float) xy[:, 0] = 2.0 * np.sqrt(2.0) / np.pi * longitude * np.cos(aux) xy[:, 1] = np.sqrt(2.0) * np.sin(aux) return xy def inverted(self): return MollweideAxes.InvertedMollweideTransform(self._resolution) class InvertedMollweideTransform(_GeoTransform): def transform_non_affine(self, values): (x, y) = values.T theta = np.arcsin(y / np.sqrt(2)) longitude = np.pi / (2 * np.sqrt(2)) * x / np.cos(theta) latitude = np.arcsin((2 * theta + np.sin(2 * theta)) / np.pi) return np.column_stack([longitude, latitude]) def inverted(self): return MollweideAxes.MollweideTransform(self._resolution) def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 super().__init__(*args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.clear() def _get_core_transform(self, resolution): return self.MollweideTransform(resolution) class LambertAxes(GeoAxes): name = 'lambert' class LambertTransform(_GeoTransform): def __init__(self, center_longitude, center_latitude, resolution): _GeoTransform.__init__(self, resolution) self._center_longitude = center_longitude self._center_latitude = center_latitude def transform_non_affine(self, values): (longitude, latitude) = values.T clong = self._center_longitude clat = self._center_latitude cos_lat = np.cos(latitude) sin_lat = np.sin(latitude) diff_long = longitude - clong cos_diff_long = np.cos(diff_long) inner_k = np.maximum(1 + np.sin(clat) * sin_lat + np.cos(clat) * cos_lat * cos_diff_long, 1e-15) k = np.sqrt(2 / inner_k) x = k * cos_lat * np.sin(diff_long) y = k * (np.cos(clat) * sin_lat - np.sin(clat) * cos_lat * cos_diff_long) return np.column_stack([x, y]) def inverted(self): return LambertAxes.InvertedLambertTransform(self._center_longitude, self._center_latitude, self._resolution) class InvertedLambertTransform(_GeoTransform): def __init__(self, center_longitude, center_latitude, resolution): _GeoTransform.__init__(self, resolution) self._center_longitude = center_longitude self._center_latitude = center_latitude def transform_non_affine(self, values): (x, y) = values.T clong = self._center_longitude clat = self._center_latitude p = np.maximum(np.hypot(x, y), 1e-09) c = 2 * np.arcsin(0.5 * p) sin_c = np.sin(c) cos_c = np.cos(c) latitude = np.arcsin(cos_c * np.sin(clat) + y * sin_c * np.cos(clat) / p) longitude = clong + np.arctan(x * sin_c / (p * np.cos(clat) * cos_c - y * np.sin(clat) * sin_c)) return np.column_stack([longitude, latitude]) def inverted(self): return LambertAxes.LambertTransform(self._center_longitude, self._center_latitude, self._resolution) def __init__(self, *args, center_longitude=0, center_latitude=0, **kwargs): self._longitude_cap = np.pi / 2 self._center_longitude = center_longitude self._center_latitude = center_latitude super().__init__(*args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.clear() def clear(self): super().clear() self.yaxis.set_major_formatter(NullFormatter()) def _get_core_transform(self, resolution): return self.LambertTransform(self._center_longitude, self._center_latitude, resolution) def _get_affine_transform(self): return Affine2D().scale(0.25).translate(0.5, 0.5) # File: matplotlib-main/lib/matplotlib/projections/polar.py import math import types import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib.axes import Axes import matplotlib.axis as maxis import matplotlib.markers as mmarkers import matplotlib.patches as mpatches from matplotlib.path import Path import matplotlib.ticker as mticker import matplotlib.transforms as mtransforms from matplotlib.spines import Spine def _apply_theta_transforms_warn(): _api.warn_deprecated('3.9', message='Passing `apply_theta_transforms=True` (the default) is deprecated since Matplotlib %(since)s. Support for this will be removed in Matplotlib %(removal)s. To prevent this warning, set `apply_theta_transforms=False`, and make sure to shift theta values before being passed to this transform.') class PolarTransform(mtransforms.Transform): input_dims = output_dims = 2 def __init__(self, axis=None, use_rmin=True, *, apply_theta_transforms=True, scale_transform=None): super().__init__() self._axis = axis self._use_rmin = use_rmin self._apply_theta_transforms = apply_theta_transforms self._scale_transform = scale_transform if apply_theta_transforms: _apply_theta_transforms_warn() __str__ = mtransforms._make_str_method('_axis', use_rmin='_use_rmin', apply_theta_transforms='_apply_theta_transforms') def _get_rorigin(self): return self._scale_transform.transform((0, self._axis.get_rorigin()))[1] def transform_non_affine(self, values): (theta, r) = np.transpose(values) if self._apply_theta_transforms and self._axis is not None: theta *= self._axis.get_theta_direction() theta += self._axis.get_theta_offset() if self._use_rmin and self._axis is not None: r = (r - self._get_rorigin()) * self._axis.get_rsign() r = np.where(r >= 0, r, np.nan) return np.column_stack([r * np.cos(theta), r * np.sin(theta)]) def transform_path_non_affine(self, path): if not len(path) or path._interpolation_steps == 1: return Path(self.transform_non_affine(path.vertices), path.codes) xys = [] codes = [] last_t = last_r = None for (trs, c) in path.iter_segments(): trs = trs.reshape((-1, 2)) if c == Path.LINETO: ((t, r),) = trs if t == last_t: xys.extend(self.transform_non_affine(trs)) codes.append(Path.LINETO) elif r == last_r: (last_td, td) = np.rad2deg([last_t, t]) if self._use_rmin and self._axis is not None: r = (r - self._get_rorigin()) * self._axis.get_rsign() if last_td <= td: while td - last_td > 360: arc = Path.arc(last_td, last_td + 360) xys.extend(arc.vertices[1:] * r) codes.extend(arc.codes[1:]) last_td += 360 arc = Path.arc(last_td, td) xys.extend(arc.vertices[1:] * r) codes.extend(arc.codes[1:]) else: while last_td - td > 360: arc = Path.arc(last_td - 360, last_td) xys.extend(arc.vertices[::-1][1:] * r) codes.extend(arc.codes[1:]) last_td -= 360 arc = Path.arc(td, last_td) xys.extend(arc.vertices[::-1][1:] * r) codes.extend(arc.codes[1:]) else: trs = cbook.simple_linear_interpolation(np.vstack([(last_t, last_r), trs]), path._interpolation_steps)[1:] xys.extend(self.transform_non_affine(trs)) codes.extend([Path.LINETO] * len(trs)) else: xys.extend(self.transform_non_affine(trs)) codes.extend([c] * len(trs)) (last_t, last_r) = trs[-1] return Path(xys, codes) def inverted(self): return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin, apply_theta_transforms=self._apply_theta_transforms) class PolarAffine(mtransforms.Affine2DBase): def __init__(self, scale_transform, limits): super().__init__() self._scale_transform = scale_transform self._limits = limits self.set_children(scale_transform, limits) self._mtx = None __str__ = mtransforms._make_str_method('_scale_transform', '_limits') def get_matrix(self): if self._invalid: limits_scaled = self._limits.transformed(self._scale_transform) yscale = limits_scaled.ymax - limits_scaled.ymin affine = mtransforms.Affine2D().scale(0.5 / yscale).translate(0.5, 0.5) self._mtx = affine.get_matrix() self._inverted = None self._invalid = 0 return self._mtx class InvertedPolarTransform(mtransforms.Transform): input_dims = output_dims = 2 def __init__(self, axis=None, use_rmin=True, *, apply_theta_transforms=True): super().__init__() self._axis = axis self._use_rmin = use_rmin self._apply_theta_transforms = apply_theta_transforms if apply_theta_transforms: _apply_theta_transforms_warn() __str__ = mtransforms._make_str_method('_axis', use_rmin='_use_rmin', apply_theta_transforms='_apply_theta_transforms') def transform_non_affine(self, values): (x, y) = values.T r = np.hypot(x, y) theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi) if self._apply_theta_transforms and self._axis is not None: theta -= self._axis.get_theta_offset() theta *= self._axis.get_theta_direction() theta %= 2 * np.pi if self._use_rmin and self._axis is not None: r += self._axis.get_rorigin() r *= self._axis.get_rsign() return np.column_stack([theta, r]) def inverted(self): return PolarAxes.PolarTransform(self._axis, self._use_rmin, apply_theta_transforms=self._apply_theta_transforms) class ThetaFormatter(mticker.Formatter): def __call__(self, x, pos=None): (vmin, vmax) = self.axis.get_view_interval() d = np.rad2deg(abs(vmax - vmin)) digits = max(-int(np.log10(d) - 1.5), 0) return f'{np.rad2deg(x):0.{digits}f}°' class _AxisWrapper: def __init__(self, axis): self._axis = axis def get_view_interval(self): return np.rad2deg(self._axis.get_view_interval()) def set_view_interval(self, vmin, vmax): self._axis.set_view_interval(*np.deg2rad((vmin, vmax))) def get_minpos(self): return np.rad2deg(self._axis.get_minpos()) def get_data_interval(self): return np.rad2deg(self._axis.get_data_interval()) def set_data_interval(self, vmin, vmax): self._axis.set_data_interval(*np.deg2rad((vmin, vmax))) def get_tick_space(self): return self._axis.get_tick_space() class ThetaLocator(mticker.Locator): def __init__(self, base): self.base = base self.axis = self.base.axis = _AxisWrapper(self.base.axis) def set_axis(self, axis): self.axis = _AxisWrapper(axis) self.base.set_axis(self.axis) def __call__(self): lim = self.axis.get_view_interval() if _is_full_circle_deg(lim[0], lim[1]): return np.deg2rad(min(lim)) + np.arange(8) * 2 * np.pi / 8 else: return np.deg2rad(self.base()) def view_limits(self, vmin, vmax): (vmin, vmax) = np.rad2deg((vmin, vmax)) return np.deg2rad(self.base.view_limits(vmin, vmax)) class ThetaTick(maxis.XTick): def __init__(self, axes, *args, **kwargs): self._text1_translate = mtransforms.ScaledTranslation(0, 0, axes.get_figure(root=False).dpi_scale_trans) self._text2_translate = mtransforms.ScaledTranslation(0, 0, axes.get_figure(root=False).dpi_scale_trans) super().__init__(axes, *args, **kwargs) self.label1.set(rotation_mode='anchor', transform=self.label1.get_transform() + self._text1_translate) self.label2.set(rotation_mode='anchor', transform=self.label2.get_transform() + self._text2_translate) def _apply_params(self, **kwargs): super()._apply_params(**kwargs) trans = self.label1.get_transform() if not trans.contains_branch(self._text1_translate): self.label1.set_transform(trans + self._text1_translate) trans = self.label2.get_transform() if not trans.contains_branch(self._text2_translate): self.label2.set_transform(trans + self._text2_translate) def _update_padding(self, pad, angle): padx = pad * np.cos(angle) / 72 pady = pad * np.sin(angle) / 72 self._text1_translate._t = (padx, pady) self._text1_translate.invalidate() self._text2_translate._t = (-padx, -pady) self._text2_translate.invalidate() def update_position(self, loc): super().update_position(loc) axes = self.axes angle = loc * axes.get_theta_direction() + axes.get_theta_offset() text_angle = np.rad2deg(angle) % 360 - 90 angle -= np.pi / 2 marker = self.tick1line.get_marker() if marker in (mmarkers.TICKUP, '|'): trans = mtransforms.Affine2D().scale(1, 1).rotate(angle) elif marker == mmarkers.TICKDOWN: trans = mtransforms.Affine2D().scale(1, -1).rotate(angle) else: trans = self.tick1line._marker._transform self.tick1line._marker._transform = trans marker = self.tick2line.get_marker() if marker in (mmarkers.TICKUP, '|'): trans = mtransforms.Affine2D().scale(1, 1).rotate(angle) elif marker == mmarkers.TICKDOWN: trans = mtransforms.Affine2D().scale(1, -1).rotate(angle) else: trans = self.tick2line._marker._transform self.tick2line._marker._transform = trans (mode, user_angle) = self._labelrotation if mode == 'default': text_angle = user_angle else: if text_angle > 90: text_angle -= 180 elif text_angle < -90: text_angle += 180 text_angle += user_angle self.label1.set_rotation(text_angle) self.label2.set_rotation(text_angle) pad = self._pad + 7 self._update_padding(pad, self._loc * axes.get_theta_direction() + axes.get_theta_offset()) class ThetaAxis(maxis.XAxis): __name__ = 'thetaaxis' axis_name = 'theta' _tick_class = ThetaTick def _wrap_locator_formatter(self): self.set_major_locator(ThetaLocator(self.get_major_locator())) self.set_major_formatter(ThetaFormatter()) self.isDefault_majloc = True self.isDefault_majfmt = True def clear(self): super().clear() self.set_ticks_position('none') self._wrap_locator_formatter() def _set_scale(self, value, **kwargs): if value != 'linear': raise NotImplementedError('The xscale cannot be set on a polar plot') super()._set_scale(value, **kwargs) self.get_major_locator().set_params(steps=[1, 1.5, 3, 4.5, 9, 10]) self._wrap_locator_formatter() def _copy_tick_props(self, src, dest): if src is None or dest is None: return super()._copy_tick_props(src, dest) trans = dest._get_text1_transform()[0] dest.label1.set_transform(trans + dest._text1_translate) trans = dest._get_text2_transform()[0] dest.label2.set_transform(trans + dest._text2_translate) class RadialLocator(mticker.Locator): def __init__(self, base, axes=None): self.base = base self._axes = axes def set_axis(self, axis): self.base.set_axis(axis) def __call__(self): if self._axes: if _is_full_circle_rad(*self._axes.viewLim.intervalx): rorigin = self._axes.get_rorigin() * self._axes.get_rsign() if self._axes.get_rmin() <= rorigin: return [tick for tick in self.base() if tick > rorigin] return self.base() def _zero_in_bounds(self): (vmin, vmax) = self._axes.yaxis._scale.limit_range_for_scale(0, 1, 1e-05) return vmin == 0 def nonsingular(self, vmin, vmax): if self._zero_in_bounds() and (vmin, vmax) == (-np.inf, np.inf): return (0, 1) else: return self.base.nonsingular(vmin, vmax) def view_limits(self, vmin, vmax): (vmin, vmax) = self.base.view_limits(vmin, vmax) if self._zero_in_bounds() and vmax > vmin: vmin = min(0, vmin) return mtransforms.nonsingular(vmin, vmax) class _ThetaShift(mtransforms.ScaledTranslation): def __init__(self, axes, pad, mode): super().__init__(pad, pad, axes.get_figure(root=False).dpi_scale_trans) self.set_children(axes._realViewLim) self.axes = axes self.mode = mode self.pad = pad __str__ = mtransforms._make_str_method('axes', 'pad', 'mode') def get_matrix(self): if self._invalid: if self.mode == 'rlabel': angle = np.deg2rad(self.axes.get_rlabel_position() * self.axes.get_theta_direction()) + self.axes.get_theta_offset() - np.pi / 2 elif self.mode == 'min': angle = self.axes._realViewLim.xmin - np.pi / 2 elif self.mode == 'max': angle = self.axes._realViewLim.xmax + np.pi / 2 self._t = (self.pad * np.cos(angle) / 72, self.pad * np.sin(angle) / 72) return super().get_matrix() class RadialTick(maxis.YTick): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label1.set_rotation_mode('anchor') self.label2.set_rotation_mode('anchor') def _determine_anchor(self, mode, angle, start): if mode == 'auto': if start: if -90 <= angle <= 90: return ('left', 'center') else: return ('right', 'center') elif -90 <= angle <= 90: return ('right', 'center') else: return ('left', 'center') elif start: if angle < -68.5: return ('center', 'top') elif angle < -23.5: return ('left', 'top') elif angle < 22.5: return ('left', 'center') elif angle < 67.5: return ('left', 'bottom') elif angle < 112.5: return ('center', 'bottom') elif angle < 157.5: return ('right', 'bottom') elif angle < 202.5: return ('right', 'center') elif angle < 247.5: return ('right', 'top') else: return ('center', 'top') elif angle < -68.5: return ('center', 'bottom') elif angle < -23.5: return ('right', 'bottom') elif angle < 22.5: return ('right', 'center') elif angle < 67.5: return ('right', 'top') elif angle < 112.5: return ('center', 'top') elif angle < 157.5: return ('left', 'top') elif angle < 202.5: return ('left', 'center') elif angle < 247.5: return ('left', 'bottom') else: return ('center', 'bottom') def update_position(self, loc): super().update_position(loc) axes = self.axes thetamin = axes.get_thetamin() thetamax = axes.get_thetamax() direction = axes.get_theta_direction() offset_rad = axes.get_theta_offset() offset = np.rad2deg(offset_rad) full = _is_full_circle_deg(thetamin, thetamax) if full: angle = (axes.get_rlabel_position() * direction + offset) % 360 - 90 tick_angle = 0 else: angle = (thetamin * direction + offset) % 360 - 90 if direction > 0: tick_angle = np.deg2rad(angle) else: tick_angle = np.deg2rad(angle + 180) text_angle = (angle + 90) % 180 - 90 (mode, user_angle) = self._labelrotation if mode == 'auto': text_angle += user_angle else: text_angle = user_angle if full: ha = self.label1.get_horizontalalignment() va = self.label1.get_verticalalignment() else: (ha, va) = self._determine_anchor(mode, angle, direction > 0) self.label1.set_horizontalalignment(ha) self.label1.set_verticalalignment(va) self.label1.set_rotation(text_angle) marker = self.tick1line.get_marker() if marker == mmarkers.TICKLEFT: trans = mtransforms.Affine2D().rotate(tick_angle) elif marker == '_': trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2) elif marker == mmarkers.TICKRIGHT: trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle) else: trans = self.tick1line._marker._transform self.tick1line._marker._transform = trans if full: self.label2.set_visible(False) self.tick2line.set_visible(False) angle = (thetamax * direction + offset) % 360 - 90 if direction > 0: tick_angle = np.deg2rad(angle) else: tick_angle = np.deg2rad(angle + 180) text_angle = (angle + 90) % 180 - 90 (mode, user_angle) = self._labelrotation if mode == 'auto': text_angle += user_angle else: text_angle = user_angle (ha, va) = self._determine_anchor(mode, angle, direction < 0) self.label2.set_ha(ha) self.label2.set_va(va) self.label2.set_rotation(text_angle) marker = self.tick2line.get_marker() if marker == mmarkers.TICKLEFT: trans = mtransforms.Affine2D().rotate(tick_angle) elif marker == '_': trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2) elif marker == mmarkers.TICKRIGHT: trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle) else: trans = self.tick2line._marker._transform self.tick2line._marker._transform = trans class RadialAxis(maxis.YAxis): __name__ = 'radialaxis' axis_name = 'radius' _tick_class = RadialTick def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sticky_edges.y.append(0) def _wrap_locator_formatter(self): self.set_major_locator(RadialLocator(self.get_major_locator(), self.axes)) self.isDefault_majloc = True def clear(self): super().clear() self.set_ticks_position('none') self._wrap_locator_formatter() def _set_scale(self, value, **kwargs): super()._set_scale(value, **kwargs) self._wrap_locator_formatter() def _is_full_circle_deg(thetamin, thetamax): return abs(abs(thetamax - thetamin) - 360.0) < 1e-12 def _is_full_circle_rad(thetamin, thetamax): return abs(abs(thetamax - thetamin) - 2 * np.pi) < 1.74e-14 class _WedgeBbox(mtransforms.Bbox): def __init__(self, center, viewLim, originLim, **kwargs): super().__init__([[0, 0], [1, 1]], **kwargs) self._center = center self._viewLim = viewLim self._originLim = originLim self.set_children(viewLim, originLim) __str__ = mtransforms._make_str_method('_center', '_viewLim', '_originLim') def get_points(self): if self._invalid: points = self._viewLim.get_points().copy() points[:, 0] *= 180 / np.pi if points[0, 0] > points[1, 0]: points[:, 0] = points[::-1, 0] points[:, 1] -= self._originLim.y0 rscale = 0.5 / points[1, 1] points[:, 1] *= rscale width = min(points[1, 1] - points[0, 1], 0.5) wedge = mpatches.Wedge(self._center, points[1, 1], points[0, 0], points[1, 0], width=width) self.update_from_path(wedge.get_path()) (w, h) = self._points[1] - self._points[0] deltah = max(w - h, 0) / 2 deltaw = max(h - w, 0) / 2 self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]]) self._invalid = 0 return self._points class PolarAxes(Axes): name = 'polar' def __init__(self, *args, theta_offset=0, theta_direction=1, rlabel_position=22.5, **kwargs): self._default_theta_offset = theta_offset self._default_theta_direction = theta_direction self._default_rlabel_position = np.deg2rad(rlabel_position) super().__init__(*args, **kwargs) self.use_sticky_edges = True self.set_aspect('equal', adjustable='box', anchor='C') self.clear() def clear(self): super().clear() self.title.set_y(1.05) start = self.spines.get('start', None) if start: start.set_visible(False) end = self.spines.get('end', None) if end: end.set_visible(False) self.set_xlim(0.0, 2 * np.pi) self.grid(mpl.rcParams['polaraxes.grid']) inner = self.spines.get('inner', None) if inner: inner.set_visible(False) self.set_rorigin(None) self.set_theta_offset(self._default_theta_offset) self.set_theta_direction(self._default_theta_direction) def _init_axis(self): self.xaxis = ThetaAxis(self, clear=False) self.yaxis = RadialAxis(self, clear=False) self.spines['polar'].register_axis(self.yaxis) def _set_lim_and_transforms(self): self._originViewLim = mtransforms.LockableBbox(self.viewLim) self._direction = mtransforms.Affine2D().scale(self._default_theta_direction, 1.0) self._theta_offset = mtransforms.Affine2D().translate(self._default_theta_offset, 0.0) self.transShift = self._direction + self._theta_offset self._realViewLim = mtransforms.TransformedBbox(self.viewLim, self.transShift) self.transScale = mtransforms.TransformWrapper(mtransforms.IdentityTransform()) self.axesLim = _WedgeBbox((0.5, 0.5), self._realViewLim, self._originViewLim) self.transWedge = mtransforms.BboxTransformFrom(self.axesLim) self.transAxes = mtransforms.BboxTransformTo(self.bbox) self.transProjection = self.PolarTransform(self, apply_theta_transforms=False, scale_transform=self.transScale) self.transProjection.set_children(self._originViewLim) self.transProjectionAffine = self.PolarAffine(self.transScale, self._originViewLim) self.transData = self.transScale + self.transShift + self.transProjection + (self.transProjectionAffine + self.transWedge + self.transAxes) self._xaxis_transform = mtransforms.blended_transform_factory(mtransforms.IdentityTransform(), mtransforms.BboxTransformTo(self.viewLim)) + self.transData flipr_transform = mtransforms.Affine2D().translate(0.0, -0.5).scale(1.0, -1.0).translate(0.0, 0.5) self._xaxis_text_transform = flipr_transform + self._xaxis_transform self._yaxis_transform = mtransforms.blended_transform_factory(mtransforms.BboxTransformTo(self.viewLim), mtransforms.IdentityTransform()) + self.transData self._r_label_position = mtransforms.Affine2D().translate(self._default_rlabel_position, 0.0) self._yaxis_text_transform = mtransforms.TransformWrapper(self._r_label_position + self.transData) def get_xaxis_transform(self, which='grid'): _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return (self._xaxis_text_transform, 'center', 'center') def get_xaxis_text2_transform(self, pad): return (self._xaxis_text_transform, 'center', 'center') def get_yaxis_transform(self, which='grid'): if which in ('tick1', 'tick2'): return self._yaxis_text_transform elif which == 'grid': return self._yaxis_transform else: _api.check_in_list(['tick1', 'tick2', 'grid'], which=which) def get_yaxis_text1_transform(self, pad): (thetamin, thetamax) = self._realViewLim.intervalx if _is_full_circle_rad(thetamin, thetamax): return (self._yaxis_text_transform, 'bottom', 'left') elif self.get_theta_direction() > 0: halign = 'left' pad_shift = _ThetaShift(self, pad, 'min') else: halign = 'right' pad_shift = _ThetaShift(self, pad, 'max') return (self._yaxis_text_transform + pad_shift, 'center', halign) def get_yaxis_text2_transform(self, pad): if self.get_theta_direction() > 0: halign = 'right' pad_shift = _ThetaShift(self, pad, 'max') else: halign = 'left' pad_shift = _ThetaShift(self, pad, 'min') return (self._yaxis_text_transform + pad_shift, 'center', halign) def draw(self, renderer): self._unstale_viewLim() (thetamin, thetamax) = np.rad2deg(self._realViewLim.intervalx) if thetamin > thetamax: (thetamin, thetamax) = (thetamax, thetamin) (rmin, rmax) = (self._realViewLim.intervaly - self.get_rorigin()) * self.get_rsign() if isinstance(self.patch, mpatches.Wedge): center = self.transWedge.transform((0.5, 0.5)) self.patch.set_center(center) self.patch.set_theta1(thetamin) self.patch.set_theta2(thetamax) (edge, _) = self.transWedge.transform((1, 0)) radius = edge - center[0] width = min(radius * (rmax - rmin) / rmax, radius) self.patch.set_radius(radius) self.patch.set_width(width) inner_width = radius - width inner = self.spines.get('inner', None) if inner: inner.set_visible(inner_width != 0.0) visible = not _is_full_circle_deg(thetamin, thetamax) start = self.spines.get('start', None) end = self.spines.get('end', None) if start: start.set_visible(visible) if end: end.set_visible(visible) if visible: yaxis_text_transform = self._yaxis_transform else: yaxis_text_transform = self._r_label_position + self.transData if self._yaxis_text_transform != yaxis_text_transform: self._yaxis_text_transform.set(yaxis_text_transform) self.yaxis.reset_ticks() self.yaxis.set_clip_path(self.patch) super().draw(renderer) def _gen_axes_patch(self): return mpatches.Wedge((0.5, 0.5), 0.5, 0.0, 360.0) def _gen_axes_spines(self): spines = {'polar': Spine.arc_spine(self, 'top', (0.5, 0.5), 0.5, 0, 360), 'start': Spine.linear_spine(self, 'left'), 'end': Spine.linear_spine(self, 'right'), 'inner': Spine.arc_spine(self, 'bottom', (0.5, 0.5), 0.0, 0, 360)} spines['polar'].set_transform(self.transWedge + self.transAxes) spines['inner'].set_transform(self.transWedge + self.transAxes) spines['start'].set_transform(self._yaxis_transform) spines['end'].set_transform(self._yaxis_transform) return spines def set_thetamax(self, thetamax): self.viewLim.x1 = np.deg2rad(thetamax) def get_thetamax(self): return np.rad2deg(self.viewLim.xmax) def set_thetamin(self, thetamin): self.viewLim.x0 = np.deg2rad(thetamin) def get_thetamin(self): return np.rad2deg(self.viewLim.xmin) def set_thetalim(self, *args, **kwargs): orig_lim = self.get_xlim() if 'thetamin' in kwargs: kwargs['xmin'] = np.deg2rad(kwargs.pop('thetamin')) if 'thetamax' in kwargs: kwargs['xmax'] = np.deg2rad(kwargs.pop('thetamax')) (new_min, new_max) = self.set_xlim(*args, **kwargs) if abs(new_max - new_min) > 2 * np.pi: self.set_xlim(orig_lim) raise ValueError('The angle range must be less than a full circle') return tuple(np.rad2deg((new_min, new_max))) def set_theta_offset(self, offset): mtx = self._theta_offset.get_matrix() mtx[0, 2] = offset self._theta_offset.invalidate() def get_theta_offset(self): return self._theta_offset.get_matrix()[0, 2] def set_theta_zero_location(self, loc, offset=0.0): mapping = {'N': np.pi * 0.5, 'NW': np.pi * 0.75, 'W': np.pi, 'SW': np.pi * 1.25, 'S': np.pi * 1.5, 'SE': np.pi * 1.75, 'E': 0, 'NE': np.pi * 0.25} return self.set_theta_offset(mapping[loc] + np.deg2rad(offset)) def set_theta_direction(self, direction): mtx = self._direction.get_matrix() if direction in ('clockwise', -1): mtx[0, 0] = -1 elif direction in ('counterclockwise', 'anticlockwise', 1): mtx[0, 0] = 1 else: _api.check_in_list([-1, 1, 'clockwise', 'counterclockwise', 'anticlockwise'], direction=direction) self._direction.invalidate() def get_theta_direction(self): return self._direction.get_matrix()[0, 0] def set_rmax(self, rmax): self.viewLim.y1 = rmax def get_rmax(self): return self.viewLim.ymax def set_rmin(self, rmin): self.viewLim.y0 = rmin def get_rmin(self): return self.viewLim.ymin def set_rorigin(self, rorigin): self._originViewLim.locked_y0 = rorigin def get_rorigin(self): return self._originViewLim.y0 def get_rsign(self): return np.sign(self._originViewLim.y1 - self._originViewLim.y0) def set_rlim(self, bottom=None, top=None, *, emit=True, auto=False, **kwargs): if 'rmin' in kwargs: if bottom is None: bottom = kwargs.pop('rmin') else: raise ValueError('Cannot supply both positional "bottom"argument and kwarg "rmin"') if 'rmax' in kwargs: if top is None: top = kwargs.pop('rmax') else: raise ValueError('Cannot supply both positional "top"argument and kwarg "rmax"') return self.set_ylim(bottom=bottom, top=top, emit=emit, auto=auto, **kwargs) def get_rlabel_position(self): return np.rad2deg(self._r_label_position.get_matrix()[0, 2]) def set_rlabel_position(self, value): self._r_label_position.clear().translate(np.deg2rad(value), 0.0) def set_yscale(self, *args, **kwargs): super().set_yscale(*args, **kwargs) self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator(), self)) def set_rscale(self, *args, **kwargs): return Axes.set_yscale(self, *args, **kwargs) def set_rticks(self, *args, **kwargs): return Axes.set_yticks(self, *args, **kwargs) def set_thetagrids(self, angles, labels=None, fmt=None, **kwargs): angles = self.convert_yunits(angles) angles = np.deg2rad(angles) self.set_xticks(angles) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(mticker.FormatStrFormatter(fmt)) for t in self.xaxis.get_ticklabels(): t._internal_update(kwargs) return (self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()) def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): radii = self.convert_xunits(radii) radii = np.asarray(radii) self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt)) if angle is None: angle = self.get_rlabel_position() self.set_rlabel_position(angle) for t in self.yaxis.get_ticklabels(): t._internal_update(kwargs) return (self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()) def format_coord(self, theta, r): screen_xy = self.transData.transform((theta, r)) screen_xys = screen_xy + np.stack(np.meshgrid([-1, 0, 1], [-1, 0, 1])).reshape((2, -1)).T (ts, rs) = self.transData.inverted().transform(screen_xys).T delta_t = abs((ts - theta + np.pi) % (2 * np.pi) - np.pi).max() delta_t_halfturns = delta_t / np.pi delta_t_degrees = delta_t_halfturns * 180 delta_r = abs(rs - r).max() if theta < 0: theta += 2 * np.pi theta_halfturns = theta / np.pi theta_degrees = theta_halfturns * 180 def format_sig(value, delta, opt, fmt): prec = max(0, -math.floor(math.log10(delta))) if fmt == 'f' else cbook._g_sig_digits(value, delta) return f'{value:-{opt}.{prec}{fmt}}' if self.fmt_ydata is None: r_label = format_sig(r, delta_r, '#', 'g') else: r_label = self.format_ydata(r) if self.fmt_xdata is None: return 'θ={}π ({}°), r={}'.format(format_sig(theta_halfturns, delta_t_halfturns, '', 'f'), format_sig(theta_degrees, delta_t_degrees, '', 'f'), r_label) else: return 'θ={}, r={}'.format(self.format_xdata(theta), r_label) def get_data_ratio(self): return 1.0 def can_zoom(self): return False def can_pan(self): return True def start_pan(self, x, y, button): angle = np.deg2rad(self.get_rlabel_position()) mode = '' if button == 1: epsilon = np.pi / 45.0 (t, r) = self.transData.inverted().transform((x, y)) if angle - epsilon <= t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = types.SimpleNamespace(rmax=self.get_rmax(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), r_label_angle=self.get_rlabel_position(), x=x, y=y, mode=mode) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': ((startt, startr), (t, r)) = p.trans_inverse.transform([(p.x, p.y), (x, y)]) dt = np.rad2deg(startt - t) self.set_rlabel_position(p.r_label_angle - dt) (trans, vert1, horiz1) = self.get_yaxis_text1_transform(0.0) (trans, vert2, horiz2) = self.get_yaxis_text2_transform(0.0) for t in self.yaxis.majorTicks + self.yaxis.minorTicks: t.label1.set_va(vert1) t.label1.set_ha(horiz1) t.label2.set_va(vert2) t.label2.set_ha(horiz2) elif p.mode == 'zoom': ((startt, startr), (t, r)) = p.trans_inverse.transform([(p.x, p.y), (x, y)]) scale = r / startr self.set_rmax(p.rmax / scale) PolarAxes.PolarTransform = PolarTransform PolarAxes.PolarAffine = PolarAffine PolarAxes.InvertedPolarTransform = InvertedPolarTransform PolarAxes.ThetaFormatter = ThetaFormatter PolarAxes.RadialLocator = RadialLocator PolarAxes.ThetaLocator = ThetaLocator # File: matplotlib-main/lib/matplotlib/pylab.py """""" from matplotlib.cbook import flatten, silent_list import matplotlib as mpl from matplotlib.dates import date2num, num2date, datestr2num, drange, DateFormatter, DateLocator, RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator, HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, relativedelta from matplotlib.mlab import detrend, detrend_linear, detrend_mean, detrend_none, window_hanning, window_none from matplotlib import cbook, mlab, pyplot as plt from matplotlib.pyplot import * from numpy import * from numpy.fft import * from numpy.random import * from numpy.linalg import * import numpy as np import numpy.ma as ma import datetime bytes = __import__('builtins').bytes abs = __import__('builtins').abs bool = __import__('builtins').bool max = __import__('builtins').max min = __import__('builtins').min pow = __import__('builtins').pow round = __import__('builtins').round # File: matplotlib-main/lib/matplotlib/pyplot.py """""" from __future__ import annotations from contextlib import AbstractContextManager, ExitStack from enum import Enum import functools import importlib import inspect import logging import sys import threading import time from typing import TYPE_CHECKING, cast, overload from cycler import cycler import matplotlib import matplotlib.colorbar import matplotlib.image from matplotlib import _api from matplotlib import cm as cm, get_backend as get_backend, rcParams as rcParams from matplotlib import style as style from matplotlib import _pylab_helpers from matplotlib import interactive from matplotlib import cbook from matplotlib import _docstring from matplotlib.backend_bases import FigureCanvasBase, FigureManagerBase, MouseButton from matplotlib.figure import Figure, FigureBase, figaspect from matplotlib.gridspec import GridSpec, SubplotSpec from matplotlib import rcsetup, rcParamsDefault, rcParamsOrig from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.axes import Subplot from matplotlib.backends import BackendFilter, backend_registry from matplotlib.projections import PolarAxes from matplotlib import mlab from matplotlib.scale import get_scale_names from matplotlib.cm import _colormaps from matplotlib.colors import _color_sequences, Colormap import numpy as np if TYPE_CHECKING: from collections.abc import Callable, Hashable, Iterable, Sequence import datetime import pathlib import os from typing import Any, BinaryIO, Literal, TypeVar from typing_extensions import ParamSpec import PIL.Image from numpy.typing import ArrayLike import matplotlib.axes import matplotlib.artist import matplotlib.backend_bases from matplotlib.axis import Tick from matplotlib.axes._base import _AxesBase from matplotlib.backend_bases import RendererBase, Event from matplotlib.cm import ScalarMappable from matplotlib.contour import ContourSet, QuadContourSet from matplotlib.collections import Collection, LineCollection, PolyCollection, PathCollection, EventCollection, QuadMesh from matplotlib.colorbar import Colorbar from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer from matplotlib.figure import SubFigure from matplotlib.legend import Legend from matplotlib.mlab import GaussianKDE from matplotlib.image import AxesImage, FigureImage from matplotlib.patches import FancyArrow, StepPatch, Wedge from matplotlib.quiver import Barbs, Quiver, QuiverKey from matplotlib.scale import ScaleBase from matplotlib.transforms import Transform, Bbox from matplotlib.typing import ColorType, LineStyleType, MarkerType, HashableList from matplotlib.widgets import SubplotTool _P = ParamSpec('_P') _R = TypeVar('_R') _T = TypeVar('_T') from matplotlib.colors import Normalize from matplotlib.lines import Line2D, AxLine from matplotlib.text import Text, Annotation from matplotlib.patches import Arrow, Circle, Rectangle from matplotlib.patches import Polygon from matplotlib.widgets import Button, Slider, Widget from .ticker import TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter, FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent, LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator, LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator _log = logging.getLogger(__name__) colormaps = _colormaps color_sequences = _color_sequences @overload def _copy_docstring_and_deprecators(method: Any, func: Literal[None]=None) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... @overload def _copy_docstring_and_deprecators(method: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: ... def _copy_docstring_and_deprecators(method: Any, func: Callable[_P, _R] | None=None) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[_P, _R]: if func is None: return cast('Callable[[Callable[_P, _R]], Callable[_P, _R]]', functools.partial(_copy_docstring_and_deprecators, method)) decorators: list[Callable[[Callable[_P, _R]], Callable[_P, _R]]] = [_docstring.copy(method)] while hasattr(method, '__wrapped__'): potential_decorator = _api.deprecation.DECORATORS.get(method) if potential_decorator: decorators.append(potential_decorator) method = method.__wrapped__ for decorator in decorators[::-1]: func = decorator(func) _add_pyplot_note(func, method) return func _NO_PYPLOT_NOTE = ['FigureBase._gci', '_AxesBase._sci', 'Artist.findobj'] def _add_pyplot_note(func, wrapped_func): if not func.__doc__: return qualname = wrapped_func.__qualname__ if qualname in _NO_PYPLOT_NOTE: return wrapped_func_is_method = True if '.' not in qualname: wrapped_func_is_method = False link = f'{wrapped_func.__module__}.{qualname}' elif qualname.startswith('Axes.'): link = '.axes.' + qualname elif qualname.startswith('_AxesBase.'): link = '.axes.Axes' + qualname[9:] elif qualname.startswith('Figure.'): link = '.' + qualname elif qualname.startswith('FigureBase.'): link = '.Figure' + qualname[10:] elif qualname.startswith('FigureCanvasBase.'): link = '.' + qualname else: raise RuntimeError(f'Wrapped method from unexpected class: {qualname}') if wrapped_func_is_method: message = f'This is the :ref:`pyplot wrapper ` for `{link}`.' else: message = f'This is equivalent to `{link}`.' doc = inspect.cleandoc(func.__doc__) if '\nNotes\n-----' in doc: (before, after) = doc.split('\nNotes\n-----', 1) elif (index := doc.find('\nReferences\n----------')) != -1: (before, after) = (doc[:index], doc[index:]) elif (index := doc.find('\nExamples\n--------')) != -1: (before, after) = (doc[:index], doc[index:]) else: before = doc + '\n' after = '' func.__doc__ = f'{before}\nNotes\n-----\n\n.. note::\n\n {message}\n{after}' _ReplDisplayHook = Enum('_ReplDisplayHook', ['NONE', 'PLAIN', 'IPYTHON']) _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE def _draw_all_if_interactive() -> None: if matplotlib.is_interactive(): draw_all() def install_repl_displayhook() -> None: global _REPL_DISPLAYHOOK if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON: return mod_ipython = sys.modules.get('IPython') if not mod_ipython: _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN return ip = mod_ipython.get_ipython() if not ip: _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN return ip.events.register('post_execute', _draw_all_if_interactive) _REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON if mod_ipython.version_info[:2] < (8, 24): from IPython.core.pylabtools import backend2gui ipython_gui_name = backend2gui.get(get_backend()) else: (_, ipython_gui_name) = backend_registry.resolve_backend(get_backend()) if ipython_gui_name: ip.enable_gui(ipython_gui_name) def uninstall_repl_displayhook() -> None: global _REPL_DISPLAYHOOK if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON: from IPython import get_ipython ip = get_ipython() ip.events.unregister('post_execute', _draw_all_if_interactive) _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE draw_all = _pylab_helpers.Gcf.draw_all @_copy_docstring_and_deprecators(matplotlib.set_loglevel) def set_loglevel(*args, **kwargs) -> None: return matplotlib.set_loglevel(*args, **kwargs) @_copy_docstring_and_deprecators(Artist.findobj) def findobj(o: Artist | None=None, match: Callable[[Artist], bool] | type[Artist] | None=None, include_self: bool=True) -> list[Artist]: if o is None: o = gcf() return o.findobj(match, include_self=include_self) _backend_mod: type[matplotlib.backend_bases._Backend] | None = None def _get_backend_mod() -> type[matplotlib.backend_bases._Backend]: if _backend_mod is None: switch_backend(rcParams._get('backend')) return cast(type[matplotlib.backend_bases._Backend], _backend_mod) def switch_backend(newbackend: str) -> None: global _backend_mod import matplotlib.backends if newbackend is rcsetup._auto_backend_sentinel: current_framework = cbook._get_running_interactive_framework() if current_framework and (backend := backend_registry.backend_for_gui_framework(current_framework)): candidates = [backend] else: candidates = [] candidates += ['macosx', 'qtagg', 'gtk4agg', 'gtk3agg', 'tkagg', 'wxagg'] for candidate in candidates: try: switch_backend(candidate) except ImportError: continue else: rcParamsOrig['backend'] = candidate return else: switch_backend('agg') rcParamsOrig['backend'] = 'agg' return old_backend = rcParams._get('backend') module = backend_registry.load_backend_module(newbackend) canvas_class = module.FigureCanvas required_framework = canvas_class.required_interactive_framework if required_framework is not None: current_framework = cbook._get_running_interactive_framework() if current_framework and required_framework and (current_framework != required_framework): raise ImportError('Cannot load backend {!r} which requires the {!r} interactive framework, as {!r} is currently running'.format(newbackend, required_framework, current_framework)) new_figure_manager = getattr(module, 'new_figure_manager', None) show = getattr(module, 'show', None) class backend_mod(matplotlib.backend_bases._Backend): locals().update(vars(module)) if new_figure_manager is None: def new_figure_manager_given_figure(num, figure): return canvas_class.new_manager(figure, num) def new_figure_manager(num, *args, FigureClass=Figure, **kwargs): fig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, fig) def draw_if_interactive() -> None: if matplotlib.is_interactive(): manager = _pylab_helpers.Gcf.get_active() if manager: manager.canvas.draw_idle() backend_mod.new_figure_manager_given_figure = new_figure_manager_given_figure backend_mod.new_figure_manager = new_figure_manager backend_mod.draw_if_interactive = draw_if_interactive manager_class = getattr(canvas_class, 'manager_class', None) manager_pyplot_show = inspect.getattr_static(manager_class, 'pyplot_show', None) base_pyplot_show = inspect.getattr_static(FigureManagerBase, 'pyplot_show', None) if show is None or (manager_pyplot_show is not None and manager_pyplot_show != base_pyplot_show): if not manager_pyplot_show: raise ValueError(f'Backend {newbackend} defines neither FigureCanvas.manager_class nor a toplevel show function') _pyplot_show = cast('Any', manager_class).pyplot_show backend_mod.show = _pyplot_show _log.debug('Loaded backend %s version %s.', newbackend, backend_mod.backend_version) if newbackend in ('ipympl', 'widget'): import importlib.metadata as im from matplotlib import _parse_to_version_info try: module_version = im.version('ipympl') if _parse_to_version_info(module_version) < (0, 9, 4): newbackend = 'module://ipympl.backend_nbagg' except im.PackageNotFoundError: pass rcParams['backend'] = rcParamsDefault['backend'] = newbackend _backend_mod = backend_mod for func_name in ['new_figure_manager', 'draw_if_interactive', 'show']: globals()[func_name].__signature__ = inspect.signature(getattr(backend_mod, func_name)) matplotlib.backends.backend = newbackend if not cbook._str_equal(old_backend, newbackend): if get_fignums(): _api.warn_deprecated('3.8', message="Auto-close()ing of figures upon backend switching is deprecated since %(since)s and will be removed %(removal)s. To suppress this warning, explicitly call plt.close('all') first.") close('all') install_repl_displayhook() def _warn_if_gui_out_of_main_thread() -> None: warn = False canvas_class = cast(type[FigureCanvasBase], _get_backend_mod().FigureCanvas) if canvas_class.required_interactive_framework: if hasattr(threading, 'get_native_id'): if threading.get_native_id() != threading.main_thread().native_id: warn = True elif threading.current_thread() is not threading.main_thread(): warn = True if warn: _api.warn_external('Starting a Matplotlib GUI outside of the main thread will likely fail.') def new_figure_manager(*args, **kwargs): _warn_if_gui_out_of_main_thread() return _get_backend_mod().new_figure_manager(*args, **kwargs) def draw_if_interactive(*args, **kwargs): return _get_backend_mod().draw_if_interactive(*args, **kwargs) def show(*args, **kwargs) -> None: _warn_if_gui_out_of_main_thread() return _get_backend_mod().show(*args, **kwargs) def isinteractive() -> bool: return matplotlib.is_interactive() def ioff() -> AbstractContextManager: stack = ExitStack() stack.callback(ion if isinteractive() else ioff) matplotlib.interactive(False) uninstall_repl_displayhook() return stack def ion() -> AbstractContextManager: stack = ExitStack() stack.callback(ion if isinteractive() else ioff) matplotlib.interactive(True) install_repl_displayhook() return stack def pause(interval: float) -> None: manager = _pylab_helpers.Gcf.get_active() if manager is not None: canvas = manager.canvas if canvas.figure.stale: canvas.draw_idle() show(block=False) canvas.start_event_loop(interval) else: time.sleep(interval) @_copy_docstring_and_deprecators(matplotlib.rc) def rc(group: str, **kwargs) -> None: matplotlib.rc(group, **kwargs) @_copy_docstring_and_deprecators(matplotlib.rc_context) def rc_context(rc: dict[str, Any] | None=None, fname: str | pathlib.Path | os.PathLike | None=None) -> AbstractContextManager[None]: return matplotlib.rc_context(rc, fname) @_copy_docstring_and_deprecators(matplotlib.rcdefaults) def rcdefaults() -> None: matplotlib.rcdefaults() if matplotlib.is_interactive(): draw_all() @_copy_docstring_and_deprecators(matplotlib.artist.getp) def getp(obj, *args, **kwargs): return matplotlib.artist.getp(obj, *args, **kwargs) @_copy_docstring_and_deprecators(matplotlib.artist.get) def get(obj, *args, **kwargs): return matplotlib.artist.get(obj, *args, **kwargs) @_copy_docstring_and_deprecators(matplotlib.artist.setp) def setp(obj, *args, **kwargs): return matplotlib.artist.setp(obj, *args, **kwargs) def xkcd(scale: float=1, length: float=100, randomness: float=2) -> ExitStack: if rcParams['text.usetex']: raise RuntimeError('xkcd mode is not compatible with text.usetex = True') stack = ExitStack() stack.callback(rcParams._update_raw, rcParams.copy()) from matplotlib import patheffects rcParams.update({'font.family': ['xkcd', 'xkcd Script', 'Comic Neue', 'Comic Sans MS'], 'font.size': 14.0, 'path.sketch': (scale, length, randomness), 'path.effects': [patheffects.withStroke(linewidth=4, foreground='w')], 'axes.linewidth': 1.5, 'lines.linewidth': 2.0, 'figure.facecolor': 'white', 'grid.linewidth': 0.0, 'axes.grid': False, 'axes.unicode_minus': False, 'axes.edgecolor': 'black', 'xtick.major.size': 8, 'xtick.major.width': 3, 'ytick.major.size': 8, 'ytick.major.width': 3}) return stack def figure(num: int | str | Figure | SubFigure | None=None, figsize: tuple[float, float] | None=None, dpi: float | None=None, *, facecolor: ColorType | None=None, edgecolor: ColorType | None=None, frameon: bool=True, FigureClass: type[Figure]=Figure, clear: bool=False, **kwargs) -> Figure: allnums = get_fignums() if isinstance(num, FigureBase): root_fig = num.get_figure(root=True) if root_fig.canvas.manager is None: raise ValueError('The passed figure is not managed by pyplot') elif any([figsize, dpi, facecolor, edgecolor, not frameon, kwargs]) and root_fig.canvas.manager.num in allnums: _api.warn_external(f'Ignoring specified arguments in this call because figure with num: {root_fig.canvas.manager.num} already exists') _pylab_helpers.Gcf.set_active(root_fig.canvas.manager) return root_fig next_num = max(allnums) + 1 if allnums else 1 fig_label = '' if num is None: num = next_num else: if any([figsize, dpi, facecolor, edgecolor, not frameon, kwargs]) and num in allnums: _api.warn_external(f'Ignoring specified arguments in this call because figure with num: {num} already exists') if isinstance(num, str): fig_label = num all_labels = get_figlabels() if fig_label not in all_labels: if fig_label == 'all': _api.warn_external("close('all') closes all existing figures.") num = next_num else: inum = all_labels.index(fig_label) num = allnums[inum] else: num = int(num) manager = _pylab_helpers.Gcf.get_fig_manager(num) if manager is None: max_open_warning = rcParams['figure.max_open_warning'] if len(allnums) == max_open_warning >= 1: _api.warn_external(f'More than {max_open_warning} figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). Consider using `matplotlib.pyplot.close()`.', RuntimeWarning) manager = new_figure_manager(num, figsize=figsize, dpi=dpi, facecolor=facecolor, edgecolor=edgecolor, frameon=frameon, FigureClass=FigureClass, **kwargs) fig = manager.canvas.figure if fig_label: fig.set_label(fig_label) for hookspecs in rcParams['figure.hooks']: (module_name, dotted_name) = hookspecs.split(':') obj: Any = importlib.import_module(module_name) for part in dotted_name.split('.'): obj = getattr(obj, part) obj(fig) _pylab_helpers.Gcf._set_new_active_manager(manager) draw_if_interactive() if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN: fig.stale_callback = _auto_draw_if_interactive if clear: manager.canvas.figure.clear() return manager.canvas.figure def _auto_draw_if_interactive(fig, val): if val and matplotlib.is_interactive() and (not fig.canvas.is_saving()) and (not fig.canvas._is_idle_drawing): with fig.canvas._idle_draw_cntx(): fig.canvas.draw_idle() def gcf() -> Figure: manager = _pylab_helpers.Gcf.get_active() if manager is not None: return manager.canvas.figure else: return figure() def fignum_exists(num: int | str) -> bool: return _pylab_helpers.Gcf.has_fignum(num) if isinstance(num, int) else num in get_figlabels() def get_fignums() -> list[int]: return sorted(_pylab_helpers.Gcf.figs) def get_figlabels() -> list[Any]: managers = _pylab_helpers.Gcf.get_all_fig_managers() managers.sort(key=lambda m: m.num) return [m.canvas.figure.get_label() for m in managers] def get_current_fig_manager() -> FigureManagerBase | None: return gcf().canvas.manager @_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect) def connect(s: str, func: Callable[[Event], Any]) -> int: return gcf().canvas.mpl_connect(s, func) @_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect) def disconnect(cid: int) -> None: gcf().canvas.mpl_disconnect(cid) def close(fig: None | int | str | Figure | Literal['all']=None) -> None: if fig is None: manager = _pylab_helpers.Gcf.get_active() if manager is None: return else: _pylab_helpers.Gcf.destroy(manager) elif fig == 'all': _pylab_helpers.Gcf.destroy_all() elif isinstance(fig, int): _pylab_helpers.Gcf.destroy(fig) elif hasattr(fig, 'int'): _pylab_helpers.Gcf.destroy(fig.int) elif isinstance(fig, str): all_labels = get_figlabels() if fig in all_labels: num = get_fignums()[all_labels.index(fig)] _pylab_helpers.Gcf.destroy(num) elif isinstance(fig, Figure): _pylab_helpers.Gcf.destroy_fig(fig) else: raise TypeError('close() argument must be a Figure, an int, a string, or None, not %s' % type(fig)) def clf() -> None: gcf().clear() def draw() -> None: gcf().canvas.draw_idle() @_copy_docstring_and_deprecators(Figure.savefig) def savefig(*args, **kwargs) -> None: fig = gcf() res = fig.savefig(*args, **kwargs) fig.canvas.draw_idle() return res def figlegend(*args, **kwargs) -> Legend: return gcf().legend(*args, **kwargs) if Figure.legend.__doc__: figlegend.__doc__ = Figure.legend.__doc__.replace(' legend(', ' figlegend(').replace('fig.legend(', 'plt.figlegend(').replace('ax.plot(', 'plt.plot(') @_docstring.dedent_interpd def axes(arg: None | tuple[float, float, float, float]=None, **kwargs) -> matplotlib.axes.Axes: fig = gcf() pos = kwargs.pop('position', None) if arg is None: if pos is None: return fig.add_subplot(**kwargs) else: return fig.add_axes(pos, **kwargs) else: return fig.add_axes(arg, **kwargs) def delaxes(ax: matplotlib.axes.Axes | None=None) -> None: if ax is None: ax = gca() ax.remove() def sca(ax: Axes) -> None: fig = ax.get_figure(root=False) figure(fig) fig.sca(ax) def cla() -> None: return gca().cla() @_docstring.dedent_interpd def subplot(*args, **kwargs) -> Axes: unset = object() projection = kwargs.get('projection', unset) polar = kwargs.pop('polar', unset) if polar is not unset and polar: if projection is not unset and projection != 'polar': raise ValueError(f'polar={polar}, yet projection={projection!r}. Only one of these arguments should be supplied.') kwargs['projection'] = projection = 'polar' if len(args) == 0: args = (1, 1, 1) if len(args) >= 3 and isinstance(args[2], bool): _api.warn_external('The subplot index argument to subplot() appears to be a boolean. Did you intend to use subplots()?') if 'nrows' in kwargs or 'ncols' in kwargs: raise TypeError("subplot() got an unexpected keyword argument 'ncols' and/or 'nrows'. Did you intend to call subplots()?") fig = gcf() key = SubplotSpec._from_subplot_args(fig, args) for ax in fig.axes: if ax.get_subplotspec() == key and (kwargs == {} or ax._projection_init == fig._process_projection_requirements(**kwargs)): break else: ax = fig.add_subplot(*args, **kwargs) fig.sca(ax) return ax @overload def subplots(nrows: Literal[1]=..., ncols: Literal[1]=..., *, sharex: bool | Literal['none', 'all', 'row', 'col']=..., sharey: bool | Literal['none', 'all', 'row', 'col']=..., squeeze: Literal[True]=..., width_ratios: Sequence[float] | None=..., height_ratios: Sequence[float] | None=..., subplot_kw: dict[str, Any] | None=..., gridspec_kw: dict[str, Any] | None=..., **fig_kw) -> tuple[Figure, Axes]: ... @overload def subplots(nrows: int=..., ncols: int=..., *, sharex: bool | Literal['none', 'all', 'row', 'col']=..., sharey: bool | Literal['none', 'all', 'row', 'col']=..., squeeze: Literal[False], width_ratios: Sequence[float] | None=..., height_ratios: Sequence[float] | None=..., subplot_kw: dict[str, Any] | None=..., gridspec_kw: dict[str, Any] | None=..., **fig_kw) -> tuple[Figure, np.ndarray]: ... @overload def subplots(nrows: int=..., ncols: int=..., *, sharex: bool | Literal['none', 'all', 'row', 'col']=..., sharey: bool | Literal['none', 'all', 'row', 'col']=..., squeeze: bool=..., width_ratios: Sequence[float] | None=..., height_ratios: Sequence[float] | None=..., subplot_kw: dict[str, Any] | None=..., gridspec_kw: dict[str, Any] | None=..., **fig_kw) -> tuple[Figure, Any]: ... def subplots(nrows: int=1, ncols: int=1, *, sharex: bool | Literal['none', 'all', 'row', 'col']=False, sharey: bool | Literal['none', 'all', 'row', 'col']=False, squeeze: bool=True, width_ratios: Sequence[float] | None=None, height_ratios: Sequence[float] | None=None, subplot_kw: dict[str, Any] | None=None, gridspec_kw: dict[str, Any] | None=None, **fig_kw) -> tuple[Figure, Any]: fig = figure(**fig_kw) axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, squeeze=squeeze, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw, height_ratios=height_ratios, width_ratios=width_ratios) return (fig, axs) @overload def subplot_mosaic(mosaic: str, *, sharex: bool=..., sharey: bool=..., width_ratios: ArrayLike | None=..., height_ratios: ArrayLike | None=..., empty_sentinel: str=..., subplot_kw: dict[str, Any] | None=..., gridspec_kw: dict[str, Any] | None=..., per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None=..., **fig_kw: Any) -> tuple[Figure, dict[str, matplotlib.axes.Axes]]: ... @overload def subplot_mosaic(mosaic: list[HashableList[_T]], *, sharex: bool=..., sharey: bool=..., width_ratios: ArrayLike | None=..., height_ratios: ArrayLike | None=..., empty_sentinel: _T=..., subplot_kw: dict[str, Any] | None=..., gridspec_kw: dict[str, Any] | None=..., per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None=..., **fig_kw: Any) -> tuple[Figure, dict[_T, matplotlib.axes.Axes]]: ... @overload def subplot_mosaic(mosaic: list[HashableList[Hashable]], *, sharex: bool=..., sharey: bool=..., width_ratios: ArrayLike | None=..., height_ratios: ArrayLike | None=..., empty_sentinel: Any=..., subplot_kw: dict[str, Any] | None=..., gridspec_kw: dict[str, Any] | None=..., per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None=..., **fig_kw: Any) -> tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: ... def subplot_mosaic(mosaic: str | list[HashableList[_T]] | list[HashableList[Hashable]], *, sharex: bool=False, sharey: bool=False, width_ratios: ArrayLike | None=None, height_ratios: ArrayLike | None=None, empty_sentinel: Any='.', subplot_kw: dict[str, Any] | None=None, gridspec_kw: dict[str, Any] | None=None, per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | dict[_T | tuple[_T, ...], dict[str, Any]] | dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None=None, **fig_kw: Any) -> tuple[Figure, dict[str, matplotlib.axes.Axes]] | tuple[Figure, dict[_T, matplotlib.axes.Axes]] | tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: fig = figure(**fig_kw) ax_dict = fig.subplot_mosaic(mosaic, sharex=sharex, sharey=sharey, height_ratios=height_ratios, width_ratios=width_ratios, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw, empty_sentinel=empty_sentinel, per_subplot_kw=per_subplot_kw) return (fig, ax_dict) def subplot2grid(shape: tuple[int, int], loc: tuple[int, int], rowspan: int=1, colspan: int=1, fig: Figure | None=None, **kwargs) -> matplotlib.axes.Axes: if fig is None: fig = gcf() (rows, cols) = shape gs = GridSpec._check_gridspec_exists(fig, rows, cols) subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan) return fig.add_subplot(subplotspec, **kwargs) def twinx(ax: matplotlib.axes.Axes | None=None) -> _AxesBase: if ax is None: ax = gca() ax1 = ax.twinx() return ax1 def twiny(ax: matplotlib.axes.Axes | None=None) -> _AxesBase: if ax is None: ax = gca() ax1 = ax.twiny() return ax1 def subplot_tool(targetfig: Figure | None=None) -> SubplotTool | None: if targetfig is None: targetfig = gcf() tb = targetfig.canvas.manager.toolbar if hasattr(tb, 'configure_subplots'): from matplotlib.backend_bases import NavigationToolbar2 return cast(NavigationToolbar2, tb).configure_subplots() elif hasattr(tb, 'trigger_tool'): from matplotlib.backend_bases import ToolContainerBase cast(ToolContainerBase, tb).trigger_tool('subplots') return None else: raise ValueError('subplot_tool can only be launched for figures with an associated toolbar') def box(on: bool | None=None) -> None: ax = gca() if on is None: on = not ax.get_frame_on() ax.set_frame_on(on) def xlim(*args, **kwargs) -> tuple[float, float]: ax = gca() if not args and (not kwargs): return ax.get_xlim() ret = ax.set_xlim(*args, **kwargs) return ret def ylim(*args, **kwargs) -> tuple[float, float]: ax = gca() if not args and (not kwargs): return ax.get_ylim() ret = ax.set_ylim(*args, **kwargs) return ret def xticks(ticks: ArrayLike | None=None, labels: Sequence[str] | None=None, *, minor: bool=False, **kwargs) -> tuple[list[Tick] | np.ndarray, list[Text]]: ax = gca() locs: list[Tick] | np.ndarray if ticks is None: locs = ax.get_xticks(minor=minor) if labels is not None: raise TypeError("xticks(): Parameter 'labels' can't be set without setting 'ticks'") else: locs = ax.set_xticks(ticks, minor=minor) labels_out: list[Text] = [] if labels is None: labels_out = ax.get_xticklabels(minor=minor) for l in labels_out: l._internal_update(kwargs) else: labels_out = ax.set_xticklabels(labels, minor=minor, **kwargs) return (locs, labels_out) def yticks(ticks: ArrayLike | None=None, labels: Sequence[str] | None=None, *, minor: bool=False, **kwargs) -> tuple[list[Tick] | np.ndarray, list[Text]]: ax = gca() locs: list[Tick] | np.ndarray if ticks is None: locs = ax.get_yticks(minor=minor) if labels is not None: raise TypeError("yticks(): Parameter 'labels' can't be set without setting 'ticks'") else: locs = ax.set_yticks(ticks, minor=minor) labels_out: list[Text] = [] if labels is None: labels_out = ax.get_yticklabels(minor=minor) for l in labels_out: l._internal_update(kwargs) else: labels_out = ax.set_yticklabels(labels, minor=minor, **kwargs) return (locs, labels_out) def rgrids(radii: ArrayLike | None=None, labels: Sequence[str | Text] | None=None, angle: float | None=None, fmt: str | None=None, **kwargs) -> tuple[list[Line2D], list[Text]]: ax = gca() if not isinstance(ax, PolarAxes): raise RuntimeError('rgrids only defined for polar Axes') if all((p is None for p in [radii, labels, angle, fmt])) and (not kwargs): lines_out: list[Line2D] = ax.yaxis.get_gridlines() labels_out: list[Text] = ax.yaxis.get_ticklabels() elif radii is None: raise TypeError("'radii' cannot be None when other parameters are passed") else: (lines_out, labels_out) = ax.set_rgrids(radii, labels=labels, angle=angle, fmt=fmt, **kwargs) return (lines_out, labels_out) def thetagrids(angles: ArrayLike | None=None, labels: Sequence[str | Text] | None=None, fmt: str | None=None, **kwargs) -> tuple[list[Line2D], list[Text]]: ax = gca() if not isinstance(ax, PolarAxes): raise RuntimeError('thetagrids only defined for polar Axes') if all((param is None for param in [angles, labels, fmt])) and (not kwargs): lines_out: list[Line2D] = ax.xaxis.get_ticklines() labels_out: list[Text] = ax.xaxis.get_ticklabels() elif angles is None: raise TypeError("'angles' cannot be None when other parameters are passed") else: (lines_out, labels_out) = ax.set_thetagrids(angles, labels=labels, fmt=fmt, **kwargs) return (lines_out, labels_out) @_api.deprecated('3.7', pending=True) def get_plot_commands() -> list[str]: NON_PLOT_COMMANDS = {'connect', 'disconnect', 'get_current_fig_manager', 'ginput', 'new_figure_manager', 'waitforbuttonpress'} return [name for name in _get_pyplot_commands() if name not in NON_PLOT_COMMANDS] def _get_pyplot_commands() -> list[str]: exclude = {'colormaps', 'colors', 'get_plot_commands', *colormaps} this_module = inspect.getmodule(get_plot_commands) return sorted((name for (name, obj) in globals().items() if not name.startswith('_') and name not in exclude and inspect.isfunction(obj) and (inspect.getmodule(obj) is this_module))) @_copy_docstring_and_deprecators(Figure.colorbar) def colorbar(mappable: ScalarMappable | None=None, cax: matplotlib.axes.Axes | None=None, ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None=None, **kwargs) -> Colorbar: if mappable is None: mappable = gci() if mappable is None: raise RuntimeError('No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).') ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs) return ret def clim(vmin: float | None=None, vmax: float | None=None) -> None: im = gci() if im is None: raise RuntimeError('You must first define an image, e.g., with imshow') im.set_clim(vmin, vmax) def get_cmap(name: Colormap | str | None=None, lut: int | None=None) -> Colormap: if name is None: name = rcParams['image.cmap'] if isinstance(name, Colormap): return name _api.check_in_list(sorted(_colormaps), name=name) if lut is None: return _colormaps[name] else: return _colormaps[name].resampled(lut) def set_cmap(cmap: Colormap | str) -> None: cmap = get_cmap(cmap) rc('image', cmap=cmap.name) im = gci() if im is not None: im.set_cmap(cmap) @_copy_docstring_and_deprecators(matplotlib.image.imread) def imread(fname: str | pathlib.Path | BinaryIO, format: str | None=None) -> np.ndarray: return matplotlib.image.imread(fname, format) @_copy_docstring_and_deprecators(matplotlib.image.imsave) def imsave(fname: str | os.PathLike | BinaryIO, arr: ArrayLike, **kwargs) -> None: matplotlib.image.imsave(fname, arr, **kwargs) def matshow(A: ArrayLike, fignum: None | int=None, **kwargs) -> AxesImage: A = np.asanyarray(A) if fignum == 0: ax = gca() else: fig = figure(fignum, figsize=figaspect(A)) ax = fig.add_axes((0.15, 0.09, 0.775, 0.775)) im = ax.matshow(A, **kwargs) sci(im) return im def polar(*args, **kwargs) -> list[Line2D]: if gcf().get_axes(): ax = gca() if not isinstance(ax, PolarAxes): _api.warn_external('Trying to create polar plot on an Axes that does not have a polar projection.') else: ax = axes(projection='polar') return ax.plot(*args, **kwargs) if rcParams['backend_fallback'] and rcParams._get_backend_or_none() in set(backend_registry.list_builtin(BackendFilter.INTERACTIVE)) - {'webagg', 'nbagg'} and cbook._get_running_interactive_framework(): rcParams._set('backend', rcsetup._auto_backend_sentinel) @_copy_docstring_and_deprecators(Figure.figimage) def figimage(X: ArrayLike, xo: int=0, yo: int=0, alpha: float | None=None, norm: str | Normalize | None=None, cmap: str | Colormap | None=None, vmin: float | None=None, vmax: float | None=None, origin: Literal['upper', 'lower'] | None=None, resize: bool=False, **kwargs) -> FigureImage: return gcf().figimage(X, xo=xo, yo=yo, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin, resize=resize, **kwargs) @_copy_docstring_and_deprecators(Figure.text) def figtext(x: float, y: float, s: str, fontdict: dict[str, Any] | None=None, **kwargs) -> Text: return gcf().text(x, y, s, fontdict=fontdict, **kwargs) @_copy_docstring_and_deprecators(Figure.gca) def gca() -> Axes: return gcf().gca() @_copy_docstring_and_deprecators(Figure._gci) def gci() -> ScalarMappable | None: return gcf()._gci() @_copy_docstring_and_deprecators(Figure.ginput) def ginput(n: int=1, timeout: float=30, show_clicks: bool=True, mouse_add: MouseButton=MouseButton.LEFT, mouse_pop: MouseButton=MouseButton.RIGHT, mouse_stop: MouseButton=MouseButton.MIDDLE) -> list[tuple[int, int]]: return gcf().ginput(n=n, timeout=timeout, show_clicks=show_clicks, mouse_add=mouse_add, mouse_pop=mouse_pop, mouse_stop=mouse_stop) @_copy_docstring_and_deprecators(Figure.subplots_adjust) def subplots_adjust(left: float | None=None, bottom: float | None=None, right: float | None=None, top: float | None=None, wspace: float | None=None, hspace: float | None=None) -> None: gcf().subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace) @_copy_docstring_and_deprecators(Figure.suptitle) def suptitle(t: str, **kwargs) -> Text: return gcf().suptitle(t, **kwargs) @_copy_docstring_and_deprecators(Figure.tight_layout) def tight_layout(*, pad: float=1.08, h_pad: float | None=None, w_pad: float | None=None, rect: tuple[float, float, float, float] | None=None) -> None: gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) @_copy_docstring_and_deprecators(Figure.waitforbuttonpress) def waitforbuttonpress(timeout: float=-1) -> None | bool: return gcf().waitforbuttonpress(timeout=timeout) @_copy_docstring_and_deprecators(Axes.acorr) def acorr(x: ArrayLike, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: return gca().acorr(x, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.angle_spectrum) def angle_spectrum(x: ArrayLike, Fs: float | None=None, Fc: int | None=None, window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None=None, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided'] | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, Line2D]: return gca().angle_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.annotate) def annotate(text: str, xy: tuple[float, float], xytext: tuple[float, float] | None=None, xycoords: str | Artist | Transform | Callable[[RendererBase], Bbox | Transform] | tuple[float, float]='data', textcoords: str | Artist | Transform | Callable[[RendererBase], Bbox | Transform] | tuple[float, float] | None=None, arrowprops: dict[str, Any] | None=None, annotation_clip: bool | None=None, **kwargs) -> Annotation: return gca().annotate(text, xy, xytext=xytext, xycoords=xycoords, textcoords=textcoords, arrowprops=arrowprops, annotation_clip=annotation_clip, **kwargs) @_copy_docstring_and_deprecators(Axes.arrow) def arrow(x: float, y: float, dx: float, dy: float, **kwargs) -> FancyArrow: return gca().arrow(x, y, dx, dy, **kwargs) @_copy_docstring_and_deprecators(Axes.autoscale) def autoscale(enable: bool=True, axis: Literal['both', 'x', 'y']='both', tight: bool | None=None) -> None: gca().autoscale(enable=enable, axis=axis, tight=tight) @_copy_docstring_and_deprecators(Axes.axhline) def axhline(y: float=0, xmin: float=0, xmax: float=1, **kwargs) -> Line2D: return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs) @_copy_docstring_and_deprecators(Axes.axhspan) def axhspan(ymin: float, ymax: float, xmin: float=0, xmax: float=1, **kwargs) -> Rectangle: return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs) @_copy_docstring_and_deprecators(Axes.axis) def axis(arg: tuple[float, float, float, float] | bool | str | None=None, /, *, emit: bool=True, **kwargs) -> tuple[float, float, float, float]: return gca().axis(arg, emit=emit, **kwargs) @_copy_docstring_and_deprecators(Axes.axline) def axline(xy1: tuple[float, float], xy2: tuple[float, float] | None=None, *, slope: float | None=None, **kwargs) -> AxLine: return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs) @_copy_docstring_and_deprecators(Axes.axvline) def axvline(x: float=0, ymin: float=0, ymax: float=1, **kwargs) -> Line2D: return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs) @_copy_docstring_and_deprecators(Axes.axvspan) def axvspan(xmin: float, xmax: float, ymin: float=0, ymax: float=1, **kwargs) -> Rectangle: return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs) @_copy_docstring_and_deprecators(Axes.bar) def bar(x: float | ArrayLike, height: float | ArrayLike, width: float | ArrayLike=0.8, bottom: float | ArrayLike | None=None, *, align: Literal['center', 'edge']='center', data=None, **kwargs) -> BarContainer: return gca().bar(x, height, width=width, bottom=bottom, align=align, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.barbs) def barbs(*args, data=None, **kwargs) -> Barbs: return gca().barbs(*args, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.barh) def barh(y: float | ArrayLike, width: float | ArrayLike, height: float | ArrayLike=0.8, left: float | ArrayLike | None=None, *, align: Literal['center', 'edge']='center', data=None, **kwargs) -> BarContainer: return gca().barh(y, width, height=height, left=left, align=align, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.bar_label) def bar_label(container: BarContainer, labels: ArrayLike | None=None, *, fmt: str | Callable[[float], str]='%g', label_type: Literal['center', 'edge']='edge', padding: float=0, **kwargs) -> list[Annotation]: return gca().bar_label(container, labels=labels, fmt=fmt, label_type=label_type, padding=padding, **kwargs) @_copy_docstring_and_deprecators(Axes.boxplot) def boxplot(x: ArrayLike | Sequence[ArrayLike], notch: bool | None=None, sym: str | None=None, vert: bool | None=None, orientation: Literal['vertical', 'horizontal']='vertical', whis: float | tuple[float, float] | None=None, positions: ArrayLike | None=None, widths: float | ArrayLike | None=None, patch_artist: bool | None=None, bootstrap: int | None=None, usermedians: ArrayLike | None=None, conf_intervals: ArrayLike | None=None, meanline: bool | None=None, showmeans: bool | None=None, showcaps: bool | None=None, showbox: bool | None=None, showfliers: bool | None=None, boxprops: dict[str, Any] | None=None, tick_labels: Sequence[str] | None=None, flierprops: dict[str, Any] | None=None, medianprops: dict[str, Any] | None=None, meanprops: dict[str, Any] | None=None, capprops: dict[str, Any] | None=None, whiskerprops: dict[str, Any] | None=None, manage_ticks: bool=True, autorange: bool=False, zorder: float | None=None, capwidths: float | ArrayLike | None=None, label: Sequence[str] | None=None, *, data=None) -> dict[str, Any]: return gca().boxplot(x, notch=notch, sym=sym, vert=vert, orientation=orientation, whis=whis, positions=positions, widths=widths, patch_artist=patch_artist, bootstrap=bootstrap, usermedians=usermedians, conf_intervals=conf_intervals, meanline=meanline, showmeans=showmeans, showcaps=showcaps, showbox=showbox, showfliers=showfliers, boxprops=boxprops, tick_labels=tick_labels, flierprops=flierprops, medianprops=medianprops, meanprops=meanprops, capprops=capprops, whiskerprops=whiskerprops, manage_ticks=manage_ticks, autorange=autorange, zorder=zorder, capwidths=capwidths, label=label, **{'data': data} if data is not None else {}) @_copy_docstring_and_deprecators(Axes.broken_barh) def broken_barh(xranges: Sequence[tuple[float, float]], yrange: tuple[float, float], *, data=None, **kwargs) -> PolyCollection: return gca().broken_barh(xranges, yrange, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.clabel) def clabel(CS: ContourSet, levels: ArrayLike | None=None, **kwargs) -> list[Text]: return gca().clabel(CS, levels=levels, **kwargs) @_copy_docstring_and_deprecators(Axes.cohere) def cohere(x: ArrayLike, y: ArrayLike, NFFT: int=256, Fs: float=2, Fc: int=0, detrend: Literal['none', 'mean', 'linear'] | Callable[[ArrayLike], ArrayLike]=mlab.detrend_none, window: Callable[[ArrayLike], ArrayLike] | ArrayLike=mlab.window_hanning, noverlap: int=0, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided']='default', scale_by_freq: bool | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray]: return gca().cohere(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.contour) def contour(*args, data=None, **kwargs) -> QuadContourSet: __ret = gca().contour(*args, **{'data': data} if data is not None else {}, **kwargs) if __ret._A is not None: sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.contourf) def contourf(*args, data=None, **kwargs) -> QuadContourSet: __ret = gca().contourf(*args, **{'data': data} if data is not None else {}, **kwargs) if __ret._A is not None: sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.csd) def csd(x: ArrayLike, y: ArrayLike, NFFT: int | None=None, Fs: float | None=None, Fc: int | None=None, detrend: Literal['none', 'mean', 'linear'] | Callable[[ArrayLike], ArrayLike] | None=None, window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None=None, noverlap: int | None=None, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided'] | None=None, scale_by_freq: bool | None=None, return_line: bool | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: return gca().csd(x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, return_line=return_line, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.ecdf) def ecdf(x: ArrayLike, weights: ArrayLike | None=None, *, complementary: bool=False, orientation: Literal['vertical', 'horizonatal']='vertical', compress: bool=False, data=None, **kwargs) -> Line2D: return gca().ecdf(x, weights=weights, complementary=complementary, orientation=orientation, compress=compress, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.errorbar) def errorbar(x: float | ArrayLike, y: float | ArrayLike, yerr: float | ArrayLike | None=None, xerr: float | ArrayLike | None=None, fmt: str='', ecolor: ColorType | None=None, elinewidth: float | None=None, capsize: float | None=None, barsabove: bool=False, lolims: bool | ArrayLike=False, uplims: bool | ArrayLike=False, xlolims: bool | ArrayLike=False, xuplims: bool | ArrayLike=False, errorevery: int | tuple[int, int]=1, capthick: float | None=None, *, data=None, **kwargs) -> ErrorbarContainer: return gca().errorbar(x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor, elinewidth=elinewidth, capsize=capsize, barsabove=barsabove, lolims=lolims, uplims=uplims, xlolims=xlolims, xuplims=xuplims, errorevery=errorevery, capthick=capthick, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.eventplot) def eventplot(positions: ArrayLike | Sequence[ArrayLike], orientation: Literal['horizontal', 'vertical']='horizontal', lineoffsets: float | Sequence[float]=1, linelengths: float | Sequence[float]=1, linewidths: float | Sequence[float] | None=None, colors: ColorType | Sequence[ColorType] | None=None, alpha: float | Sequence[float] | None=None, linestyles: LineStyleType | Sequence[LineStyleType]='solid', *, data=None, **kwargs) -> EventCollection: return gca().eventplot(positions, orientation=orientation, lineoffsets=lineoffsets, linelengths=linelengths, linewidths=linewidths, colors=colors, alpha=alpha, linestyles=linestyles, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.fill) def fill(*args, data=None, **kwargs) -> list[Polygon]: return gca().fill(*args, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.fill_between) def fill_between(x: ArrayLike, y1: ArrayLike | float, y2: ArrayLike | float=0, where: Sequence[bool] | None=None, interpolate: bool=False, step: Literal['pre', 'post', 'mid'] | None=None, *, data=None, **kwargs) -> PolyCollection: return gca().fill_between(x, y1, y2=y2, where=where, interpolate=interpolate, step=step, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.fill_betweenx) def fill_betweenx(y: ArrayLike, x1: ArrayLike | float, x2: ArrayLike | float=0, where: Sequence[bool] | None=None, step: Literal['pre', 'post', 'mid'] | None=None, interpolate: bool=False, *, data=None, **kwargs) -> PolyCollection: return gca().fill_betweenx(y, x1, x2=x2, where=where, step=step, interpolate=interpolate, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.grid) def grid(visible: bool | None=None, which: Literal['major', 'minor', 'both']='major', axis: Literal['both', 'x', 'y']='both', **kwargs) -> None: gca().grid(visible=visible, which=which, axis=axis, **kwargs) @_copy_docstring_and_deprecators(Axes.hexbin) def hexbin(x: ArrayLike, y: ArrayLike, C: ArrayLike | None=None, gridsize: int | tuple[int, int]=100, bins: Literal['log'] | int | Sequence[float] | None=None, xscale: Literal['linear', 'log']='linear', yscale: Literal['linear', 'log']='linear', extent: tuple[float, float, float, float] | None=None, cmap: str | Colormap | None=None, norm: str | Normalize | None=None, vmin: float | None=None, vmax: float | None=None, alpha: float | None=None, linewidths: float | None=None, edgecolors: Literal['face', 'none'] | ColorType='face', reduce_C_function: Callable[[np.ndarray | list[float]], float]=np.mean, mincnt: int | None=None, marginals: bool=False, *, data=None, **kwargs) -> PolyCollection: __ret = gca().hexbin(x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale, yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths, edgecolors=edgecolors, reduce_C_function=reduce_C_function, mincnt=mincnt, marginals=marginals, **{'data': data} if data is not None else {}, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.hist) def hist(x: ArrayLike | Sequence[ArrayLike], bins: int | Sequence[float] | str | None=None, range: tuple[float, float] | None=None, density: bool=False, weights: ArrayLike | None=None, cumulative: bool | float=False, bottom: ArrayLike | float | None=None, histtype: Literal['bar', 'barstacked', 'step', 'stepfilled']='bar', align: Literal['left', 'mid', 'right']='mid', orientation: Literal['vertical', 'horizontal']='vertical', rwidth: float | None=None, log: bool=False, color: ColorType | Sequence[ColorType] | None=None, label: str | Sequence[str] | None=None, stacked: bool=False, *, data=None, **kwargs) -> tuple[np.ndarray | list[np.ndarray], np.ndarray, BarContainer | Polygon | list[BarContainer | Polygon]]: return gca().hist(x, bins=bins, range=range, density=density, weights=weights, cumulative=cumulative, bottom=bottom, histtype=histtype, align=align, orientation=orientation, rwidth=rwidth, log=log, color=color, label=label, stacked=stacked, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.stairs) def stairs(values: ArrayLike, edges: ArrayLike | None=None, *, orientation: Literal['vertical', 'horizontal']='vertical', baseline: float | ArrayLike | None=0, fill: bool=False, data=None, **kwargs) -> StepPatch: return gca().stairs(values, edges=edges, orientation=orientation, baseline=baseline, fill=fill, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.hist2d) def hist2d(x: ArrayLike, y: ArrayLike, bins: None | int | tuple[int, int] | ArrayLike | tuple[ArrayLike, ArrayLike]=10, range: ArrayLike | None=None, density: bool=False, weights: ArrayLike | None=None, cmin: float | None=None, cmax: float | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: __ret = gca().hist2d(x, y, bins=bins, range=range, density=density, weights=weights, cmin=cmin, cmax=cmax, **{'data': data} if data is not None else {}, **kwargs) sci(__ret[-1]) return __ret @_copy_docstring_and_deprecators(Axes.hlines) def hlines(y: float | ArrayLike, xmin: float | ArrayLike, xmax: float | ArrayLike, colors: ColorType | Sequence[ColorType] | None=None, linestyles: LineStyleType='solid', label: str='', *, data=None, **kwargs) -> LineCollection: return gca().hlines(y, xmin, xmax, colors=colors, linestyles=linestyles, label=label, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.imshow) def imshow(X: ArrayLike | PIL.Image.Image, cmap: str | Colormap | None=None, norm: str | Normalize | None=None, *, aspect: Literal['equal', 'auto'] | float | None=None, interpolation: str | None=None, alpha: float | ArrayLike | None=None, vmin: float | None=None, vmax: float | None=None, origin: Literal['upper', 'lower'] | None=None, extent: tuple[float, float, float, float] | None=None, interpolation_stage: Literal['data', 'rgba', 'auto'] | None=None, filternorm: bool=True, filterrad: float=4.0, resample: bool | None=None, url: str | None=None, data=None, **kwargs) -> AxesImage: __ret = gca().imshow(X, cmap=cmap, norm=norm, aspect=aspect, interpolation=interpolation, alpha=alpha, vmin=vmin, vmax=vmax, origin=origin, extent=extent, interpolation_stage=interpolation_stage, filternorm=filternorm, filterrad=filterrad, resample=resample, url=url, **{'data': data} if data is not None else {}, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.legend) def legend(*args, **kwargs) -> Legend: return gca().legend(*args, **kwargs) @_copy_docstring_and_deprecators(Axes.locator_params) def locator_params(axis: Literal['both', 'x', 'y']='both', tight: bool | None=None, **kwargs) -> None: gca().locator_params(axis=axis, tight=tight, **kwargs) @_copy_docstring_and_deprecators(Axes.loglog) def loglog(*args, **kwargs) -> list[Line2D]: return gca().loglog(*args, **kwargs) @_copy_docstring_and_deprecators(Axes.magnitude_spectrum) def magnitude_spectrum(x: ArrayLike, Fs: float | None=None, Fc: int | None=None, window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None=None, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided'] | None=None, scale: Literal['default', 'linear', 'dB'] | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, Line2D]: return gca().magnitude_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides, scale=scale, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.margins) def margins(*margins: float, x: float | None=None, y: float | None=None, tight: bool | None=True) -> tuple[float, float] | None: return gca().margins(*margins, x=x, y=y, tight=tight) @_copy_docstring_and_deprecators(Axes.minorticks_off) def minorticks_off() -> None: gca().minorticks_off() @_copy_docstring_and_deprecators(Axes.minorticks_on) def minorticks_on() -> None: gca().minorticks_on() @_copy_docstring_and_deprecators(Axes.pcolor) def pcolor(*args: ArrayLike, shading: Literal['flat', 'nearest', 'auto'] | None=None, alpha: float | None=None, norm: str | Normalize | None=None, cmap: str | Colormap | None=None, vmin: float | None=None, vmax: float | None=None, data=None, **kwargs) -> Collection: __ret = gca().pcolor(*args, shading=shading, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin, vmax=vmax, **{'data': data} if data is not None else {}, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.pcolormesh) def pcolormesh(*args: ArrayLike, alpha: float | None=None, norm: str | Normalize | None=None, cmap: str | Colormap | None=None, vmin: float | None=None, vmax: float | None=None, shading: Literal['flat', 'nearest', 'gouraud', 'auto'] | None=None, antialiased: bool=False, data=None, **kwargs) -> QuadMesh: __ret = gca().pcolormesh(*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin, vmax=vmax, shading=shading, antialiased=antialiased, **{'data': data} if data is not None else {}, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.phase_spectrum) def phase_spectrum(x: ArrayLike, Fs: float | None=None, Fc: int | None=None, window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None=None, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided'] | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, Line2D]: return gca().phase_spectrum(x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.pie) def pie(x: ArrayLike, explode: ArrayLike | None=None, labels: Sequence[str] | None=None, colors: ColorType | Sequence[ColorType] | None=None, autopct: str | Callable[[float], str] | None=None, pctdistance: float=0.6, shadow: bool=False, labeldistance: float | None=1.1, startangle: float=0, radius: float=1, counterclock: bool=True, wedgeprops: dict[str, Any] | None=None, textprops: dict[str, Any] | None=None, center: tuple[float, float]=(0, 0), frame: bool=False, rotatelabels: bool=False, *, normalize: bool=True, hatch: str | Sequence[str] | None=None, data=None) -> tuple[list[Wedge], list[Text]] | tuple[list[Wedge], list[Text], list[Text]]: return gca().pie(x, explode=explode, labels=labels, colors=colors, autopct=autopct, pctdistance=pctdistance, shadow=shadow, labeldistance=labeldistance, startangle=startangle, radius=radius, counterclock=counterclock, wedgeprops=wedgeprops, textprops=textprops, center=center, frame=frame, rotatelabels=rotatelabels, normalize=normalize, hatch=hatch, **{'data': data} if data is not None else {}) @_copy_docstring_and_deprecators(Axes.plot) def plot(*args: float | ArrayLike | str, scalex: bool=True, scaley: bool=True, data=None, **kwargs) -> list[Line2D]: return gca().plot(*args, scalex=scalex, scaley=scaley, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.plot_date) def plot_date(x: ArrayLike, y: ArrayLike, fmt: str='o', tz: str | datetime.tzinfo | None=None, xdate: bool=True, ydate: bool=False, *, data=None, **kwargs) -> list[Line2D]: return gca().plot_date(x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.psd) def psd(x: ArrayLike, NFFT: int | None=None, Fs: float | None=None, Fc: int | None=None, detrend: Literal['none', 'mean', 'linear'] | Callable[[ArrayLike], ArrayLike] | None=None, window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None=None, noverlap: int | None=None, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided'] | None=None, scale_by_freq: bool | None=None, return_line: bool | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: return gca().psd(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, return_line=return_line, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.quiver) def quiver(*args, data=None, **kwargs) -> Quiver: __ret = gca().quiver(*args, **{'data': data} if data is not None else {}, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.quiverkey) def quiverkey(Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs) -> QuiverKey: return gca().quiverkey(Q, X, Y, U, label, **kwargs) @_copy_docstring_and_deprecators(Axes.scatter) def scatter(x: float | ArrayLike, y: float | ArrayLike, s: float | ArrayLike | None=None, c: ArrayLike | Sequence[ColorType] | ColorType | None=None, marker: MarkerType | None=None, cmap: str | Colormap | None=None, norm: str | Normalize | None=None, vmin: float | None=None, vmax: float | None=None, alpha: float | None=None, linewidths: float | Sequence[float] | None=None, *, edgecolors: Literal['face', 'none'] | ColorType | Sequence[ColorType] | None=None, plotnonfinite: bool=False, data=None, **kwargs) -> PathCollection: __ret = gca().scatter(x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths, edgecolors=edgecolors, plotnonfinite=plotnonfinite, **{'data': data} if data is not None else {}, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.semilogx) def semilogx(*args, **kwargs) -> list[Line2D]: return gca().semilogx(*args, **kwargs) @_copy_docstring_and_deprecators(Axes.semilogy) def semilogy(*args, **kwargs) -> list[Line2D]: return gca().semilogy(*args, **kwargs) @_copy_docstring_and_deprecators(Axes.specgram) def specgram(x: ArrayLike, NFFT: int | None=None, Fs: float | None=None, Fc: int | None=None, detrend: Literal['none', 'mean', 'linear'] | Callable[[ArrayLike], ArrayLike] | None=None, window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None=None, noverlap: int | None=None, cmap: str | Colormap | None=None, xextent: tuple[float, float] | None=None, pad_to: int | None=None, sides: Literal['default', 'onesided', 'twosided'] | None=None, scale_by_freq: bool | None=None, mode: Literal['default', 'psd', 'magnitude', 'angle', 'phase'] | None=None, scale: Literal['default', 'linear', 'dB'] | None=None, vmin: float | None=None, vmax: float | None=None, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: __ret = gca().specgram(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window, noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq, mode=mode, scale=scale, vmin=vmin, vmax=vmax, **{'data': data} if data is not None else {}, **kwargs) sci(__ret[-1]) return __ret @_copy_docstring_and_deprecators(Axes.spy) def spy(Z: ArrayLike, precision: float | Literal['present']=0, marker: str | None=None, markersize: float | None=None, aspect: Literal['equal', 'auto'] | float | None='equal', origin: Literal['upper', 'lower']='upper', **kwargs) -> AxesImage: __ret = gca().spy(Z, precision=precision, marker=marker, markersize=markersize, aspect=aspect, origin=origin, **kwargs) if isinstance(__ret, cm.ScalarMappable): sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.stackplot) def stackplot(x, *args, labels=(), colors=None, hatch=None, baseline='zero', data=None, **kwargs): return gca().stackplot(x, *args, labels=labels, colors=colors, hatch=hatch, baseline=baseline, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.stem) def stem(*args: ArrayLike | str, linefmt: str | None=None, markerfmt: str | None=None, basefmt: str | None=None, bottom: float=0, label: str | None=None, orientation: Literal['vertical', 'horizontal']='vertical', data=None) -> StemContainer: return gca().stem(*args, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt, bottom=bottom, label=label, orientation=orientation, **{'data': data} if data is not None else {}) @_copy_docstring_and_deprecators(Axes.step) def step(x: ArrayLike, y: ArrayLike, *args, where: Literal['pre', 'post', 'mid']='pre', data=None, **kwargs) -> list[Line2D]: return gca().step(x, y, *args, where=where, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.streamplot) def streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction='both', broken_streamlines=True, *, data=None): __ret = gca().streamplot(x, y, u, v, density=density, linewidth=linewidth, color=color, cmap=cmap, norm=norm, arrowsize=arrowsize, arrowstyle=arrowstyle, minlength=minlength, transform=transform, zorder=zorder, start_points=start_points, maxlength=maxlength, integration_direction=integration_direction, broken_streamlines=broken_streamlines, **{'data': data} if data is not None else {}) sci(__ret.lines) return __ret @_copy_docstring_and_deprecators(Axes.table) def table(cellText=None, cellColours=None, cellLoc='right', colWidths=None, rowLabels=None, rowColours=None, rowLoc='left', colLabels=None, colColours=None, colLoc='center', loc='bottom', bbox=None, edges='closed', **kwargs): return gca().table(cellText=cellText, cellColours=cellColours, cellLoc=cellLoc, colWidths=colWidths, rowLabels=rowLabels, rowColours=rowColours, rowLoc=rowLoc, colLabels=colLabels, colColours=colColours, colLoc=colLoc, loc=loc, bbox=bbox, edges=edges, **kwargs) @_copy_docstring_and_deprecators(Axes.text) def text(x: float, y: float, s: str, fontdict: dict[str, Any] | None=None, **kwargs) -> Text: return gca().text(x, y, s, fontdict=fontdict, **kwargs) @_copy_docstring_and_deprecators(Axes.tick_params) def tick_params(axis: Literal['both', 'x', 'y']='both', **kwargs) -> None: gca().tick_params(axis=axis, **kwargs) @_copy_docstring_and_deprecators(Axes.ticklabel_format) def ticklabel_format(*, axis: Literal['both', 'x', 'y']='both', style: Literal['', 'sci', 'scientific', 'plain'] | None=None, scilimits: tuple[int, int] | None=None, useOffset: bool | float | None=None, useLocale: bool | None=None, useMathText: bool | None=None) -> None: gca().ticklabel_format(axis=axis, style=style, scilimits=scilimits, useOffset=useOffset, useLocale=useLocale, useMathText=useMathText) @_copy_docstring_and_deprecators(Axes.tricontour) def tricontour(*args, **kwargs): __ret = gca().tricontour(*args, **kwargs) if __ret._A is not None: sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.tricontourf) def tricontourf(*args, **kwargs): __ret = gca().tricontourf(*args, **kwargs) if __ret._A is not None: sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.tripcolor) def tripcolor(*args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', facecolors=None, **kwargs): __ret = gca().tripcolor(*args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin, vmax=vmax, shading=shading, facecolors=facecolors, **kwargs) sci(__ret) return __ret @_copy_docstring_and_deprecators(Axes.triplot) def triplot(*args, **kwargs): return gca().triplot(*args, **kwargs) @_copy_docstring_and_deprecators(Axes.violinplot) def violinplot(dataset: ArrayLike | Sequence[ArrayLike], positions: ArrayLike | None=None, vert: bool | None=None, orientation: Literal['vertical', 'horizontal']='vertical', widths: float | ArrayLike=0.5, showmeans: bool=False, showextrema: bool=True, showmedians: bool=False, quantiles: Sequence[float | Sequence[float]] | None=None, points: int=100, bw_method: Literal['scott', 'silverman'] | float | Callable[[GaussianKDE], float] | None=None, side: Literal['both', 'low', 'high']='both', *, data=None) -> dict[str, Collection]: return gca().violinplot(dataset, positions=positions, vert=vert, orientation=orientation, widths=widths, showmeans=showmeans, showextrema=showextrema, showmedians=showmedians, quantiles=quantiles, points=points, bw_method=bw_method, side=side, **{'data': data} if data is not None else {}) @_copy_docstring_and_deprecators(Axes.vlines) def vlines(x: float | ArrayLike, ymin: float | ArrayLike, ymax: float | ArrayLike, colors: ColorType | Sequence[ColorType] | None=None, linestyles: LineStyleType='solid', label: str='', *, data=None, **kwargs) -> LineCollection: return gca().vlines(x, ymin, ymax, colors=colors, linestyles=linestyles, label=label, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes.xcorr) def xcorr(x: ArrayLike, y: ArrayLike, normed: bool=True, detrend: Callable[[ArrayLike], ArrayLike]=mlab.detrend_none, usevlines: bool=True, maxlags: int=10, *, data=None, **kwargs) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: return gca().xcorr(x, y, normed=normed, detrend=detrend, usevlines=usevlines, maxlags=maxlags, **{'data': data} if data is not None else {}, **kwargs) @_copy_docstring_and_deprecators(Axes._sci) def sci(im: ScalarMappable) -> None: gca()._sci(im) @_copy_docstring_and_deprecators(Axes.set_title) def title(label: str, fontdict: dict[str, Any] | None=None, loc: Literal['left', 'center', 'right'] | None=None, pad: float | None=None, *, y: float | None=None, **kwargs) -> Text: return gca().set_title(label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs) @_copy_docstring_and_deprecators(Axes.set_xlabel) def xlabel(xlabel: str, fontdict: dict[str, Any] | None=None, labelpad: float | None=None, *, loc: Literal['left', 'center', 'right'] | None=None, **kwargs) -> Text: return gca().set_xlabel(xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs) @_copy_docstring_and_deprecators(Axes.set_ylabel) def ylabel(ylabel: str, fontdict: dict[str, Any] | None=None, labelpad: float | None=None, *, loc: Literal['bottom', 'center', 'top'] | None=None, **kwargs) -> Text: return gca().set_ylabel(ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs) @_copy_docstring_and_deprecators(Axes.set_xscale) def xscale(value: str | ScaleBase, **kwargs) -> None: gca().set_xscale(value, **kwargs) @_copy_docstring_and_deprecators(Axes.set_yscale) def yscale(value: str | ScaleBase, **kwargs) -> None: gca().set_yscale(value, **kwargs) def autumn() -> None: set_cmap('autumn') def bone() -> None: set_cmap('bone') def cool() -> None: set_cmap('cool') def copper() -> None: set_cmap('copper') def flag() -> None: set_cmap('flag') def gray() -> None: set_cmap('gray') def hot() -> None: set_cmap('hot') def hsv() -> None: set_cmap('hsv') def jet() -> None: set_cmap('jet') def pink() -> None: set_cmap('pink') def prism() -> None: set_cmap('prism') def spring() -> None: set_cmap('spring') def summer() -> None: set_cmap('summer') def winter() -> None: set_cmap('winter') def magma() -> None: set_cmap('magma') def inferno() -> None: set_cmap('inferno') def plasma() -> None: set_cmap('plasma') def viridis() -> None: set_cmap('viridis') def nipy_spectral() -> None: set_cmap('nipy_spectral') # File: matplotlib-main/lib/matplotlib/quiver.py """""" import math import numpy as np from numpy import ma from matplotlib import _api, cbook, _docstring import matplotlib.artist as martist import matplotlib.collections as mcollections from matplotlib.patches import CirclePolygon import matplotlib.text as mtext import matplotlib.transforms as transforms _quiver_doc = '\nPlot a 2D field of arrows.\n\nCall signature::\n\n quiver([X, Y], U, V, [C], /, **kwargs)\n\n*X*, *Y* define the arrow locations, *U*, *V* define the arrow directions, and\n*C* optionally sets the color. The arguments *X*, *Y*, *U*, *V*, *C* are\npositional-only.\n\n**Arrow length**\n\nThe default settings auto-scales the length of the arrows to a reasonable size.\nTo change this behavior see the *scale* and *scale_units* parameters.\n\n**Arrow shape**\n\nThe arrow shape is determined by *width*, *headwidth*, *headlength* and\n*headaxislength*. See the notes below.\n\n**Arrow styling**\n\nEach arrow is internally represented by a filled polygon with a default edge\nlinewidth of 0. As a result, an arrow is rather a filled area, not a line with\na head, and `.PolyCollection` properties like *linewidth*, *edgecolor*,\n*facecolor*, etc. act accordingly.\n\n\nParameters\n----------\nX, Y : 1D or 2D array-like, optional\n The x and y coordinates of the arrow locations.\n\n If not given, they will be generated as a uniform integer meshgrid based\n on the dimensions of *U* and *V*.\n\n If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D\n using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``\n must match the column and row dimensions of *U* and *V*.\n\nU, V : 1D or 2D array-like\n The x and y direction components of the arrow vectors. The interpretation\n of these components (in data or in screen space) depends on *angles*.\n\n *U* and *V* must have the same number of elements, matching the number of\n arrow locations in *X*, *Y*. *U* and *V* may be masked. Locations masked\n in any of *U*, *V*, and *C* will not be drawn.\n\nC : 1D or 2D array-like, optional\n Numeric data that defines the arrow colors by colormapping via *norm* and\n *cmap*.\n\n This does not support explicit colors. If you want to set colors directly,\n use *color* instead. The size of *C* must match the number of arrow\n locations.\n\nangles : {\'uv\', \'xy\'} or array-like, default: \'uv\'\n Method for determining the angle of the arrows.\n\n - \'uv\': Arrow direction in screen coordinates. Use this if the arrows\n symbolize a quantity that is not based on *X*, *Y* data coordinates.\n\n If *U* == *V* the orientation of the arrow on the plot is 45 degrees\n counter-clockwise from the horizontal axis (positive to the right).\n\n - \'xy\': Arrow direction in data coordinates, i.e. the arrows point from\n (x, y) to (x+u, y+v). Use this e.g. for plotting a gradient field.\n\n - Arbitrary angles may be specified explicitly as an array of values\n in degrees, counter-clockwise from the horizontal axis.\n\n In this case *U*, *V* is only used to determine the length of the\n arrows.\n\n Note: inverting a data axis will correspondingly invert the\n arrows only with ``angles=\'xy\'``.\n\npivot : {\'tail\', \'mid\', \'middle\', \'tip\'}, default: \'tail\'\n The part of the arrow that is anchored to the *X*, *Y* grid. The arrow\n rotates about this point.\n\n \'mid\' is a synonym for \'middle\'.\n\nscale : float, optional\n Scales the length of the arrow inversely.\n\n Number of data units per arrow length unit, e.g., m/s per plot width; a\n smaller scale parameter makes the arrow longer. Default is *None*.\n\n If *None*, a simple autoscaling algorithm is used, based on the average\n vector length and the number of vectors. The arrow length unit is given by\n the *scale_units* parameter.\n\nscale_units : {\'width\', \'height\', \'dots\', \'inches\', \'x\', \'y\', \'xy\'}, optional\n If the *scale* kwarg is *None*, the arrow length unit. Default is *None*.\n\n e.g. *scale_units* is \'inches\', *scale* is 2.0, and ``(u, v) = (1, 0)``,\n then the vector will be 0.5 inches long.\n\n If *scale_units* is \'width\' or \'height\', then the vector will be half the\n width/height of the axes.\n\n If *scale_units* is \'x\' then the vector will be 0.5 x-axis\n units. To plot vectors in the x-y plane, with u and v having\n the same units as x and y, use\n ``angles=\'xy\', scale_units=\'xy\', scale=1``.\n\nunits : {\'width\', \'height\', \'dots\', \'inches\', \'x\', \'y\', \'xy\'}, default: \'width\'\n Affects the arrow size (except for the length). In particular, the shaft\n *width* is measured in multiples of this unit.\n\n Supported values are:\n\n - \'width\', \'height\': The width or height of the Axes.\n - \'dots\', \'inches\': Pixels or inches based on the figure dpi.\n - \'x\', \'y\', \'xy\': *X*, *Y* or :math:`\\sqrt{X^2 + Y^2}` in data units.\n\n The following table summarizes how these values affect the visible arrow\n size under zooming and figure size changes:\n\n ================= ================= ==================\n units zoom figure size change\n ================= ================= ==================\n \'x\', \'y\', \'xy\' arrow size scales —\n \'width\', \'height\' — arrow size scales\n \'dots\', \'inches\' — —\n ================= ================= ==================\n\nwidth : float, optional\n Shaft width in arrow units. All head parameters are relative to *width*.\n\n The default depends on choice of *units* above, and number of vectors;\n a typical starting value is about 0.005 times the width of the plot.\n\nheadwidth : float, default: 3\n Head width as multiple of shaft *width*. See the notes below.\n\nheadlength : float, default: 5\n Head length as multiple of shaft *width*. See the notes below.\n\nheadaxislength : float, default: 4.5\n Head length at shaft intersection as multiple of shaft *width*.\n See the notes below.\n\nminshaft : float, default: 1\n Length below which arrow scales, in units of head length. Do not\n set this to less than 1, or small arrows will look terrible!\n\nminlength : float, default: 1\n Minimum length as a multiple of shaft width; if an arrow length\n is less than this, plot a dot (hexagon) of this diameter instead.\n\ncolor : :mpltype:`color` or list :mpltype:`color`, optional\n Explicit color(s) for the arrows. If *C* has been set, *color* has no\n effect.\n\n This is a synonym for the `.PolyCollection` *facecolor* parameter.\n\nOther Parameters\n----------------\ndata : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n**kwargs : `~matplotlib.collections.PolyCollection` properties, optional\n All other keyword arguments are passed on to `.PolyCollection`:\n\n %(PolyCollection:kwdoc)s\n\nReturns\n-------\n`~matplotlib.quiver.Quiver`\n\nSee Also\n--------\n.Axes.quiverkey : Add a key to a quiver plot.\n\nNotes\n-----\n\n**Arrow shape**\n\nThe arrow is drawn as a polygon using the nodes as shown below. The values\n*headwidth*, *headlength*, and *headaxislength* are in units of *width*.\n\n.. image:: /_static/quiver_sizes.svg\n :width: 500px\n\nThe defaults give a slightly swept-back arrow. Here are some guidelines how to\nget other head shapes:\n\n- To make the head a triangle, make *headaxislength* the same as *headlength*.\n- To make the arrow more pointed, reduce *headwidth* or increase *headlength*\n and *headaxislength*.\n- To make the head smaller relative to the shaft, scale down all the head\n parameters proportionally.\n- To remove the head completely, set all *head* parameters to 0.\n- To get a diamond-shaped head, make *headaxislength* larger than *headlength*.\n- Warning: For *headaxislength* < (*headlength* / *headwidth*), the "headaxis"\n nodes (i.e. the ones connecting the head with the shaft) will protrude out\n of the head in forward direction so that the arrow head looks broken.\n' % _docstring.interpd.params _docstring.interpd.update(quiver_doc=_quiver_doc) class QuiverKey(martist.Artist): halign = {'N': 'center', 'S': 'center', 'E': 'left', 'W': 'right'} valign = {'N': 'bottom', 'S': 'top', 'E': 'center', 'W': 'center'} pivot = {'N': 'middle', 'S': 'middle', 'E': 'tip', 'W': 'tail'} def __init__(self, Q, X, Y, U, label, *, angle=0, coordinates='axes', color=None, labelsep=0.1, labelpos='N', labelcolor=None, fontproperties=None, **kwargs): super().__init__() self.Q = Q self.X = X self.Y = Y self.U = U self.angle = angle self.coord = coordinates self.color = color self.label = label self._labelsep_inches = labelsep self.labelpos = labelpos self.labelcolor = labelcolor self.fontproperties = fontproperties or dict() self.kw = kwargs self.text = mtext.Text(text=label, horizontalalignment=self.halign[self.labelpos], verticalalignment=self.valign[self.labelpos], fontproperties=self.fontproperties) if self.labelcolor is not None: self.text.set_color(self.labelcolor) self._dpi_at_last_init = None self.zorder = Q.zorder + 0.1 @property def labelsep(self): return self._labelsep_inches * self.Q.axes.get_figure(root=True).dpi def _init(self): if True: if self.Q._dpi_at_last_init != self.Q.axes.get_figure(root=True).dpi: self.Q._init() self._set_transform() with cbook._setattr_cm(self.Q, pivot=self.pivot[self.labelpos], Umask=ma.nomask): u = self.U * np.cos(np.radians(self.angle)) v = self.U * np.sin(np.radians(self.angle)) self.verts = self.Q._make_verts([[0.0, 0.0]], np.array([u]), np.array([v]), 'uv') kwargs = self.Q.polykw kwargs.update(self.kw) self.vector = mcollections.PolyCollection(self.verts, offsets=[(self.X, self.Y)], offset_transform=self.get_transform(), **kwargs) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self.vector.set_figure(self.get_figure()) self._dpi_at_last_init = self.Q.axes.get_figure(root=True).dpi def _text_shift(self): return {'N': (0, +self.labelsep), 'S': (0, -self.labelsep), 'E': (+self.labelsep, 0), 'W': (-self.labelsep, 0)}[self.labelpos] @martist.allow_rasterization def draw(self, renderer): self._init() self.vector.draw(renderer) pos = self.get_transform().transform((self.X, self.Y)) self.text.set_position(pos + self._text_shift()) self.text.draw(renderer) self.stale = False def _set_transform(self): fig = self.Q.axes.get_figure(root=False) self.set_transform(_api.check_getitem({'data': self.Q.axes.transData, 'axes': self.Q.axes.transAxes, 'figure': fig.transFigure, 'inches': fig.dpi_scale_trans}, coordinates=self.coord)) def set_figure(self, fig): super().set_figure(fig) self.text.set_figure(fig) def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) if self.text.contains(mouseevent)[0] or self.vector.contains(mouseevent)[0]: return (True, {}) return (False, {}) def _parse_args(*args, caller_name='function'): X = Y = C = None nargs = len(args) if nargs == 2: (U, V) = np.atleast_1d(*args) elif nargs == 3: (U, V, C) = np.atleast_1d(*args) elif nargs == 4: (X, Y, U, V) = np.atleast_1d(*args) elif nargs == 5: (X, Y, U, V, C) = np.atleast_1d(*args) else: raise _api.nargs_error(caller_name, takes='from 2 to 5', given=nargs) (nr, nc) = (1, U.shape[0]) if U.ndim == 1 else U.shape if X is not None: X = X.ravel() Y = Y.ravel() if len(X) == nc and len(Y) == nr: (X, Y) = (a.ravel() for a in np.meshgrid(X, Y)) elif len(X) != len(Y): raise ValueError(f'X and Y must be the same size, but X.size is {X.size} and Y.size is {Y.size}.') else: indexgrid = np.meshgrid(np.arange(nc), np.arange(nr)) (X, Y) = (np.ravel(a) for a in indexgrid) return (X, Y, U, V, C) def _check_consistent_shapes(*arrays): all_shapes = {a.shape for a in arrays} if len(all_shapes) != 1: raise ValueError('The shapes of the passed in arrays do not match') class Quiver(mcollections.PolyCollection): _PIVOT_VALS = ('tail', 'middle', 'tip') @_docstring.Substitution(_quiver_doc) def __init__(self, ax, *args, scale=None, headwidth=3, headlength=5, headaxislength=4.5, minshaft=1, minlength=1, units='width', scale_units=None, angles='uv', width=None, color='k', pivot='tail', **kwargs): self._axes = ax (X, Y, U, V, C) = _parse_args(*args, caller_name='quiver') self.X = X self.Y = Y self.XY = np.column_stack((X, Y)) self.N = len(X) self.scale = scale self.headwidth = headwidth self.headlength = float(headlength) self.headaxislength = headaxislength self.minshaft = minshaft self.minlength = minlength self.units = units self.scale_units = scale_units self.angles = angles self.width = width if pivot.lower() == 'mid': pivot = 'middle' self.pivot = pivot.lower() _api.check_in_list(self._PIVOT_VALS, pivot=self.pivot) self.transform = kwargs.pop('transform', ax.transData) kwargs.setdefault('facecolors', color) kwargs.setdefault('linewidths', (0,)) super().__init__([], offsets=self.XY, offset_transform=self.transform, closed=False, **kwargs) self.polykw = kwargs self.set_UVC(U, V, C) self._dpi_at_last_init = None def _init(self): if True: trans = self._set_transform() self.span = trans.inverted().transform_bbox(self.axes.bbox).width if self.width is None: sn = np.clip(math.sqrt(self.N), 8, 25) self.width = 0.06 * self.span / sn if self._dpi_at_last_init != self.axes.get_figure(root=True).dpi and self.scale is None: self._make_verts(self.XY, self.U, self.V, self.angles) self._dpi_at_last_init = self.axes.get_figure(root=True).dpi def get_datalim(self, transData): trans = self.get_transform() offset_trf = self.get_offset_transform() full_transform = trans - transData + (offset_trf - transData) XY = full_transform.transform(self.XY) bbox = transforms.Bbox.null() bbox.update_from_data_xy(XY, ignore=True) return bbox @martist.allow_rasterization def draw(self, renderer): self._init() verts = self._make_verts(self.XY, self.U, self.V, self.angles) self.set_verts(verts, closed=False) super().draw(renderer) self.stale = False def set_UVC(self, U, V, C=None): U = ma.masked_invalid(U, copy=True).ravel() V = ma.masked_invalid(V, copy=True).ravel() if C is not None: C = ma.masked_invalid(C, copy=True).ravel() for (name, var) in zip(('U', 'V', 'C'), (U, V, C)): if not (var is None or var.size == self.N or var.size == 1): raise ValueError(f'Argument {name} has a size {var.size} which does not match {self.N}, the number of arrow positions') mask = ma.mask_or(U.mask, V.mask, copy=False, shrink=True) if C is not None: mask = ma.mask_or(mask, C.mask, copy=False, shrink=True) if mask is ma.nomask: C = C.filled() else: C = ma.array(C, mask=mask, copy=False) self.U = U.filled(1) self.V = V.filled(1) self.Umask = mask if C is not None: self.set_array(C) self.stale = True def _dots_per_unit(self, units): bb = self.axes.bbox vl = self.axes.viewLim return _api.check_getitem({'x': bb.width / vl.width, 'y': bb.height / vl.height, 'xy': np.hypot(*bb.size) / np.hypot(*vl.size), 'width': bb.width, 'height': bb.height, 'dots': 1.0, 'inches': self.axes.get_figure(root=True).dpi}, units=units) def _set_transform(self): dx = self._dots_per_unit(self.units) self._trans_scale = dx trans = transforms.Affine2D().scale(dx) self.set_transform(trans) return trans def _angles_lengths(self, XY, U, V, eps=1): xy = self.axes.transData.transform(XY) uv = np.column_stack((U, V)) xyp = self.axes.transData.transform(XY + eps * uv) dxy = xyp - xy angles = np.arctan2(dxy[:, 1], dxy[:, 0]) lengths = np.hypot(*dxy.T) / eps return (angles, lengths) def _make_verts(self, XY, U, V, angles): uv = U + V * 1j str_angles = angles if isinstance(angles, str) else '' if str_angles == 'xy' and self.scale_units == 'xy': (angles, lengths) = self._angles_lengths(XY, U, V, eps=1) elif str_angles == 'xy' or self.scale_units == 'xy': eps = np.abs(self.axes.dataLim.extents).max() * 0.001 (angles, lengths) = self._angles_lengths(XY, U, V, eps=eps) if str_angles and self.scale_units == 'xy': a = lengths else: a = np.abs(uv) if self.scale is None: sn = max(10, math.sqrt(self.N)) if self.Umask is not ma.nomask: amean = a[~self.Umask].mean() else: amean = a.mean() scale = 1.8 * amean * sn / self.span if self.scale_units is None: if self.scale is None: self.scale = scale widthu_per_lenu = 1.0 else: if self.scale_units == 'xy': dx = 1 else: dx = self._dots_per_unit(self.scale_units) widthu_per_lenu = dx / self._trans_scale if self.scale is None: self.scale = scale * widthu_per_lenu length = a * (widthu_per_lenu / (self.scale * self.width)) (X, Y) = self._h_arrows(length) if str_angles == 'xy': theta = angles elif str_angles == 'uv': theta = np.angle(uv) else: theta = ma.masked_invalid(np.deg2rad(angles)).filled(0) theta = theta.reshape((-1, 1)) xy = (X + Y * 1j) * np.exp(1j * theta) * self.width XY = np.stack((xy.real, xy.imag), axis=2) if self.Umask is not ma.nomask: XY = ma.array(XY) XY[self.Umask] = ma.masked return XY def _h_arrows(self, length): minsh = self.minshaft * self.headlength N = len(length) length = length.reshape(N, 1) np.clip(length, 0, 2 ** 16, out=length) x = np.array([0, -self.headaxislength, -self.headlength, 0], np.float64) x = x + np.array([0, 1, 1, 1]) * length y = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64) y = np.repeat(y[np.newaxis, :], N, axis=0) x0 = np.array([0, minsh - self.headaxislength, minsh - self.headlength, minsh], np.float64) y0 = 0.5 * np.array([1, 1, self.headwidth, 0], np.float64) ii = [0, 1, 2, 3, 2, 1, 0, 0] X = x[:, ii] Y = y[:, ii] Y[:, 3:-1] *= -1 X0 = x0[ii] Y0 = y0[ii] Y0[3:-1] *= -1 shrink = length / minsh if minsh != 0.0 else 0.0 X0 = shrink * X0[np.newaxis, :] Y0 = shrink * Y0[np.newaxis, :] short = np.repeat(length < minsh, 8, axis=1) np.copyto(X, X0, where=short) np.copyto(Y, Y0, where=short) if self.pivot == 'middle': X -= 0.5 * X[:, 3, np.newaxis] elif self.pivot == 'tip': X = X - X[:, 3, np.newaxis] elif self.pivot != 'tail': _api.check_in_list(['middle', 'tip', 'tail'], pivot=self.pivot) tooshort = length < self.minlength if tooshort.any(): th = np.arange(0, 8, 1, np.float64) * (np.pi / 3.0) x1 = np.cos(th) * self.minlength * 0.5 y1 = np.sin(th) * self.minlength * 0.5 X1 = np.repeat(x1[np.newaxis, :], N, axis=0) Y1 = np.repeat(y1[np.newaxis, :], N, axis=0) tooshort = np.repeat(tooshort, 8, 1) np.copyto(X, X1, where=tooshort) np.copyto(Y, Y1, where=tooshort) return (X, Y) _barbs_doc = '\nPlot a 2D field of wind barbs.\n\nCall signature::\n\n barbs([X, Y], U, V, [C], /, **kwargs)\n\nWhere *X*, *Y* define the barb locations, *U*, *V* define the barb\ndirections, and *C* optionally sets the color.\n\nThe arguments *X*, *Y*, *U*, *V*, *C* are positional-only and may be\n1D or 2D. *U*, *V*, *C* may be masked arrays, but masked *X*, *Y*\nare not supported at present.\n\nBarbs are traditionally used in meteorology as a way to plot the speed\nand direction of wind observations, but can technically be used to\nplot any two dimensional vector quantity. As opposed to arrows, which\ngive vector magnitude by the length of the arrow, the barbs give more\nquantitative information about the vector magnitude by putting slanted\nlines or a triangle for various increments in magnitude, as show\nschematically below::\n\n : /\\ \\\n : / \\ \\\n : / \\ \\ \\\n : / \\ \\ \\\n : ------------------------------\n\nThe largest increment is given by a triangle (or "flag"). After those\ncome full lines (barbs). The smallest increment is a half line. There\nis only, of course, ever at most 1 half line. If the magnitude is\nsmall and only needs a single half-line and no full lines or\ntriangles, the half-line is offset from the end of the barb so that it\ncan be easily distinguished from barbs with a single full line. The\nmagnitude for the barb shown above would nominally be 65, using the\nstandard increments of 50, 10, and 5.\n\nSee also https://en.wikipedia.org/wiki/Wind_barb.\n\nParameters\n----------\nX, Y : 1D or 2D array-like, optional\n The x and y coordinates of the barb locations. See *pivot* for how the\n barbs are drawn to the x, y positions.\n\n If not given, they will be generated as a uniform integer meshgrid based\n on the dimensions of *U* and *V*.\n\n If *X* and *Y* are 1D but *U*, *V* are 2D, *X*, *Y* are expanded to 2D\n using ``X, Y = np.meshgrid(X, Y)``. In this case ``len(X)`` and ``len(Y)``\n must match the column and row dimensions of *U* and *V*.\n\nU, V : 1D or 2D array-like\n The x and y components of the barb shaft.\n\nC : 1D or 2D array-like, optional\n Numeric data that defines the barb colors by colormapping via *norm* and\n *cmap*.\n\n This does not support explicit colors. If you want to set colors directly,\n use *barbcolor* instead.\n\nlength : float, default: 7\n Length of the barb in points; the other parts of the barb\n are scaled against this.\n\npivot : {\'tip\', \'middle\'} or float, default: \'tip\'\n The part of the arrow that is anchored to the *X*, *Y* grid. The barb\n rotates about this point. This can also be a number, which shifts the\n start of the barb that many points away from grid point.\n\nbarbcolor : :mpltype:`color` or color sequence\n The color of all parts of the barb except for the flags. This parameter\n is analogous to the *edgecolor* parameter for polygons, which can be used\n instead. However this parameter will override facecolor.\n\nflagcolor : :mpltype:`color` or color sequence\n The color of any flags on the barb. This parameter is analogous to the\n *facecolor* parameter for polygons, which can be used instead. However,\n this parameter will override facecolor. If this is not set (and *C* has\n not either) then *flagcolor* will be set to match *barbcolor* so that the\n barb has a uniform color. If *C* has been set, *flagcolor* has no effect.\n\nsizes : dict, optional\n A dictionary of coefficients specifying the ratio of a given\n feature to the length of the barb. Only those values one wishes to\n override need to be included. These features include:\n\n - \'spacing\' - space between features (flags, full/half barbs)\n - \'height\' - height (distance from shaft to top) of a flag or full barb\n - \'width\' - width of a flag, twice the width of a full barb\n - \'emptybarb\' - radius of the circle used for low magnitudes\n\nfill_empty : bool, default: False\n Whether the empty barbs (circles) that are drawn should be filled with\n the flag color. If they are not filled, the center is transparent.\n\nrounding : bool, default: True\n Whether the vector magnitude should be rounded when allocating barb\n components. If True, the magnitude is rounded to the nearest multiple\n of the half-barb increment. If False, the magnitude is simply truncated\n to the next lowest multiple.\n\nbarb_increments : dict, optional\n A dictionary of increments specifying values to associate with\n different parts of the barb. Only those values one wishes to\n override need to be included.\n\n - \'half\' - half barbs (Default is 5)\n - \'full\' - full barbs (Default is 10)\n - \'flag\' - flags (default is 50)\n\nflip_barb : bool or array-like of bool, default: False\n Whether the lines and flags should point opposite to normal.\n Normal behavior is for the barbs and lines to point right (comes from wind\n barbs having these features point towards low pressure in the Northern\n Hemisphere).\n\n A single value is applied to all barbs. Individual barbs can be flipped by\n passing a bool array of the same size as *U* and *V*.\n\nReturns\n-------\nbarbs : `~matplotlib.quiver.Barbs`\n\nOther Parameters\n----------------\ndata : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n**kwargs\n The barbs can further be customized using `.PolyCollection` keyword\n arguments:\n\n %(PolyCollection:kwdoc)s\n' % _docstring.interpd.params _docstring.interpd.update(barbs_doc=_barbs_doc) class Barbs(mcollections.PolyCollection): @_docstring.interpd def __init__(self, ax, *args, pivot='tip', length=7, barbcolor=None, flagcolor=None, sizes=None, fill_empty=False, barb_increments=None, rounding=True, flip_barb=False, **kwargs): self.sizes = sizes or dict() self.fill_empty = fill_empty self.barb_increments = barb_increments or dict() self.rounding = rounding self.flip = np.atleast_1d(flip_barb) transform = kwargs.pop('transform', ax.transData) self._pivot = pivot self._length = length if None in (barbcolor, flagcolor): kwargs['edgecolors'] = 'face' if flagcolor: kwargs['facecolors'] = flagcolor elif barbcolor: kwargs['facecolors'] = barbcolor else: kwargs.setdefault('facecolors', 'k') else: kwargs['edgecolors'] = barbcolor kwargs['facecolors'] = flagcolor if 'linewidth' not in kwargs and 'lw' not in kwargs: kwargs['linewidth'] = 1 (x, y, u, v, c) = _parse_args(*args, caller_name='barbs') self.x = x self.y = y xy = np.column_stack((x, y)) barb_size = self._length ** 2 / 4 super().__init__([], (barb_size,), offsets=xy, offset_transform=transform, **kwargs) self.set_transform(transforms.IdentityTransform()) self.set_UVC(u, v, c) def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50): if rounding: mag = half * np.around(mag / half) (n_flags, mag) = divmod(mag, flag) (n_barb, mag) = divmod(mag, full) half_flag = mag >= half empty_flag = ~(half_flag | (n_flags > 0) | (n_barb > 0)) return (n_flags.astype(int), n_barb.astype(int), half_flag, empty_flag) def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length, pivot, sizes, fill_empty, flip): spacing = length * sizes.get('spacing', 0.125) full_height = length * sizes.get('height', 0.4) full_width = length * sizes.get('width', 0.25) empty_rad = length * sizes.get('emptybarb', 0.15) pivot_points = dict(tip=0.0, middle=-length / 2.0) endx = 0.0 try: endy = float(pivot) except ValueError: endy = pivot_points[pivot.lower()] angles = -(ma.arctan2(v, u) + np.pi / 2) circ = CirclePolygon((0, 0), radius=empty_rad).get_verts() if fill_empty: empty_barb = circ else: empty_barb = np.concatenate((circ, circ[::-1])) barb_list = [] for (index, angle) in np.ndenumerate(angles): if empty_flag[index]: barb_list.append(empty_barb) continue poly_verts = [(endx, endy)] offset = length barb_height = -full_height if flip[index] else full_height for i in range(nflags[index]): if offset != length: offset += spacing / 2.0 poly_verts.extend([[endx, endy + offset], [endx + barb_height, endy - full_width / 2 + offset], [endx, endy - full_width + offset]]) offset -= full_width + spacing for i in range(nbarbs[index]): poly_verts.extend([(endx, endy + offset), (endx + barb_height, endy + offset + full_width / 2), (endx, endy + offset)]) offset -= spacing if half_barb[index]: if offset == length: poly_verts.append((endx, endy + offset)) offset -= 1.5 * spacing poly_verts.extend([(endx, endy + offset), (endx + barb_height / 2, endy + offset + full_width / 4), (endx, endy + offset)]) poly_verts = transforms.Affine2D().rotate(-angle).transform(poly_verts) barb_list.append(poly_verts) return barb_list def set_UVC(self, U, V, C=None): self.u = ma.masked_invalid(U, copy=True).ravel() self.v = ma.masked_invalid(V, copy=True).ravel() if len(self.flip) == 1: flip = np.broadcast_to(self.flip, self.u.shape) else: flip = self.flip if C is not None: c = ma.masked_invalid(C, copy=True).ravel() (x, y, u, v, c, flip) = cbook.delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v, c, flip.ravel()) _check_consistent_shapes(x, y, u, v, c, flip) else: (x, y, u, v, flip) = cbook.delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v, flip.ravel()) _check_consistent_shapes(x, y, u, v, flip) magnitude = np.hypot(u, v) (flags, barbs, halves, empty) = self._find_tails(magnitude, self.rounding, **self.barb_increments) plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty, self._length, self._pivot, self.sizes, self.fill_empty, flip) self.set_verts(plot_barbs) if C is not None: self.set_array(c) xy = np.column_stack((x, y)) self._offsets = xy self.stale = True def set_offsets(self, xy): self.x = xy[:, 0] self.y = xy[:, 1] (x, y, u, v) = cbook.delete_masked_points(self.x.ravel(), self.y.ravel(), self.u, self.v) _check_consistent_shapes(x, y, u, v) xy = np.column_stack((x, y)) super().set_offsets(xy) self.stale = True # File: matplotlib-main/lib/matplotlib/sankey.py """""" import logging from types import SimpleNamespace import numpy as np import matplotlib as mpl from matplotlib.path import Path from matplotlib.patches import PathPatch from matplotlib.transforms import Affine2D from matplotlib import _docstring _log = logging.getLogger(__name__) __author__ = 'Kevin L. Davies' __credits__ = ['Yannick Copin'] __license__ = 'BSD' __version__ = '2011/09/16' RIGHT = 0 UP = 1 DOWN = 3 class Sankey: def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25, radius=0.1, shoulder=0.03, offset=0.15, head_angle=100, margin=0.4, tolerance=1e-06, **kwargs): if gap < 0: raise ValueError("'gap' is negative, which is not allowed because it would cause the paths to overlap") if radius > gap: raise ValueError("'radius' is greater than 'gap', which is not allowed because it would cause the paths to overlap") if head_angle < 0: raise ValueError("'head_angle' is negative, which is not allowed because it would cause inputs to look like outputs and vice versa") if tolerance < 0: raise ValueError("'tolerance' is negative, but it must be a magnitude") if ax is None: import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[]) self.diagrams = [] self.ax = ax self.unit = unit self.format = format self.scale = scale self.gap = gap self.radius = radius self.shoulder = shoulder self.offset = offset self.margin = margin self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0) self.tolerance = tolerance self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf)) if len(kwargs): self.add(**kwargs) def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)): ARC_CODES = [Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4] ARC_VERTICES = np.array([[1.0, 0.0], [1.0, 0.265114773], [0.894571235, 0.519642327], [0.707106781, 0.707106781], [0.519642327, 0.894571235], [0.265114773, 1.0], [0.0, 1.0]]) if quadrant in (0, 2): if cw: vertices = ARC_VERTICES else: vertices = ARC_VERTICES[:, ::-1] elif cw: vertices = np.column_stack((-ARC_VERTICES[:, 1], ARC_VERTICES[:, 0])) else: vertices = np.column_stack((-ARC_VERTICES[:, 0], ARC_VERTICES[:, 1])) if quadrant > 1: radius = -radius return list(zip(ARC_CODES, radius * vertices + np.tile(center, (ARC_VERTICES.shape[0], 1)))) def _add_input(self, path, angle, flow, length): if angle is None: return ([0, 0], [0, 0]) else: (x, y) = path[-1][1] dipdepth = flow / 2 * self.pitch if angle == RIGHT: x -= length dip = [x + dipdepth, y + flow / 2.0] path.extend([(Path.LINETO, [x, y]), (Path.LINETO, dip), (Path.LINETO, [x, y + flow]), (Path.LINETO, [x + self.gap, y + flow])]) label_location = [dip[0] - self.offset, dip[1]] else: x -= self.gap if angle == UP: sign = 1 else: sign = -1 dip = [x - flow / 2, y - sign * (length - dipdepth)] if angle == DOWN: quadrant = 2 else: quadrant = 1 if self.radius: path.extend(self._arc(quadrant=quadrant, cw=angle == UP, radius=self.radius, center=(x + self.radius, y - sign * self.radius))) else: path.append((Path.LINETO, [x, y])) path.extend([(Path.LINETO, [x, y - sign * length]), (Path.LINETO, dip), (Path.LINETO, [x - flow, y - sign * length])]) path.extend(self._arc(quadrant=quadrant, cw=angle == DOWN, radius=flow + self.radius, center=(x + self.radius, y - sign * self.radius))) path.append((Path.LINETO, [x - flow, y + sign * flow])) label_location = [dip[0], dip[1] - sign * self.offset] return (dip, label_location) def _add_output(self, path, angle, flow, length): if angle is None: return ([0, 0], [0, 0]) else: (x, y) = path[-1][1] tipheight = (self.shoulder - flow / 2) * self.pitch if angle == RIGHT: x += length tip = [x + tipheight, y + flow / 2.0] path.extend([(Path.LINETO, [x, y]), (Path.LINETO, [x, y + self.shoulder]), (Path.LINETO, tip), (Path.LINETO, [x, y - self.shoulder + flow]), (Path.LINETO, [x, y + flow]), (Path.LINETO, [x - self.gap, y + flow])]) label_location = [tip[0] + self.offset, tip[1]] else: x += self.gap if angle == UP: (sign, quadrant) = (1, 3) else: (sign, quadrant) = (-1, 0) tip = [x - flow / 2.0, y + sign * (length + tipheight)] if self.radius: path.extend(self._arc(quadrant=quadrant, cw=angle == UP, radius=self.radius, center=(x - self.radius, y + sign * self.radius))) else: path.append((Path.LINETO, [x, y])) path.extend([(Path.LINETO, [x, y + sign * length]), (Path.LINETO, [x - self.shoulder, y + sign * length]), (Path.LINETO, tip), (Path.LINETO, [x + self.shoulder - flow, y + sign * length]), (Path.LINETO, [x - flow, y + sign * length])]) path.extend(self._arc(quadrant=quadrant, cw=angle == DOWN, radius=self.radius - flow, center=(x - self.radius, y + sign * self.radius))) path.append((Path.LINETO, [x - flow, y + sign * flow])) label_location = [tip[0], tip[1] + sign * self.offset] return (tip, label_location) def _revert(self, path, first_action=Path.LINETO): reverse_path = [] next_code = first_action for (code, position) in path[::-1]: reverse_path.append((next_code, position)) next_code = code return reverse_path @_docstring.dedent_interpd def add(self, patchlabel='', flows=None, orientations=None, labels='', trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0), rotation=0, **kwargs): flows = np.array([1.0, -1.0]) if flows is None else np.array(flows) n = flows.shape[0] if rotation is None: rotation = 0 else: rotation /= 90.0 if orientations is None: orientations = 0 try: orientations = np.broadcast_to(orientations, n) except ValueError: raise ValueError(f"The shapes of 'flows' {np.shape(flows)} and 'orientations' {np.shape(orientations)} are incompatible") from None try: labels = np.broadcast_to(labels, n) except ValueError: raise ValueError(f"The shapes of 'flows' {np.shape(flows)} and 'labels' {np.shape(labels)} are incompatible") from None if trunklength < 0: raise ValueError("'trunklength' is negative, which is not allowed because it would cause poor layout") if abs(np.sum(flows)) > self.tolerance: _log.info('The sum of the flows is nonzero (%f; patchlabel=%r); is the system not at steady state?', np.sum(flows), patchlabel) scaled_flows = self.scale * flows gain = sum((max(flow, 0) for flow in scaled_flows)) loss = sum((min(flow, 0) for flow in scaled_flows)) if prior is not None: if prior < 0: raise ValueError('The index of the prior diagram is negative') if min(connect) < 0: raise ValueError('At least one of the connection indices is negative') if prior >= len(self.diagrams): raise ValueError(f'The index of the prior diagram is {prior}, but there are only {len(self.diagrams)} other diagrams') if connect[0] >= len(self.diagrams[prior].flows): raise ValueError('The connection index to the source diagram is {}, but that diagram has only {} flows'.format(connect[0], len(self.diagrams[prior].flows))) if connect[1] >= n: raise ValueError(f'The connection index to this diagram is {connect[1]}, but this diagram has only {n} flows') if self.diagrams[prior].angles[connect[0]] is None: raise ValueError(f'The connection cannot be made, which may occur if the magnitude of flow {connect[0]} of diagram {prior} is less than the specified tolerance') flow_error = self.diagrams[prior].flows[connect[0]] + flows[connect[1]] if abs(flow_error) >= self.tolerance: raise ValueError(f'The scaled sum of the connected flows is {flow_error}, which is not within the tolerance ({self.tolerance})') are_inputs = [None] * n for (i, flow) in enumerate(flows): if flow >= self.tolerance: are_inputs[i] = True elif flow <= -self.tolerance: are_inputs[i] = False else: _log.info('The magnitude of flow %d (%f) is below the tolerance (%f).\nIt will not be shown, and it cannot be used in a connection.', i, flow, self.tolerance) angles = [None] * n for (i, (orient, is_input)) in enumerate(zip(orientations, are_inputs)): if orient == 1: if is_input: angles[i] = DOWN elif is_input is False: angles[i] = UP elif orient == 0: if is_input is not None: angles[i] = RIGHT else: if orient != -1: raise ValueError(f'The value of orientations[{i}] is {orient}, but it must be -1, 0, or 1') if is_input: angles[i] = UP elif is_input is False: angles[i] = DOWN if np.iterable(pathlengths): if len(pathlengths) != n: raise ValueError(f"The lengths of 'flows' ({n}) and 'pathlengths' ({len(pathlengths)}) are incompatible") else: urlength = pathlengths ullength = pathlengths lrlength = pathlengths lllength = pathlengths d = dict(RIGHT=pathlengths) pathlengths = [d.get(angle, 0) for angle in angles] for (i, (angle, is_input, flow)) in enumerate(zip(angles, are_inputs, scaled_flows)): if angle == DOWN and is_input: pathlengths[i] = ullength ullength += flow elif angle == UP and is_input is False: pathlengths[i] = urlength urlength -= flow for (i, (angle, is_input, flow)) in enumerate(reversed(list(zip(angles, are_inputs, scaled_flows)))): if angle == UP and is_input: pathlengths[n - i - 1] = lllength lllength += flow elif angle == DOWN and is_input is False: pathlengths[n - i - 1] = lrlength lrlength -= flow has_left_input = False for (i, (angle, is_input, spec)) in enumerate(reversed(list(zip(angles, are_inputs, zip(scaled_flows, pathlengths))))): if angle == RIGHT: if is_input: if has_left_input: pathlengths[n - i - 1] = 0 else: has_left_input = True has_right_output = False for (i, (angle, is_input, spec)) in enumerate(zip(angles, are_inputs, list(zip(scaled_flows, pathlengths)))): if angle == RIGHT: if is_input is False: if has_right_output: pathlengths[i] = 0 else: has_right_output = True urpath = [(Path.MOVETO, [self.gap - trunklength / 2.0, gain / 2.0]), (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, gain / 2.0]), (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, gain / 2.0]), (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, -loss / 2.0]), (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, -loss / 2.0]), (Path.LINETO, [trunklength / 2.0 - self.gap, -loss / 2.0])] llpath = [(Path.LINETO, [trunklength / 2.0 - self.gap, loss / 2.0]), (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0, loss / 2.0]), (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0, loss / 2.0]), (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0, -gain / 2.0]), (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0, -gain / 2.0]), (Path.LINETO, [self.gap - trunklength / 2.0, -gain / 2.0])] lrpath = [(Path.LINETO, [trunklength / 2.0 - self.gap, loss / 2.0])] ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, gain / 2.0])] tips = np.zeros((n, 2)) label_locations = np.zeros((n, 2)) for (i, (angle, is_input, spec)) in enumerate(zip(angles, are_inputs, list(zip(scaled_flows, pathlengths)))): if angle == DOWN and is_input: (tips[i, :], label_locations[i, :]) = self._add_input(ulpath, angle, *spec) elif angle == UP and is_input is False: (tips[i, :], label_locations[i, :]) = self._add_output(urpath, angle, *spec) for (i, (angle, is_input, spec)) in enumerate(reversed(list(zip(angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): if angle == UP and is_input: (tip, label_location) = self._add_input(llpath, angle, *spec) tips[n - i - 1, :] = tip label_locations[n - i - 1, :] = label_location elif angle == DOWN and is_input is False: (tip, label_location) = self._add_output(lrpath, angle, *spec) tips[n - i - 1, :] = tip label_locations[n - i - 1, :] = label_location has_left_input = False for (i, (angle, is_input, spec)) in enumerate(reversed(list(zip(angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): if angle == RIGHT and is_input: if not has_left_input: if llpath[-1][1][0] > ulpath[-1][1][0]: llpath.append((Path.LINETO, [ulpath[-1][1][0], llpath[-1][1][1]])) has_left_input = True (tip, label_location) = self._add_input(llpath, angle, *spec) tips[n - i - 1, :] = tip label_locations[n - i - 1, :] = label_location has_right_output = False for (i, (angle, is_input, spec)) in enumerate(zip(angles, are_inputs, list(zip(scaled_flows, pathlengths)))): if angle == RIGHT and is_input is False: if not has_right_output: if urpath[-1][1][0] < lrpath[-1][1][0]: urpath.append((Path.LINETO, [lrpath[-1][1][0], urpath[-1][1][1]])) has_right_output = True (tips[i, :], label_locations[i, :]) = self._add_output(urpath, angle, *spec) if not has_left_input: ulpath.pop() llpath.pop() if not has_right_output: lrpath.pop() urpath.pop() path = urpath + self._revert(lrpath) + llpath + self._revert(ulpath) + [(Path.CLOSEPOLY, urpath[0][1])] (codes, vertices) = zip(*path) vertices = np.array(vertices) def _get_angle(a, r): if a is None: return None else: return a + r if prior is None: if rotation != 0: angles = [_get_angle(angle, rotation) for angle in angles] rotate = Affine2D().rotate_deg(rotation * 90).transform_affine tips = rotate(tips) label_locations = rotate(label_locations) vertices = rotate(vertices) text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center') else: rotation = self.diagrams[prior].angles[connect[0]] - angles[connect[1]] angles = [_get_angle(angle, rotation) for angle in angles] rotate = Affine2D().rotate_deg(rotation * 90).transform_affine tips = rotate(tips) offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]] translate = Affine2D().translate(*offset).transform_affine tips = translate(tips) label_locations = translate(rotate(label_locations)) vertices = translate(rotate(vertices)) kwds = dict(s=patchlabel, ha='center', va='center') text = self.ax.text(*offset, **kwds) if mpl.rcParams['_internal.classic_mode']: fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4')) lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5)) else: fc = kwargs.pop('fc', kwargs.pop('facecolor', None)) lw = kwargs.pop('lw', kwargs.pop('linewidth', None)) if fc is None: fc = self.ax._get_patches_for_fill.get_next_color() patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs) self.ax.add_patch(patch) texts = [] for (number, angle, label, location) in zip(flows, angles, labels, label_locations): if label is None or angle is None: label = '' elif self.unit is not None: if isinstance(self.format, str): quantity = self.format % abs(number) + self.unit elif callable(self.format): quantity = self.format(number) else: raise TypeError('format must be callable or a format string') if label != '': label += '\n' label += quantity texts.append(self.ax.text(x=location[0], y=location[1], s=label, ha='center', va='center')) self.extent = (min(np.min(vertices[:, 0]), np.min(label_locations[:, 0]), self.extent[0]), max(np.max(vertices[:, 0]), np.max(label_locations[:, 0]), self.extent[1]), min(np.min(vertices[:, 1]), np.min(label_locations[:, 1]), self.extent[2]), max(np.max(vertices[:, 1]), np.max(label_locations[:, 1]), self.extent[3])) self.diagrams.append(SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips, text=text, texts=texts)) return self def finish(self): self.ax.axis([self.extent[0] - self.margin, self.extent[1] + self.margin, self.extent[2] - self.margin, self.extent[3] + self.margin]) self.ax.set_aspect('equal', adjustable='datalim') return self.diagrams # File: matplotlib-main/lib/matplotlib/scale.py """""" import inspect import textwrap import numpy as np import matplotlib as mpl from matplotlib import _api, _docstring from matplotlib.ticker import NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter, NullLocator, LogLocator, AutoLocator, AutoMinorLocator, SymmetricalLogLocator, AsinhLocator, LogitLocator from matplotlib.transforms import Transform, IdentityTransform class ScaleBase: def __init__(self, axis): def get_transform(self): raise NotImplementedError() def set_default_locators_and_formatters(self, axis): raise NotImplementedError() def limit_range_for_scale(self, vmin, vmax, minpos): return (vmin, vmax) class LinearScale(ScaleBase): name = 'linear' def __init__(self, axis): def set_default_locators_and_formatters(self, axis): axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) if axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or (axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']): axis.set_minor_locator(AutoMinorLocator()) else: axis.set_minor_locator(NullLocator()) def get_transform(self): return IdentityTransform() class FuncTransform(Transform): input_dims = output_dims = 1 def __init__(self, forward, inverse): super().__init__() if callable(forward) and callable(inverse): self._forward = forward self._inverse = inverse else: raise ValueError('arguments to FuncTransform must be functions') def transform_non_affine(self, values): return self._forward(values) def inverted(self): return FuncTransform(self._inverse, self._forward) class FuncScale(ScaleBase): name = 'function' def __init__(self, axis, functions): (forward, inverse) = functions transform = FuncTransform(forward, inverse) self._transform = transform def get_transform(self): return self._transform def set_default_locators_and_formatters(self, axis): axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) if axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or (axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']): axis.set_minor_locator(AutoMinorLocator()) else: axis.set_minor_locator(NullLocator()) class LogTransform(Transform): input_dims = output_dims = 1 def __init__(self, base, nonpositive='clip'): super().__init__() if base <= 0 or base == 1: raise ValueError('The log base cannot be <= 0 or == 1') self.base = base self._clip = _api.check_getitem({'clip': True, 'mask': False}, nonpositive=nonpositive) def __str__(self): return '{}(base={}, nonpositive={!r})'.format(type(self).__name__, self.base, 'clip' if self._clip else 'mask') def transform_non_affine(self, values): with np.errstate(divide='ignore', invalid='ignore'): log = {np.e: np.log, 2: np.log2, 10: np.log10}.get(self.base) if log: out = log(values) else: out = np.log(values) out /= np.log(self.base) if self._clip: out[values <= 0] = -1000 return out def inverted(self): return InvertedLogTransform(self.base) class InvertedLogTransform(Transform): input_dims = output_dims = 1 def __init__(self, base): super().__init__() self.base = base def __str__(self): return f'{type(self).__name__}(base={self.base})' def transform_non_affine(self, values): return np.power(self.base, values) def inverted(self): return LogTransform(self.base) class LogScale(ScaleBase): name = 'log' def __init__(self, axis, *, base=10, subs=None, nonpositive='clip'): self._transform = LogTransform(base, nonpositive) self.subs = subs base = property(lambda self: self._transform.base) def set_default_locators_and_formatters(self, axis): axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(LogFormatterSciNotation(self.base, labelOnlyBase=self.subs is not None)) def get_transform(self): return self._transform def limit_range_for_scale(self, vmin, vmax, minpos): if not np.isfinite(minpos): minpos = 1e-300 return (minpos if vmin <= 0 else vmin, minpos if vmax <= 0 else vmax) class FuncScaleLog(LogScale): name = 'functionlog' def __init__(self, axis, functions, base=10): (forward, inverse) = functions self.subs = None self._transform = FuncTransform(forward, inverse) + LogTransform(base) @property def base(self): return self._transform._b.base def get_transform(self): return self._transform class SymmetricalLogTransform(Transform): input_dims = output_dims = 1 def __init__(self, base, linthresh, linscale): super().__init__() if base <= 1.0: raise ValueError("'base' must be larger than 1") if linthresh <= 0.0: raise ValueError("'linthresh' must be positive") if linscale <= 0.0: raise ValueError("'linscale' must be positive") self.base = base self.linthresh = linthresh self.linscale = linscale self._linscale_adj = linscale / (1.0 - self.base ** (-1)) self._log_base = np.log(base) def transform_non_affine(self, values): abs_a = np.abs(values) with np.errstate(divide='ignore', invalid='ignore'): out = np.sign(values) * self.linthresh * (self._linscale_adj + np.log(abs_a / self.linthresh) / self._log_base) inside = abs_a <= self.linthresh out[inside] = values[inside] * self._linscale_adj return out def inverted(self): return InvertedSymmetricalLogTransform(self.base, self.linthresh, self.linscale) class InvertedSymmetricalLogTransform(Transform): input_dims = output_dims = 1 def __init__(self, base, linthresh, linscale): super().__init__() symlog = SymmetricalLogTransform(base, linthresh, linscale) self.base = base self.linthresh = linthresh self.invlinthresh = symlog.transform(linthresh) self.linscale = linscale self._linscale_adj = linscale / (1.0 - self.base ** (-1)) def transform_non_affine(self, values): abs_a = np.abs(values) with np.errstate(divide='ignore', invalid='ignore'): out = np.sign(values) * self.linthresh * np.power(self.base, abs_a / self.linthresh - self._linscale_adj) inside = abs_a <= self.invlinthresh out[inside] = values[inside] / self._linscale_adj return out def inverted(self): return SymmetricalLogTransform(self.base, self.linthresh, self.linscale) class SymmetricalLogScale(ScaleBase): name = 'symlog' def __init__(self, axis, *, base=10, linthresh=2, subs=None, linscale=1): self._transform = SymmetricalLogTransform(base, linthresh, linscale) self.subs = subs base = property(lambda self: self._transform.base) linthresh = property(lambda self: self._transform.linthresh) linscale = property(lambda self: self._transform.linscale) def set_default_locators_and_formatters(self, axis): axis.set_major_locator(SymmetricalLogLocator(self.get_transform())) axis.set_major_formatter(LogFormatterSciNotation(self.base)) axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(), self.subs)) axis.set_minor_formatter(NullFormatter()) def get_transform(self): return self._transform class AsinhTransform(Transform): input_dims = output_dims = 1 def __init__(self, linear_width): super().__init__() if linear_width <= 0.0: raise ValueError("Scale parameter 'linear_width' " + 'must be strictly positive') self.linear_width = linear_width def transform_non_affine(self, values): return self.linear_width * np.arcsinh(values / self.linear_width) def inverted(self): return InvertedAsinhTransform(self.linear_width) class InvertedAsinhTransform(Transform): input_dims = output_dims = 1 def __init__(self, linear_width): super().__init__() self.linear_width = linear_width def transform_non_affine(self, values): return self.linear_width * np.sinh(values / self.linear_width) def inverted(self): return AsinhTransform(self.linear_width) class AsinhScale(ScaleBase): name = 'asinh' auto_tick_multipliers = {3: (2,), 4: (2,), 5: (2,), 8: (2, 4), 10: (2, 5), 16: (2, 4, 8), 64: (4, 16), 1024: (256, 512)} def __init__(self, axis, *, linear_width=1.0, base=10, subs='auto', **kwargs): super().__init__(axis) self._transform = AsinhTransform(linear_width) self._base = int(base) if subs == 'auto': self._subs = self.auto_tick_multipliers.get(self._base) else: self._subs = subs linear_width = property(lambda self: self._transform.linear_width) def get_transform(self): return self._transform def set_default_locators_and_formatters(self, axis): axis.set(major_locator=AsinhLocator(self.linear_width, base=self._base), minor_locator=AsinhLocator(self.linear_width, base=self._base, subs=self._subs), minor_formatter=NullFormatter()) if self._base > 1: axis.set_major_formatter(LogFormatterSciNotation(self._base)) else: axis.set_major_formatter('{x:.3g}') class LogitTransform(Transform): input_dims = output_dims = 1 def __init__(self, nonpositive='mask'): super().__init__() _api.check_in_list(['mask', 'clip'], nonpositive=nonpositive) self._nonpositive = nonpositive self._clip = {'clip': True, 'mask': False}[nonpositive] def transform_non_affine(self, values): with np.errstate(divide='ignore', invalid='ignore'): out = np.log10(values / (1 - values)) if self._clip: out[values <= 0] = -1000 out[1 <= values] = 1000 return out def inverted(self): return LogisticTransform(self._nonpositive) def __str__(self): return f'{type(self).__name__}({self._nonpositive!r})' class LogisticTransform(Transform): input_dims = output_dims = 1 def __init__(self, nonpositive='mask'): super().__init__() self._nonpositive = nonpositive def transform_non_affine(self, values): return 1.0 / (1 + 10 ** (-values)) def inverted(self): return LogitTransform(self._nonpositive) def __str__(self): return f'{type(self).__name__}({self._nonpositive!r})' class LogitScale(ScaleBase): name = 'logit' def __init__(self, axis, nonpositive='mask', *, one_half='\\frac{1}{2}', use_overline=False): self._transform = LogitTransform(nonpositive) self._use_overline = use_overline self._one_half = one_half def get_transform(self): return self._transform def set_default_locators_and_formatters(self, axis): axis.set_major_locator(LogitLocator()) axis.set_major_formatter(LogitFormatter(one_half=self._one_half, use_overline=self._use_overline)) axis.set_minor_locator(LogitLocator(minor=True)) axis.set_minor_formatter(LogitFormatter(minor=True, one_half=self._one_half, use_overline=self._use_overline)) def limit_range_for_scale(self, vmin, vmax, minpos): if not np.isfinite(minpos): minpos = 1e-07 return (minpos if vmin <= 0 else vmin, 1 - minpos if vmax >= 1 else vmax) _scale_mapping = {'linear': LinearScale, 'log': LogScale, 'symlog': SymmetricalLogScale, 'asinh': AsinhScale, 'logit': LogitScale, 'function': FuncScale, 'functionlog': FuncScaleLog} def get_scale_names(): return sorted(_scale_mapping) def scale_factory(scale, axis, **kwargs): scale_cls = _api.check_getitem(_scale_mapping, scale=scale) return scale_cls(axis, **kwargs) if scale_factory.__doc__: scale_factory.__doc__ = scale_factory.__doc__ % {'names': ', '.join(map(repr, get_scale_names()))} def register_scale(scale_class): _scale_mapping[scale_class.name] = scale_class def _get_scale_docs(): docs = [] for (name, scale_class) in _scale_mapping.items(): docstring = inspect.getdoc(scale_class.__init__) or '' docs.extend([f' {name!r}', '', textwrap.indent(docstring, ' ' * 8), '']) return '\n'.join(docs) _docstring.interpd.update(scale_type='{%s}' % ', '.join([repr(x) for x in get_scale_names()]), scale_docs=_get_scale_docs().rstrip()) # File: matplotlib-main/lib/matplotlib/sphinxext/figmpl_directive.py """""" from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst.directives.images import Figure, Image import os from os.path import relpath from pathlib import PurePath, Path import shutil from sphinx.errors import ExtensionError import matplotlib class figmplnode(nodes.General, nodes.Element): pass class FigureMpl(Figure): has_content = False required_arguments = 1 optional_arguments = 2 final_argument_whitespace = False option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': Image.align, 'class': directives.class_option, 'caption': directives.unchanged, 'srcset': directives.unchanged} def run(self): image_node = figmplnode() imagenm = self.arguments[0] image_node['alt'] = self.options.get('alt', '') image_node['align'] = self.options.get('align', None) image_node['class'] = self.options.get('class', None) image_node['width'] = self.options.get('width', None) image_node['height'] = self.options.get('height', None) image_node['scale'] = self.options.get('scale', None) image_node['caption'] = self.options.get('caption', None) image_node['uri'] = imagenm image_node['srcset'] = self.options.get('srcset', None) return [image_node] def _parse_srcsetNodes(st): entries = st.split(',') srcset = {} for entry in entries: spl = entry.strip().split(' ') if len(spl) == 1: srcset[0] = spl[0] elif len(spl) == 2: mult = spl[1][:-1] srcset[float(mult)] = spl[0] else: raise ExtensionError(f'srcset argument "{entry}" is invalid.') return srcset def _copy_images_figmpl(self, node): if node['srcset']: srcset = _parse_srcsetNodes(node['srcset']) else: srcset = None docsource = PurePath(self.document['source']).parent srctop = self.builder.srcdir rel = relpath(docsource, srctop).replace('.', '').replace(os.sep, '-') if len(rel): rel += '-' imagedir = PurePath(self.builder.outdir, self.builder.imagedir) Path(imagedir).mkdir(parents=True, exist_ok=True) if srcset: for src in srcset.values(): abspath = PurePath(docsource, src) name = rel + abspath.name shutil.copyfile(abspath, imagedir / name) else: abspath = PurePath(docsource, node['uri']) name = rel + abspath.name shutil.copyfile(abspath, imagedir / name) return (imagedir, srcset, rel) def visit_figmpl_html(self, node): (imagedir, srcset, rel) = _copy_images_figmpl(self, node) docsource = PurePath(self.document['source']) srctop = PurePath(self.builder.srcdir, '') relsource = relpath(docsource, srctop) desttop = PurePath(self.builder.outdir, '') dest = desttop / relsource imagerel = PurePath(relpath(imagedir, dest.parent)).as_posix() if self.builder.name == 'dirhtml': imagerel = f'..{imagerel}' nm = PurePath(node['uri'][1:]).name uri = f'{imagerel}/{rel}{nm}' maxsrc = uri srcsetst = '' if srcset: maxmult = -1 for (mult, src) in srcset.items(): nm = PurePath(src[1:]).name path = f'{imagerel}/{rel}{nm}' srcsetst += path if mult == 0: srcsetst += ', ' else: srcsetst += f' {mult:1.2f}x, ' if mult > maxmult: maxmult = mult maxsrc = path srcsetst = srcsetst[:-2] alt = node['alt'] if node['class'] is not None: classst = ' '.join(node['class']) classst = f'class="{classst}"' else: classst = '' stylers = ['width', 'height', 'scale'] stylest = '' for style in stylers: if node[style]: stylest += f'{style}: {node[style]};' figalign = node['align'] if node['align'] else 'center' img_block = f'{alt}' html_block = f'
\n' html_block += f' \n' html_block += f' {img_block}\n \n' if node['caption']: html_block += '
\n' html_block += f"""

{node['caption']}

\n""" html_block += '
\n' html_block += '
\n' self.body.append(html_block) def visit_figmpl_latex(self, node): if node['srcset'] is not None: (imagedir, srcset) = _copy_images_figmpl(self, node) maxmult = -1 maxmult = max(srcset, default=-1) node['uri'] = PurePath(srcset[maxmult]).name self.visit_figure(node) def depart_figmpl_html(self, node): pass def depart_figmpl_latex(self, node): self.depart_figure(node) def figurempl_addnode(app): app.add_node(figmplnode, html=(visit_figmpl_html, depart_figmpl_html), latex=(visit_figmpl_latex, depart_figmpl_latex)) def setup(app): app.add_directive('figure-mpl', FigureMpl) figurempl_addnode(app) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': matplotlib.__version__} return metadata # File: matplotlib-main/lib/matplotlib/sphinxext/mathmpl.py """""" import hashlib from pathlib import Path from docutils import nodes from docutils.parsers.rst import Directive, directives import sphinx from sphinx.errors import ConfigError, ExtensionError import matplotlib as mpl from matplotlib import _api, mathtext from matplotlib.rcsetup import validate_float_or_None class latex_math(nodes.General, nodes.Element): pass def fontset_choice(arg): return directives.choice(arg, mathtext.MathTextParser._font_type_mapping) def math_role(role, rawtext, text, lineno, inliner, options={}, content=[]): i = rawtext.find('`') latex = rawtext[i + 1:-1] node = latex_math(rawtext) node['latex'] = latex node['fontset'] = options.get('fontset', 'cm') node['fontsize'] = options.get('fontsize', setup.app.config.mathmpl_fontsize) return ([node], []) math_role.options = {'fontset': fontset_choice, 'fontsize': validate_float_or_None} class MathDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = False option_spec = {'fontset': fontset_choice, 'fontsize': validate_float_or_None} def run(self): latex = ''.join(self.content) node = latex_math(self.block_text) node['latex'] = latex node['fontset'] = self.options.get('fontset', 'cm') node['fontsize'] = self.options.get('fontsize', setup.app.config.mathmpl_fontsize) return [node] def latex2png(latex, filename, fontset='cm', fontsize=10, dpi=100): with mpl.rc_context({'mathtext.fontset': fontset, 'font.size': fontsize}): try: depth = mathtext.math_to_image(f'${latex}$', filename, dpi=dpi, format='png') except Exception: _api.warn_external(f'Could not render math expression {latex}') depth = 0 return depth def latex2html(node, source): inline = isinstance(node.parent, nodes.TextElement) latex = node['latex'] fontset = node['fontset'] fontsize = node['fontsize'] name = 'math-{}'.format(hashlib.md5(f'{latex}{fontset}{fontsize}'.encode()).hexdigest()[-10:]) destdir = Path(setup.app.builder.outdir, '_images', 'mathmpl') destdir.mkdir(parents=True, exist_ok=True) dest = destdir / f'{name}.png' depth = latex2png(latex, dest, fontset, fontsize=fontsize) srcset = [] for size in setup.app.config.mathmpl_srcset: filename = f"{name}-{size.replace('.', '_')}.png" latex2png(latex, destdir / filename, fontset, fontsize=fontsize, dpi=100 * float(size[:-1])) srcset.append(f'{setup.app.builder.imgpath}/mathmpl/{filename} {size}') if srcset: srcset = f'srcset="{setup.app.builder.imgpath}/mathmpl/{name}.png, ' + ', '.join(srcset) + '" ' if inline: cls = '' else: cls = 'class="center" ' if inline and depth != 0: style = 'style="position: relative; bottom: -%dpx"' % (depth + 1) else: style = '' return f'' def _config_inited(app, config): for (i, size) in enumerate(app.config.mathmpl_srcset): if size[-1] == 'x': try: float(size[:-1]) except ValueError: raise ConfigError(f'Invalid value for mathmpl_srcset parameter: {size!r}. Must be a list of strings with the multiplicative factor followed by an "x". e.g. ["2.0x", "1.5x"]') else: raise ConfigError(f'Invalid value for mathmpl_srcset parameter: {size!r}. Must be a list of strings with the multiplicative factor followed by an "x". e.g. ["2.0x", "1.5x"]') def setup(app): setup.app = app app.add_config_value('mathmpl_fontsize', 10.0, True) app.add_config_value('mathmpl_srcset', [], True) try: app.connect('config-inited', _config_inited) except ExtensionError: app.connect('env-updated', lambda app, env: _config_inited(app, None)) def visit_latex_math_html(self, node): source = self.document.attributes['source'] self.body.append(latex2html(node, source)) def depart_latex_math_html(self, node): pass def visit_latex_math_latex(self, node): inline = isinstance(node.parent, nodes.TextElement) if inline: self.body.append('$%s$' % node['latex']) else: self.body.extend(['\\begin{equation}', node['latex'], '\\end{equation}']) def depart_latex_math_latex(self, node): pass app.add_node(latex_math, html=(visit_latex_math_html, depart_latex_math_html), latex=(visit_latex_math_latex, depart_latex_math_latex)) app.add_role('mathmpl', math_role) app.add_directive('mathmpl', MathDirective) if sphinx.version_info < (1, 8): app.add_role('math', math_role) app.add_directive('math', MathDirective) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata # File: matplotlib-main/lib/matplotlib/sphinxext/plot_directive.py """""" import contextlib import doctest from io import StringIO import itertools import os from os.path import relpath from pathlib import Path import re import shutil import sys import textwrap import traceback from docutils.parsers.rst import directives, Directive from docutils.parsers.rst.directives.images import Image import jinja2 from sphinx.errors import ExtensionError import matplotlib from matplotlib.backend_bases import FigureManagerBase import matplotlib.pyplot as plt from matplotlib import _pylab_helpers, cbook matplotlib.use('agg') __version__ = 2 def _option_boolean(arg): if not arg or not arg.strip(): return True elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise ValueError(f'{arg!r} unknown boolean') def _option_context(arg): if arg in [None, 'reset', 'close-figs']: return arg raise ValueError("Argument should be None or 'reset' or 'close-figs'") def _option_format(arg): return directives.choice(arg, ('python', 'doctest')) def mark_plot_labels(app, document): for (name, explicit) in document.nametypes.items(): if not explicit: continue labelid = document.nameids[name] if labelid is None: continue node = document.ids[labelid] if node.tagname in ('html_only', 'latex_only'): for n in node: if n.tagname == 'figure': sectname = name for c in n: if c.tagname == 'caption': sectname = c.astext() break node['ids'].remove(labelid) node['names'].remove(name) n['ids'].append(labelid) n['names'].append(name) document.settings.env.labels[name] = (document.settings.env.docname, labelid, sectname) break class PlotDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 2 final_argument_whitespace = False option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': Image.align, 'class': directives.class_option, 'include-source': _option_boolean, 'show-source-link': _option_boolean, 'format': _option_format, 'context': _option_context, 'nofigs': directives.flag, 'caption': directives.unchanged} def run(self): try: return run(self.arguments, self.content, self.options, self.state_machine, self.state, self.lineno) except Exception as e: raise self.error(str(e)) def _copy_css_file(app, exc): if exc is None and app.builder.format == 'html': src = cbook._get_data_path('plot_directive/plot_directive.css') dst = app.outdir / Path('_static') dst.mkdir(exist_ok=True) shutil.copyfile(src, dst / Path('plot_directive.css')) def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir app.add_directive('plot', PlotDirective) app.add_config_value('plot_pre_code', None, True) app.add_config_value('plot_include_source', False, True) app.add_config_value('plot_html_show_source_link', True, True) app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) app.add_config_value('plot_basedir', None, True) app.add_config_value('plot_html_show_formats', True, True) app.add_config_value('plot_rcparams', {}, True) app.add_config_value('plot_apply_rcparams', False, True) app.add_config_value('plot_working_directory', None, True) app.add_config_value('plot_template', None, True) app.add_config_value('plot_srcset', [], True) app.connect('doctree-read', mark_plot_labels) app.add_css_file('plot_directive.css') app.connect('build-finished', _copy_css_file) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': matplotlib.__version__} return metadata def contains_doctest(text): try: compile(text, '', 'exec') return False except SyntaxError: pass r = re.compile('^\\s*>>>', re.M) m = r.search(text) return bool(m) def _split_code_at_show(text, function_name): is_doctest = contains_doctest(text) if function_name is None: parts = [] part = [] for line in text.split('\n'): if not is_doctest and line.startswith('plt.show(') or (is_doctest and line.strip() == '>>> plt.show()'): part.append(line) parts.append('\n'.join(part)) part = [] else: part.append(line) if '\n'.join(part).strip(): parts.append('\n'.join(part)) else: parts = [text] return (is_doctest, parts) _SOURCECODE = '\n{{ source_code }}\n\n.. only:: html\n\n {% if src_name or (html_show_formats and not multi_image) %}\n (\n {%- if src_name -%}\n :download:`Source code <{{ build_dir }}/{{ src_name }}>`\n {%- endif -%}\n {%- if html_show_formats and not multi_image -%}\n {%- for img in images -%}\n {%- for fmt in img.formats -%}\n {%- if src_name or not loop.first -%}, {% endif -%}\n :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`\n {%- endfor -%}\n {%- endfor -%}\n {%- endif -%}\n )\n {% endif %}\n' TEMPLATE_SRCSET = _SOURCECODE + '\n {% for img in images %}\n .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}\n {% for option in options -%}\n {{ option }}\n {% endfor %}\n {%- if caption -%}\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endif -%}\n {%- if srcset -%}\n :srcset: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}\n {%- for sr in srcset -%}\n , {{ build_dir }}/{{ img.basename }}.{{ sr }}.{{ default_fmt }} {{sr}}\n {%- endfor -%}\n {% endif %}\n\n {% if html_show_formats and multi_image %}\n (\n {%- for fmt in img.formats -%}\n {%- if not loop.first -%}, {% endif -%}\n :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`\n {%- endfor -%}\n )\n {% endif %}\n\n\n {% endfor %}\n\n.. only:: not html\n\n {% for img in images %}\n .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.*\n {% for option in options -%}\n {{ option }}\n {% endfor -%}\n\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endfor %}\n\n' TEMPLATE = _SOURCECODE + '\n\n {% for img in images %}\n .. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}\n {% for option in options -%}\n {{ option }}\n {% endfor %}\n\n {% if html_show_formats and multi_image -%}\n (\n {%- for fmt in img.formats -%}\n {%- if not loop.first -%}, {% endif -%}\n :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`\n {%- endfor -%}\n )\n {%- endif -%}\n\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endfor %}\n\n.. only:: not html\n\n {% for img in images %}\n .. figure:: {{ build_dir }}/{{ img.basename }}.*\n {% for option in options -%}\n {{ option }}\n {% endfor -%}\n\n {{ caption }} {# appropriate leading whitespace added beforehand #}\n {% endfor %}\n\n' exception_template = '\n.. only:: html\n\n [`source code <%(linkdir)s/%(basename)s.py>`__]\n\nException occurred rendering plot.\n\n' plot_context = dict() class ImageFile: def __init__(self, basename, dirname): self.basename = basename self.dirname = dirname self.formats = [] def filename(self, format): return os.path.join(self.dirname, f'{self.basename}.{format}') def filenames(self): return [self.filename(fmt) for fmt in self.formats] def out_of_date(original, derived, includes=None): if not os.path.exists(derived): return True if includes is None: includes = [] files_to_check = [original, *includes] def out_of_date_one(original, derived_mtime): return os.path.exists(original) and derived_mtime < os.stat(original).st_mtime derived_mtime = os.stat(derived).st_mtime return any((out_of_date_one(f, derived_mtime) for f in files_to_check)) class PlotError(RuntimeError): pass def _run_code(code, code_path, ns=None, function_name=None): pwd = os.getcwd() if setup.config.plot_working_directory is not None: try: os.chdir(setup.config.plot_working_directory) except OSError as err: raise OSError(f'{err}\n`plot_working_directory` option in Sphinx configuration file must be a valid directory path') from err except TypeError as err: raise TypeError(f'{err}\n`plot_working_directory` option in Sphinx configuration file must be a string or None') from err elif code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) os.chdir(dirname) with cbook._setattr_cm(sys, argv=[code_path], path=[os.getcwd(), *sys.path]), contextlib.redirect_stdout(StringIO()): try: if ns is None: ns = {} if not ns: if setup.config.plot_pre_code is None: exec('import numpy as np\nfrom matplotlib import pyplot as plt\n', ns) else: exec(str(setup.config.plot_pre_code), ns) if '__main__' in code: ns['__name__'] = '__main__' with cbook._setattr_cm(FigureManagerBase, show=lambda self: None): exec(code, ns) if function_name is not None: exec(function_name + '()', ns) except (Exception, SystemExit) as err: raise PlotError(traceback.format_exc()) from err finally: os.chdir(pwd) return ns def clear_state(plot_rcparams, close=True): if close: plt.close('all') matplotlib.rc_file_defaults() matplotlib.rcParams.update(plot_rcparams) def get_plot_formats(config): default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200} formats = [] plot_formats = config.plot_formats for fmt in plot_formats: if isinstance(fmt, str): if ':' in fmt: (suffix, dpi) = fmt.split(':') formats.append((str(suffix), int(dpi))) else: formats.append((fmt, default_dpi.get(fmt, 80))) elif isinstance(fmt, (tuple, list)) and len(fmt) == 2: formats.append((str(fmt[0]), int(fmt[1]))) else: raise PlotError('invalid image format "%r" in plot_formats' % fmt) return formats def _parse_srcset(entries): srcset = {} for entry in entries: entry = entry.strip() if len(entry) >= 2: mult = entry[:-1] srcset[float(mult)] = entry else: raise ExtensionError(f'srcset argument {entry!r} is invalid.') return srcset def render_figures(code, code_path, output_dir, output_base, context, function_name, config, context_reset=False, close_figs=False, code_includes=None): if function_name is not None: output_base = f'{output_base}_{function_name}' formats = get_plot_formats(config) (is_doctest, code_pieces) = _split_code_at_show(code, function_name) img = ImageFile(output_base, output_dir) for (format, dpi) in formats: if context or out_of_date(code_path, img.filename(format), includes=code_includes): all_exists = False break img.formats.append(format) else: all_exists = True if all_exists: return [(code, [img])] results = [] for (i, code_piece) in enumerate(code_pieces): images = [] for j in itertools.count(): if len(code_pieces) > 1: img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir) else: img = ImageFile('%s_%02d' % (output_base, j), output_dir) for (fmt, dpi) in formats: if context or out_of_date(code_path, img.filename(fmt), includes=code_includes): all_exists = False break img.formats.append(fmt) if not all_exists: all_exists = j > 0 break images.append(img) if not all_exists: break results.append((code_piece, images)) else: all_exists = True if all_exists: return results results = [] ns = plot_context if context else {} if context_reset: clear_state(config.plot_rcparams) plot_context.clear() close_figs = not context or close_figs for (i, code_piece) in enumerate(code_pieces): if not context or config.plot_apply_rcparams: clear_state(config.plot_rcparams, close_figs) elif close_figs: plt.close('all') _run_code(doctest.script_from_examples(code_piece) if is_doctest else code_piece, code_path, ns, function_name) images = [] fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() for (j, figman) in enumerate(fig_managers): if len(fig_managers) == 1 and len(code_pieces) == 1: img = ImageFile(output_base, output_dir) elif len(code_pieces) == 1: img = ImageFile('%s_%02d' % (output_base, j), output_dir) else: img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir) images.append(img) for (fmt, dpi) in formats: try: figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi) if fmt == formats[0][0] and config.plot_srcset: srcset = _parse_srcset(config.plot_srcset) for (mult, suffix) in srcset.items(): fm = f'{suffix}.{fmt}' img.formats.append(fm) figman.canvas.figure.savefig(img.filename(fm), dpi=int(dpi * mult)) except Exception as err: raise PlotError(traceback.format_exc()) from err img.formats.append(fmt) results.append((code_piece, images)) if not context or config.plot_apply_rcparams: clear_state(config.plot_rcparams, close=not context) return results def run(arguments, content, options, state_machine, state, lineno): document = state_machine.document config = document.settings.env.config nofigs = 'nofigs' in options if config.plot_srcset and setup.app.builder.name == 'singlehtml': raise ExtensionError('plot_srcset option not compatible with single HTML writer') formats = get_plot_formats(config) default_fmt = formats[0][0] options.setdefault('include-source', config.plot_include_source) options.setdefault('show-source-link', config.plot_html_show_source_link) if 'class' in options: options['class'] = ['plot-directive'] + options['class'] else: options.setdefault('class', ['plot-directive']) keep_context = 'context' in options context_opt = None if not keep_context else options['context'] rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) if len(arguments): if not config.plot_basedir: source_file_name = os.path.join(setup.app.builder.srcdir, directives.uri(arguments[0])) else: source_file_name = os.path.join(setup.confdir, config.plot_basedir, directives.uri(arguments[0])) caption = '\n'.join(content) if 'caption' in options: if caption: raise ValueError('Caption specified in both content and options. Please remove ambiguity.') caption = options['caption'] if len(arguments) == 2: function_name = arguments[1] else: function_name = None code = Path(source_file_name).read_text(encoding='utf-8') output_base = os.path.basename(source_file_name) else: source_file_name = rst_file code = textwrap.dedent('\n'.join(map(str, content))) counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter (base, ext) = os.path.splitext(os.path.basename(source_file_name)) output_base = '%s-%d.py' % (base, counter) function_name = None caption = options.get('caption', '') (base, source_ext) = os.path.splitext(output_base) if source_ext in ('.py', '.rst', '.txt'): output_base = base else: source_ext = '' output_base = output_base.replace('.', '-') is_doctest = contains_doctest(code) if 'format' in options: if options['format'] == 'python': is_doctest = False else: is_doctest = True source_rel_name = relpath(source_file_name, setup.confdir) source_rel_dir = os.path.dirname(source_rel_name).lstrip(os.path.sep) build_dir = os.path.join(os.path.dirname(setup.app.doctreedir), 'plot_directive', source_rel_dir) build_dir = os.path.normpath(build_dir) os.makedirs(build_dir, exist_ok=True) try: build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') except ValueError: build_dir_link = build_dir try: source_file_includes = [os.path.join(os.getcwd(), t[0]) for t in state.document.include_log] except AttributeError: possible_sources = {os.path.join(setup.confdir, t[0]) for t in state_machine.input_lines.items} source_file_includes = [f for f in possible_sources if os.path.isfile(f)] try: source_file_includes.remove(source_file_name) except ValueError: pass if options['show-source-link']: Path(build_dir, output_base + source_ext).write_text(doctest.script_from_examples(code) if source_file_name == rst_file and is_doctest else code, encoding='utf-8') try: results = render_figures(code=code, code_path=source_file_name, output_dir=build_dir, output_base=output_base, context=keep_context, function_name=function_name, config=config, context_reset=context_opt == 'reset', close_figs=context_opt == 'close-figs', code_includes=source_file_includes) errors = [] except PlotError as err: reporter = state.memo.reporter sm = reporter.system_message(2, 'Exception occurred in plotting {}\n from {}:\n{}'.format(output_base, source_file_name, err), line=lineno) results = [(code, [])] errors = [sm] if caption and config.plot_srcset: caption = f':caption: {caption}' elif caption: caption = '\n' + '\n'.join((' ' + line.strip() for line in caption.split('\n'))) total_lines = [] for (j, (code_piece, images)) in enumerate(results): if options['include-source']: if is_doctest: lines = ['', *code_piece.splitlines()] else: lines = ['.. code-block:: python', '', *textwrap.indent(code_piece, ' ').splitlines()] source_code = '\n'.join(lines) else: source_code = '' if nofigs: images = [] opts = [f':{key}: {val}' for (key, val) in options.items() if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] if j == 0 and options['show-source-link']: src_name = output_base + source_ext else: src_name = None if config.plot_srcset: srcset = [*_parse_srcset(config.plot_srcset).values()] template = TEMPLATE_SRCSET else: srcset = None template = TEMPLATE result = jinja2.Template(config.plot_template or template).render(default_fmt=default_fmt, build_dir=build_dir_link, src_name=src_name, multi_image=len(images) > 1, options=opts, srcset=srcset, images=images, source_code=source_code, html_show_formats=config.plot_html_show_formats and len(images), caption=caption) total_lines.extend(result.split('\n')) total_lines.extend('\n') if total_lines: state_machine.insert_input(total_lines, source=source_file_name) return errors # File: matplotlib-main/lib/matplotlib/sphinxext/roles.py """""" from urllib.parse import urlsplit, urlunsplit from docutils import nodes import matplotlib from matplotlib import rcParamsDefault class _QueryReference(nodes.Inline, nodes.TextElement): def to_query_string(self): return '&'.join((f'{name}={value}' for (name, value) in self.attlist())) def _visit_query_reference_node(self, node): query = node.to_query_string() for refnode in node.findall(nodes.reference): uri = urlsplit(refnode['refuri'])._replace(query=query) refnode['refuri'] = urlunsplit(uri) self.visit_literal(node) def _depart_query_reference_node(self, node): self.depart_literal(node) def _rcparam_role(name, rawtext, text, lineno, inliner, options=None, content=None): title = f'rcParams["{text}"]' target = 'matplotlibrc-sample' (ref_nodes, messages) = inliner.interpreted(title, f'{title} <{target}>', 'ref', lineno) qr = _QueryReference(rawtext, highlight=text) qr += ref_nodes node_list = [qr] if text in rcParamsDefault and text != 'backend': node_list.extend([nodes.Text(' (default: '), nodes.literal('', repr(rcParamsDefault[text])), nodes.Text(')')]) return (node_list, messages) def _mpltype_role(name, rawtext, text, lineno, inliner, options=None, content=None): mpltype = text type_to_link_target = {'color': 'colors_def'} if mpltype not in type_to_link_target: raise ValueError(f'Unknown mpltype: {mpltype!r}') (node_list, messages) = inliner.interpreted(mpltype, f'{mpltype} <{type_to_link_target[mpltype]}>', 'ref', lineno) return (node_list, messages) def setup(app): app.add_role('rc', _rcparam_role) app.add_role('mpltype', _mpltype_role) app.add_node(_QueryReference, html=(_visit_query_reference_node, _depart_query_reference_node), latex=(_visit_query_reference_node, _depart_query_reference_node), text=(_visit_query_reference_node, _depart_query_reference_node)) return {'version': matplotlib.__version__, 'parallel_read_safe': True, 'parallel_write_safe': True} # File: matplotlib-main/lib/matplotlib/spines.py from collections.abc import MutableMapping import functools import numpy as np import matplotlib as mpl from matplotlib import _api, _docstring from matplotlib.artist import allow_rasterization import matplotlib.transforms as mtransforms import matplotlib.patches as mpatches import matplotlib.path as mpath class Spine(mpatches.Patch): def __str__(self): return 'Spine' @_docstring.dedent_interpd def __init__(self, axes, spine_type, path, **kwargs): 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) self._bounds = None self._position = None _api.check_isinstance(mpath.Path, path=path) self._path = path self._patch_type = 'line' self._patch_transform = mtransforms.IdentityTransform() def set_patch_arc(self, center, radius, theta1, theta2): 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) self.set_transform(self.axes.transAxes) self.stale = True def set_patch_circle(self, center, radius): self._patch_type = 'circle' self._center = center self._width = radius * 2 self._height = radius * 2 self.set_transform(self.axes.transAxes) self.stale = True def set_patch_line(self): self._patch_type = 'line' self.stale = True def _recompute_transform(self): 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): 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: self._position = ('outward', 0.0) self.set_position(self._position) def register_axis(self, axis): self.axis = axis self.stale = True def clear(self): self._clear() if self.axis is not None: self.axis.clear() def _clear(self): self._position = None def _adjust_location(self): 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): if position in ('center', 'zero'): 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): self._ensure_position_is_set() return self._position def get_spine_transform(self): 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: return base_transform else: offset_vec = {'left': (-1, 0), 'right': (1, 0), 'bottom': (0, -1), 'top': (0, 1)}[self.spine_type] 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']: return mtransforms.Affine2D.from_values(0, 0, 0, 1, amount, 0) + base_transform elif self.spine_type in ['bottom', 'top']: return mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, amount) + base_transform elif position_type == 'data': if self.spine_type in ('right', 'top'): 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): 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): return self._bounds @classmethod def linear_spine(cls, axes, spine_type, **kwargs): 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): 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): 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): self.set_edgecolor(c) self.stale = True class SpinesProxy: 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): 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): self._dict[key] = value def __delitem__(self, key): del self._dict[key] def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) # File: matplotlib-main/lib/matplotlib/stackplot.py """""" 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): 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) 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.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) 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 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] 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 r # File: matplotlib-main/lib/matplotlib/streamplot.py """""" import numpy as np import matplotlib as mpl from matplotlib import _api, cm, patches import matplotlib.colors as mcolors import matplotlib.collections as mcollections import matplotlib.lines as mlines __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): grid = Grid(x, y) mask = StreamMask(density) dmap = DomainMap(grid, mask) if zorder is None: zorder = mlines.Line2D.zorder 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.0 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 = [[]] 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 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() 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') sp2[:, 0] -= grid.x_origin sp2[:, 1] -= grid.y_origin for (xs, ys) in sp2: (xg, yg) = dmap.data2grid(xs, ys) 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 (tx, ty) = dmap.grid2data(tgx, tgy) tx += grid.x_origin ty += grid.y_origin 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) s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty))) n = np.searchsorted(s, s[-1] / 2.0) 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) 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 class DomainMap: def __init__(self, grid, mask): self.grid = grid self.mask = mask self.x_grid2mask = (mask.nx - 1) / (grid.nx - 1) self.y_grid2mask = (mask.ny - 1) / (grid.ny - 1) self.x_mask2grid = 1.0 / self.x_grid2mask self.y_mask2grid = 1.0 / self.y_grid2mask self.x_data2grid = 1.0 / grid.dx self.y_data2grid = 1.0 / grid.dy def grid2mask(self, xi, yi): 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: 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) 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 0 <= xi <= self.nx - 1 and 0 <= yi <= self.ny - 1 class StreamMask: 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): self._traj = [] self._update_trajectory(xm, ym, broken_streamlines) def _undo_trajectory(self): for t in self._traj: self._mask[t] = 0 def _update_trajectory(self, xm, ym, broken_streamlines=True): 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) elif broken_streamlines: raise InvalidIndexError else: pass class InvalidIndexError(Exception): pass class TerminateTrajectory(Exception): pass def _get_integrator(u, v, dmap, minlength, maxlength, integration_direction): (u, v) = dmap.data2grid(u, v) 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.0 / 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): (stotal, xy_traj) = (0.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: dmap.undo_trajectory() return None return integrate class OutOfBounds(IndexError): pass def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True): maxerror = 0.003 maxds = min(1.0 / dmap.mask.nx, 1.0 / 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 (k1x, k1y) = f(xi, yi) (k2x, k2y) = f(xi + ds * k1x, yi + ds * k1y) except OutOfBounds: 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 = np.hypot((dx2 - dx1) / (nx - 1), (dy2 - dy1) / (ny - 1)) 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 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): (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) def interpgrid(a, xi, yi): (Ny, Nx) = np.shape(a) if isinstance(xi, np.ndarray): x = xi.astype(int) y = yi.astype(int) xn = np.clip(x + 1, 0, Nx - 1) yn = np.clip(y + 1, 0, Ny - 1) else: x = int(xi) y = int(yi) 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): (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' # File: matplotlib-main/lib/matplotlib/style/core.py """""" import contextlib import importlib.resources import logging import os from pathlib import Path import warnings import matplotlib as mpl from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault _log = logging.getLogger(__name__) __all__ = ['use', 'context', 'available', 'library', 'reload_library'] BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] STYLE_EXTENSION = 'mplstyle' STYLE_BLACKLIST = {'interactive', 'backend', 'webagg.port', 'webagg.address', 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', 'toolbar', 'timezone', 'figure.max_open_warning', 'figure.raise_window', 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy', 'date.epoch'} @_docstring.Substitution('\n'.join(map('- {}'.format, sorted(STYLE_BLACKLIST, key=str.lower)))) def use(style): if isinstance(style, (str, Path)) or hasattr(style, 'keys'): styles = [style] else: styles = style style_alias = {'mpl20': 'default', 'mpl15': 'classic'} for style in styles: if isinstance(style, str): style = style_alias.get(style, style) if style == 'default': with _api.suppress_matplotlib_deprecation_warning(): style = {k: rcParamsDefault[k] for k in rcParamsDefault if k not in STYLE_BLACKLIST} elif style in library: style = library[style] elif '.' in style: (pkg, _, name) = style.rpartition('.') try: path = importlib.resources.files(pkg) / f'{name}.{STYLE_EXTENSION}' style = _rc_params_in_file(path) except (ModuleNotFoundError, OSError, TypeError) as exc: pass if isinstance(style, (str, Path)): try: style = _rc_params_in_file(style) except OSError as err: raise OSError(f'{style!r} is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)') from err filtered = {} for k in style: if k in STYLE_BLACKLIST: _api.warn_external(f'Style includes a parameter, {k!r}, that is not related to style. Ignoring this parameter.') else: filtered[k] = style[k] mpl.rcParams.update(filtered) @contextlib.contextmanager def context(style, after_reset=False): with mpl.rc_context(): if after_reset: mpl.rcdefaults() use(style) yield def update_user_library(library): for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS): styles = read_style_directory(stylelib_path) update_nested_dict(library, styles) return library def read_style_directory(style_dir): styles = dict() for path in Path(style_dir).glob(f'*.{STYLE_EXTENSION}'): with warnings.catch_warnings(record=True) as warns: styles[path.stem] = _rc_params_in_file(path) for w in warns: _log.warning('In %s: %s', path, w.message) return styles def update_nested_dict(main_dict, new_dict): for (name, rc_dict) in new_dict.items(): main_dict.setdefault(name, {}).update(rc_dict) return main_dict _base_library = read_style_directory(BASE_LIBRARY_PATH) library = {} available = [] def reload_library(): library.clear() library.update(update_user_library(_base_library)) available[:] = sorted(library.keys()) reload_library() # File: matplotlib-main/lib/matplotlib/table.py """""" import numpy as np from . import _api, _docstring from .artist import Artist, allow_rasterization from .patches import Rectangle from .text import Text from .transforms import Bbox from .path import Path class Cell(Rectangle): PAD = 0.1 '' _edges = 'BRTL' _edge_aliases = {'open': '', 'closed': _edges, 'horizontal': 'BT', 'vertical': 'RL'} def __init__(self, xy, width, height, *, edgecolor='k', facecolor='w', fill=True, text='', loc='right', fontproperties=None, visible_edges='closed'): super().__init__(xy, width=width, height=height, fill=fill, edgecolor=edgecolor, facecolor=facecolor) self.set_clip_on(False) self.visible_edges = visible_edges self._loc = loc self._text = Text(x=xy[0], y=xy[1], clip_on=False, text=text, fontproperties=fontproperties, horizontalalignment=loc, verticalalignment='center') def set_transform(self, t): super().set_transform(t) self.stale = True def set_figure(self, fig): super().set_figure(fig) self._text.set_figure(fig) def get_text(self): return self._text def set_fontsize(self, size): self._text.set_fontsize(size) self.stale = True def get_fontsize(self): return self._text.get_fontsize() def auto_set_font_size(self, renderer): fontsize = self.get_fontsize() required = self.get_required_width(renderer) while fontsize > 1 and required > self.get_width(): fontsize -= 1 self.set_fontsize(fontsize) required = self.get_required_width(renderer) return fontsize @allow_rasterization def draw(self, renderer): if not self.get_visible(): return super().draw(renderer) self._set_text_position(renderer) self._text.draw(renderer) self.stale = False def _set_text_position(self, renderer): bbox = self.get_window_extent(renderer) y = bbox.y0 + bbox.height / 2 loc = self._text.get_horizontalalignment() if loc == 'center': x = bbox.x0 + bbox.width / 2 elif loc == 'left': x = bbox.x0 + bbox.width * self.PAD else: x = bbox.x0 + bbox.width * (1 - self.PAD) self._text.set_position((x, y)) def get_text_bounds(self, renderer): return self._text.get_window_extent(renderer).transformed(self.get_data_transform().inverted()).bounds def get_required_width(self, renderer): (l, b, w, h) = self.get_text_bounds(renderer) return w * (1.0 + 2.0 * self.PAD) @_docstring.dedent_interpd def set_text_props(self, **kwargs): self._text._internal_update(kwargs) self.stale = True @property def visible_edges(self): return self._visible_edges @visible_edges.setter def visible_edges(self, value): if value is None: self._visible_edges = self._edges elif value in self._edge_aliases: self._visible_edges = self._edge_aliases[value] else: if any((edge not in self._edges for edge in value)): raise ValueError('Invalid edge param {}, must only be one of {} or string of {}'.format(value, ', '.join(self._edge_aliases), ', '.join(self._edges))) self._visible_edges = value self.stale = True def get_path(self): codes = [Path.MOVETO] codes.extend((Path.LINETO if edge in self._visible_edges else Path.MOVETO for edge in self._edges)) if Path.MOVETO not in codes[1:]: codes[-1] = Path.CLOSEPOLY return Path([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]], codes, readonly=True) CustomCell = Cell class Table(Artist): codes = {'best': 0, 'upper right': 1, 'upper left': 2, 'lower left': 3, 'lower right': 4, 'center left': 5, 'center right': 6, 'lower center': 7, 'upper center': 8, 'center': 9, 'top right': 10, 'top left': 11, 'bottom left': 12, 'bottom right': 13, 'right': 14, 'left': 15, 'top': 16, 'bottom': 17} '' FONTSIZE = 10 AXESPAD = 0.02 '' def __init__(self, ax, loc=None, bbox=None, **kwargs): super().__init__() if isinstance(loc, str): if loc not in self.codes: raise ValueError('Unrecognized location {!r}. Valid locations are\n\t{}'.format(loc, '\n\t'.join(self.codes))) loc = self.codes[loc] self.set_figure(ax.get_figure(root=False)) self._axes = ax self._loc = loc self._bbox = bbox ax._unstale_viewLim() self.set_transform(ax.transAxes) self._cells = {} self._edges = None self._autoColumns = [] self._autoFontsize = True self._internal_update(kwargs) self.set_clip_on(False) def add_cell(self, row, col, *args, **kwargs): xy = (0, 0) cell = Cell(xy, *args, visible_edges=self.edges, **kwargs) self[row, col] = cell return cell def __setitem__(self, position, cell): _api.check_isinstance(Cell, cell=cell) try: (row, col) = (position[0], position[1]) except Exception as err: raise KeyError('Only tuples length 2 are accepted as coordinates') from err cell.set_figure(self.get_figure(root=False)) cell.set_transform(self.get_transform()) cell.set_clip_on(False) self._cells[row, col] = cell self.stale = True def __getitem__(self, position): return self._cells[position] @property def edges(self): return self._edges @edges.setter def edges(self, value): self._edges = value self.stale = True def _approx_text_height(self): return self.FONTSIZE / 72.0 * self.get_figure(root=True).dpi / self._axes.bbox.height * 1.2 @allow_rasterization def draw(self, renderer): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() if renderer is None: raise RuntimeError('No renderer defined') if not self.get_visible(): return renderer.open_group('table', gid=self.get_gid()) self._update_positions(renderer) for key in sorted(self._cells): self._cells[key].draw(renderer) renderer.close_group('table') self.stale = False def _get_grid_bbox(self, renderer): boxes = [cell.get_window_extent(renderer) for ((row, col), cell) in self._cells.items() if row >= 0 and col >= 0] bbox = Bbox.union(boxes) return bbox.transformed(self.get_transform().inverted()) def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) renderer = self.get_figure(root=True)._get_renderer() if renderer is not None: boxes = [cell.get_window_extent(renderer) for ((row, col), cell) in self._cells.items() if row >= 0 and col >= 0] bbox = Bbox.union(boxes) return (bbox.contains(mouseevent.x, mouseevent.y), {}) else: return (False, {}) def get_children(self): return list(self._cells.values()) def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() self._update_positions(renderer) boxes = [cell.get_window_extent(renderer) for cell in self._cells.values()] return Bbox.union(boxes) def _do_cell_alignment(self): widths = {} heights = {} for ((row, col), cell) in self._cells.items(): height = heights.setdefault(row, 0.0) heights[row] = max(height, cell.get_height()) width = widths.setdefault(col, 0.0) widths[col] = max(width, cell.get_width()) xpos = 0 lefts = {} for col in sorted(widths): lefts[col] = xpos xpos += widths[col] ypos = 0 bottoms = {} for row in sorted(heights, reverse=True): bottoms[row] = ypos ypos += heights[row] for ((row, col), cell) in self._cells.items(): cell.set_x(lefts[col]) cell.set_y(bottoms[row]) def auto_set_column_width(self, col): col1d = np.atleast_1d(col) if not np.issubdtype(col1d.dtype, np.integer): _api.warn_deprecated('3.8', name='col', message='%(name)r must be an int or sequence of ints. Passing other types is deprecated since %(since)s and will be removed %(removal)s.') return for cell in col1d: self._autoColumns.append(cell) self.stale = True def _auto_set_column_width(self, col, renderer): cells = [cell for (key, cell) in self._cells.items() if key[1] == col] max_width = max((cell.get_required_width(renderer) for cell in cells), default=0) for cell in cells: cell.set_width(max_width) def auto_set_font_size(self, value=True): self._autoFontsize = value self.stale = True def _auto_set_font_size(self, renderer): if len(self._cells) == 0: return fontsize = next(iter(self._cells.values())).get_fontsize() cells = [] for (key, cell) in self._cells.items(): if key[1] in self._autoColumns: continue size = cell.auto_set_font_size(renderer) fontsize = min(fontsize, size) cells.append(cell) for cell in self._cells.values(): cell.set_fontsize(fontsize) def scale(self, xscale, yscale): for c in self._cells.values(): c.set_width(c.get_width() * xscale) c.set_height(c.get_height() * yscale) def set_fontsize(self, size): for cell in self._cells.values(): cell.set_fontsize(size) self.stale = True def _offset(self, ox, oy): for c in self._cells.values(): (x, y) = (c.get_x(), c.get_y()) c.set_x(x + ox) c.set_y(y + oy) def _update_positions(self, renderer): for col in self._autoColumns: self._auto_set_column_width(col, renderer) if self._autoFontsize: self._auto_set_font_size(renderer) self._do_cell_alignment() bbox = self._get_grid_bbox(renderer) (l, b, w, h) = bbox.bounds if self._bbox is not None: if isinstance(self._bbox, Bbox): (rl, rb, rw, rh) = self._bbox.bounds else: (rl, rb, rw, rh) = self._bbox self.scale(rw / w, rh / h) ox = rl - l oy = rb - b self._do_cell_alignment() else: (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, TR, TL, BL, BR, R, L, T, B) = range(len(self.codes)) ox = 0.5 - w / 2 - l oy = 0.5 - h / 2 - b if self._loc in (UL, LL, CL): ox = self.AXESPAD - l if self._loc in (BEST, UR, LR, R, CR): ox = 1 - (l + w + self.AXESPAD) if self._loc in (BEST, UR, UL, UC): oy = 1 - (b + h + self.AXESPAD) if self._loc in (LL, LR, LC): oy = self.AXESPAD - b if self._loc in (LC, UC, C): ox = 0.5 - w / 2 - l if self._loc in (CL, CR, C): oy = 0.5 - h / 2 - b if self._loc in (TL, BL, L): ox = -(l + w) if self._loc in (TR, BR, R): ox = 1.0 - l if self._loc in (TR, TL, T): oy = 1.0 - b if self._loc in (BL, BR, B): oy = -(b + h) self._offset(ox, oy) def get_celld(self): return self._cells @_docstring.dedent_interpd def table(ax, cellText=None, cellColours=None, cellLoc='right', colWidths=None, rowLabels=None, rowColours=None, rowLoc='left', colLabels=None, colColours=None, colLoc='center', loc='bottom', bbox=None, edges='closed', **kwargs): if cellColours is None and cellText is None: raise ValueError('At least one argument from "cellColours" or "cellText" must be provided to create a table.') if cellText is None: rows = len(cellColours) cols = len(cellColours[0]) cellText = [[''] * cols] * rows rows = len(cellText) cols = len(cellText[0]) for row in cellText: if len(row) != cols: raise ValueError(f"Each row in 'cellText' must have {cols} columns") if cellColours is not None: if len(cellColours) != rows: raise ValueError(f"'cellColours' must have {rows} rows") for row in cellColours: if len(row) != cols: raise ValueError(f"Each row in 'cellColours' must have {cols} columns") else: cellColours = ['w' * cols] * rows if colWidths is None: colWidths = [1.0 / cols] * cols rowLabelWidth = 0 if rowLabels is None: if rowColours is not None: rowLabels = [''] * rows rowLabelWidth = colWidths[0] elif rowColours is None: rowColours = 'w' * rows if rowLabels is not None: if len(rowLabels) != rows: raise ValueError(f"'rowLabels' must be of length {rows}") offset = 1 if colLabels is None: if colColours is not None: colLabels = [''] * cols else: offset = 0 elif colColours is None: colColours = 'w' * cols if cellColours is None: cellColours = ['w' * cols] * rows table = Table(ax, loc, bbox, **kwargs) table.edges = edges height = table._approx_text_height() for row in range(rows): for col in range(cols): table.add_cell(row + offset, col, width=colWidths[col], height=height, text=cellText[row][col], facecolor=cellColours[row][col], loc=cellLoc) if colLabels is not None: for col in range(cols): table.add_cell(0, col, width=colWidths[col], height=height, text=colLabels[col], facecolor=colColours[col], loc=colLoc) if rowLabels is not None: for row in range(rows): table.add_cell(row + offset, -1, width=rowLabelWidth or 1e-15, height=height, text=rowLabels[row], facecolor=rowColours[row], loc=rowLoc) if rowLabelWidth == 0: table.auto_set_column_width(-1) ax.add_table(table) return table # File: matplotlib-main/lib/matplotlib/texmanager.py """""" import functools import hashlib import logging import os from pathlib import Path import subprocess from tempfile import TemporaryDirectory import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, dviread _log = logging.getLogger(__name__) def _usepackage_if_not_loaded(package, *, option=None): option = f'[{option}]' if option is not None else '' return '\\makeatletter\\@ifpackageloaded{%(package)s}{}{\\usepackage%(option)s{%(package)s}}\\makeatother' % {'package': package, 'option': option} class TexManager: texcache = _api.deprecate_privatize_attribute('3.8') _texcache = os.path.join(mpl.get_cachedir(), 'tex.cache') _grey_arrayd = {} _font_families = ('serif', 'sans-serif', 'cursive', 'monospace') _font_preambles = {'new century schoolbook': '\\renewcommand{\\rmdefault}{pnc}', 'bookman': '\\renewcommand{\\rmdefault}{pbk}', 'times': '\\usepackage{mathptmx}', 'palatino': '\\usepackage{mathpazo}', 'zapf chancery': '\\usepackage{chancery}', 'cursive': '\\usepackage{chancery}', 'charter': '\\usepackage{charter}', 'serif': '', 'sans-serif': '', 'helvetica': '\\usepackage{helvet}', 'avant garde': '\\usepackage{avant}', 'courier': '\\usepackage{courier}', 'monospace': '\\usepackage{type1ec}', 'computer modern roman': '\\usepackage{type1ec}', 'computer modern sans serif': '\\usepackage{type1ec}', 'computer modern typewriter': '\\usepackage{type1ec}'} _font_types = {'new century schoolbook': 'serif', 'bookman': 'serif', 'times': 'serif', 'palatino': 'serif', 'zapf chancery': 'cursive', 'charter': 'serif', 'helvetica': 'sans-serif', 'avant garde': 'sans-serif', 'courier': 'monospace', 'computer modern roman': 'serif', 'computer modern sans serif': 'sans-serif', 'computer modern typewriter': 'monospace'} @functools.lru_cache def __new__(cls): Path(cls._texcache).mkdir(parents=True, exist_ok=True) return object.__new__(cls) @classmethod def _get_font_family_and_reduced(cls): ff = mpl.rcParams['font.family'] ff_val = ff[0].lower() if len(ff) == 1 else None if len(ff) == 1 and ff_val in cls._font_families: return (ff_val, False) elif len(ff) == 1 and ff_val in cls._font_preambles: return (cls._font_types[ff_val], True) else: _log.info('font.family must be one of (%s) when text.usetex is True. serif will be used by default.', ', '.join(cls._font_families)) return ('serif', False) @classmethod def _get_font_preamble_and_command(cls): (requested_family, is_reduced_font) = cls._get_font_family_and_reduced() preambles = {} for font_family in cls._font_families: if is_reduced_font and font_family == requested_family: preambles[font_family] = cls._font_preambles[mpl.rcParams['font.family'][0].lower()] else: rcfonts = mpl.rcParams[f'font.{font_family}'] for (i, font) in enumerate(map(str.lower, rcfonts)): if font in cls._font_preambles: preambles[font_family] = cls._font_preambles[font] _log.debug('family: %s, package: %s, font: %s, skipped: %s', font_family, cls._font_preambles[font], rcfonts[i], ', '.join(rcfonts[:i])) break else: _log.info('No LaTeX-compatible font found for the %s fontfamily in rcParams. Using default.', font_family) preambles[font_family] = cls._font_preambles[font_family] cmd = {preambles[family] for family in ['serif', 'sans-serif', 'monospace']} if requested_family == 'cursive': cmd.add(preambles['cursive']) cmd.add('\\usepackage{type1cm}') preamble = '\n'.join(sorted(cmd)) fontcmd = '\\sffamily' if requested_family == 'sans-serif' else '\\ttfamily' if requested_family == 'monospace' else '\\rmfamily' return (preamble, fontcmd) @classmethod def get_basefile(cls, tex, fontsize, dpi=None): src = cls._get_tex_source(tex, fontsize) + str(dpi) filehash = hashlib.md5(src.encode('utf-8')).hexdigest() filepath = Path(cls._texcache) (num_letters, num_levels) = (2, 2) for i in range(0, num_letters * num_levels, num_letters): filepath = filepath / Path(filehash[i:i + 2]) filepath.mkdir(parents=True, exist_ok=True) return os.path.join(filepath, filehash) @classmethod def get_font_preamble(cls): (font_preamble, command) = cls._get_font_preamble_and_command() return font_preamble @classmethod def get_custom_preamble(cls): return mpl.rcParams['text.latex.preamble'] @classmethod def _get_tex_source(cls, tex, fontsize): (font_preamble, fontcmd) = cls._get_font_preamble_and_command() baselineskip = 1.25 * fontsize return '\n'.join(['\\documentclass{article}', '% Pass-through \\mathdefault, which is used in non-usetex mode', '% to use the default text font but was historically suppressed', '% in usetex mode.', '\\newcommand{\\mathdefault}[1]{#1}', font_preamble, '\\usepackage[utf8]{inputenc}', '\\DeclareUnicodeCharacter{2212}{\\ensuremath{-}}', '% geometry is loaded before the custom preamble as ', '% convert_psfrags relies on a custom preamble to change the ', '% geometry.', '\\usepackage[papersize=72in, margin=1in]{geometry}', cls.get_custom_preamble(), '% Use `underscore` package to take care of underscores in text.', '% The [strings] option allows to use underscores in file names.', _usepackage_if_not_loaded('underscore', option='strings'), '% Custom packages (e.g. newtxtext) may already have loaded ', '% textcomp with different options.', _usepackage_if_not_loaded('textcomp'), '\\pagestyle{empty}', '\\begin{document}', '% The empty hbox ensures that a page is printed even for empty', '% inputs, except when using psfrag which gets confused by it.', '% matplotlibbaselinemarker is used by dviread to detect the', "% last line's baseline.", f'\\fontsize{{{fontsize}}}{{{baselineskip}}}%', '\\ifdefined\\psfrag\\else\\hbox{}\\fi%', f'{{{fontcmd} {tex}}}%', '\\end{document}']) @classmethod def make_tex(cls, tex, fontsize): texfile = cls.get_basefile(tex, fontsize) + '.tex' Path(texfile).write_text(cls._get_tex_source(tex, fontsize), encoding='utf-8') return texfile @classmethod def _run_checked_subprocess(cls, command, tex, *, cwd=None): _log.debug(cbook._pformat_subprocess(command)) try: report = subprocess.check_output(command, cwd=cwd if cwd is not None else cls._texcache, stderr=subprocess.STDOUT) except FileNotFoundError as exc: raise RuntimeError(f'Failed to process string with tex because {command[0]} could not be found') from exc except subprocess.CalledProcessError as exc: raise RuntimeError('{prog} was not able to process the following string:\n{tex!r}\n\nHere is the full command invocation and its output:\n\n{format_command}\n\n{exc}\n\n'.format(prog=command[0], format_command=cbook._pformat_subprocess(command), tex=tex.encode('unicode_escape'), exc=exc.output.decode('utf-8', 'backslashreplace'))) from None _log.debug(report) return report @classmethod def make_dvi(cls, tex, fontsize): basefile = cls.get_basefile(tex, fontsize) dvifile = '%s.dvi' % basefile if not os.path.exists(dvifile): texfile = Path(cls.make_tex(tex, fontsize)) cwd = Path(dvifile).parent with TemporaryDirectory(dir=cwd) as tmpdir: tmppath = Path(tmpdir) cls._run_checked_subprocess(['latex', '-interaction=nonstopmode', '--halt-on-error', f'--output-directory={tmppath.name}', f'{texfile.name}'], tex, cwd=cwd) (tmppath / Path(dvifile).name).replace(dvifile) return dvifile @classmethod def make_png(cls, tex, fontsize, dpi): basefile = cls.get_basefile(tex, fontsize, dpi) pngfile = '%s.png' % basefile if not os.path.exists(pngfile): dvifile = cls.make_dvi(tex, fontsize) cmd = ['dvipng', '-bg', 'Transparent', '-D', str(dpi), '-T', 'tight', '-o', pngfile, dvifile] if getattr(mpl, '_called_from_pytest', False) and mpl._get_executable_info('dvipng').raw_version != '1.16': cmd.insert(1, '--freetype0') cls._run_checked_subprocess(cmd, tex) return pngfile @classmethod def get_grey(cls, tex, fontsize=None, dpi=None): if not fontsize: fontsize = mpl.rcParams['font.size'] if not dpi: dpi = mpl.rcParams['savefig.dpi'] key = (cls._get_tex_source(tex, fontsize), dpi) alpha = cls._grey_arrayd.get(key) if alpha is None: pngfile = cls.make_png(tex, fontsize, dpi) rgba = mpl.image.imread(os.path.join(cls._texcache, pngfile)) cls._grey_arrayd[key] = alpha = rgba[:, :, -1] return alpha @classmethod def get_rgba(cls, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)): alpha = cls.get_grey(tex, fontsize, dpi) rgba = np.empty((*alpha.shape, 4)) rgba[..., :3] = mpl.colors.to_rgb(rgb) rgba[..., -1] = alpha return rgba @classmethod def get_text_width_height_descent(cls, tex, fontsize, renderer=None): if tex.strip() == '': return (0, 0, 0) dvifile = cls.make_dvi(tex, fontsize) dpi_fraction = renderer.points_to_pixels(1.0) if renderer else 1 with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi: (page,) = dvi return (page.width, page.height + page.descent, page.descent) # File: matplotlib-main/lib/matplotlib/text.py """""" import functools import logging import math from numbers import Real import weakref import numpy as np import matplotlib as mpl from . import _api, artist, cbook, _docstring from .artist import Artist from .font_manager import FontProperties from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle from .textpath import TextPath, TextToPath from .transforms import Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform _log = logging.getLogger(__name__) def _get_textbox(text, renderer): projected_xs = [] projected_ys = [] theta = np.deg2rad(text.get_rotation()) tr = Affine2D().rotate(-theta) (_, parts, d) = text._get_layout(renderer) for (t, wh, x, y) in parts: (w, h) = wh (xt1, yt1) = tr.transform((x, y)) yt1 -= d (xt2, yt2) = (xt1 + w, yt1 + h) projected_xs.extend([xt1, xt2]) projected_ys.extend([yt1, yt2]) (xt_box, yt_box) = (min(projected_xs), min(projected_ys)) (w_box, h_box) = (max(projected_xs) - xt_box, max(projected_ys) - yt_box) (x_box, y_box) = Affine2D().rotate(theta).transform((xt_box, yt_box)) return (x_box, y_box, w_box, h_box) def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi): return _get_text_metrics_with_cache_impl(weakref.ref(renderer), text, fontprop.copy(), ismath, dpi) @functools.lru_cache(4096) def _get_text_metrics_with_cache_impl(renderer_ref, text, fontprop, ismath, dpi): return renderer_ref().get_text_width_height_descent(text, fontprop, ismath) @_docstring.interpd @_api.define_aliases({'color': ['c'], 'fontproperties': ['font', 'font_properties'], 'fontfamily': ['family'], 'fontname': ['name'], 'fontsize': ['size'], 'fontstretch': ['stretch'], 'fontstyle': ['style'], 'fontvariant': ['variant'], 'fontweight': ['weight'], 'horizontalalignment': ['ha'], 'verticalalignment': ['va'], 'multialignment': ['ma']}) class Text(Artist): zorder = 3 _charsize_cache = dict() def __repr__(self): return f'Text({self._x}, {self._y}, {self._text!r})' def __init__(self, x=0, y=0, text='', *, color=None, verticalalignment='baseline', horizontalalignment='left', multialignment=None, fontproperties=None, rotation=None, linespacing=None, rotation_mode=None, usetex=None, wrap=False, transform_rotates_text=False, parse_math=None, antialiased=None, **kwargs): super().__init__() (self._x, self._y) = (x, y) self._text = '' self._reset_visual_defaults(text=text, color=color, fontproperties=fontproperties, usetex=usetex, parse_math=parse_math, wrap=wrap, verticalalignment=verticalalignment, horizontalalignment=horizontalalignment, multialignment=multialignment, rotation=rotation, transform_rotates_text=transform_rotates_text, linespacing=linespacing, rotation_mode=rotation_mode, antialiased=antialiased) self.update(kwargs) def _reset_visual_defaults(self, text='', color=None, fontproperties=None, usetex=None, parse_math=None, wrap=False, verticalalignment='baseline', horizontalalignment='left', multialignment=None, rotation=None, transform_rotates_text=False, linespacing=None, rotation_mode=None, antialiased=None): self.set_text(text) self.set_color(mpl._val_or_rc(color, 'text.color')) self.set_fontproperties(fontproperties) self.set_usetex(usetex) self.set_parse_math(mpl._val_or_rc(parse_math, 'text.parse_math')) self.set_wrap(wrap) self.set_verticalalignment(verticalalignment) self.set_horizontalalignment(horizontalalignment) self._multialignment = multialignment self.set_rotation(rotation) self._transform_rotates_text = transform_rotates_text self._bbox_patch = None self._renderer = None if linespacing is None: linespacing = 1.2 self.set_linespacing(linespacing) self.set_rotation_mode(rotation_mode) self.set_antialiased(antialiased if antialiased is not None else mpl.rcParams['text.antialiased']) def update(self, kwargs): ret = [] kwargs = cbook.normalize_kwargs(kwargs, Text) sentinel = object() fontproperties = kwargs.pop('fontproperties', sentinel) if fontproperties is not sentinel: ret.append(self.set_fontproperties(fontproperties)) bbox = kwargs.pop('bbox', sentinel) ret.extend(super().update(kwargs)) if bbox is not sentinel: ret.append(self.set_bbox(bbox)) return ret def __getstate__(self): d = super().__getstate__() d['_renderer'] = None return d def contains(self, mouseevent): if self._different_canvas(mouseevent) or not self.get_visible() or self._renderer is None: return (False, {}) bbox = Text.get_window_extent(self) inside = bbox.x0 <= mouseevent.x <= bbox.x1 and bbox.y0 <= mouseevent.y <= bbox.y1 cattr = {} if self._bbox_patch: (patch_inside, patch_cattr) = self._bbox_patch.contains(mouseevent) inside = inside or patch_inside cattr['bbox_patch'] = patch_cattr return (inside, cattr) def _get_xy_display(self): (x, y) = self.get_unitless_position() return self.get_transform().transform((x, y)) def _get_multialignment(self): if self._multialignment is not None: return self._multialignment else: return self._horizontalalignment def _char_index_at(self, x): if not self._text: return 0 text = self._text fontproperties = str(self._fontproperties) if fontproperties not in Text._charsize_cache: Text._charsize_cache[fontproperties] = dict() charsize_cache = Text._charsize_cache[fontproperties] for char in set(text): if char not in charsize_cache: self.set_text(char) bb = self.get_window_extent() charsize_cache[char] = bb.x1 - bb.x0 self.set_text(text) bb = self.get_window_extent() size_accum = np.cumsum([0] + [charsize_cache[x] for x in text]) std_x = x - bb.x0 return np.abs(size_accum - std_x).argmin() def get_rotation(self): if self.get_transform_rotates_text(): return self.get_transform().transform_angles([self._rotation], [self.get_unitless_position()]).item(0) else: return self._rotation def get_transform_rotates_text(self): return self._transform_rotates_text def set_rotation_mode(self, m): if m is None: m = 'default' else: _api.check_in_list(('anchor', 'default'), rotation_mode=m) self._rotation_mode = m self.stale = True def get_rotation_mode(self): return self._rotation_mode def set_antialiased(self, antialiased): self._antialiased = antialiased self.stale = True def get_antialiased(self): return self._antialiased def update_from(self, other): super().update_from(other) self._color = other._color self._multialignment = other._multialignment self._verticalalignment = other._verticalalignment self._horizontalalignment = other._horizontalalignment self._fontproperties = other._fontproperties.copy() self._usetex = other._usetex self._rotation = other._rotation self._transform_rotates_text = other._transform_rotates_text self._picker = other._picker self._linespacing = other._linespacing self._antialiased = other._antialiased self.stale = True def _get_layout(self, renderer): (thisx, thisy) = (0.0, 0.0) lines = self._get_wrapped_text().split('\n') ws = [] hs = [] xs = [] ys = [] (_, lp_h, lp_d) = _get_text_metrics_with_cache(renderer, 'lp', self._fontproperties, ismath='TeX' if self.get_usetex() else False, dpi=self.get_figure(root=True).dpi) min_dy = (lp_h - lp_d) * self._linespacing for (i, line) in enumerate(lines): (clean_line, ismath) = self._preprocess_math(line) if clean_line: (w, h, d) = _get_text_metrics_with_cache(renderer, clean_line, self._fontproperties, ismath=ismath, dpi=self.get_figure(root=True).dpi) else: w = h = d = 0 h = max(h, lp_h) d = max(d, lp_d) ws.append(w) hs.append(h) baseline = h - d - thisy if i == 0: thisy = -(h - d) else: thisy -= max(min_dy, (h - d) * self._linespacing) xs.append(thisx) ys.append(thisy) thisy -= d descent = d width = max(ws) xmin = 0 xmax = width ymax = 0 ymin = ys[-1] - descent M = Affine2D().rotate_deg(self.get_rotation()) malign = self._get_multialignment() if malign == 'left': offset_layout = [(x, y) for (x, y) in zip(xs, ys)] elif malign == 'center': offset_layout = [(x + width / 2 - w / 2, y) for (x, y, w) in zip(xs, ys, ws)] elif malign == 'right': offset_layout = [(x + width - w, y) for (x, y, w) in zip(xs, ys, ws)] corners_horiz = np.array([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]) corners_rotated = M.transform(corners_horiz) xmin = corners_rotated[:, 0].min() xmax = corners_rotated[:, 0].max() ymin = corners_rotated[:, 1].min() ymax = corners_rotated[:, 1].max() width = xmax - xmin height = ymax - ymin halign = self._horizontalalignment valign = self._verticalalignment rotation_mode = self.get_rotation_mode() if rotation_mode != 'anchor': if halign == 'center': offsetx = (xmin + xmax) / 2 elif halign == 'right': offsetx = xmax else: offsetx = xmin if valign == 'center': offsety = (ymin + ymax) / 2 elif valign == 'top': offsety = ymax elif valign == 'baseline': offsety = ymin + descent elif valign == 'center_baseline': offsety = ymin + height - baseline / 2.0 else: offsety = ymin else: (xmin1, ymin1) = corners_horiz[0] (xmax1, ymax1) = corners_horiz[2] if halign == 'center': offsetx = (xmin1 + xmax1) / 2.0 elif halign == 'right': offsetx = xmax1 else: offsetx = xmin1 if valign == 'center': offsety = (ymin1 + ymax1) / 2.0 elif valign == 'top': offsety = ymax1 elif valign == 'baseline': offsety = ymax1 - baseline elif valign == 'center_baseline': offsety = ymax1 - baseline / 2.0 else: offsety = ymin1 (offsetx, offsety) = M.transform((offsetx, offsety)) xmin -= offsetx ymin -= offsety bbox = Bbox.from_bounds(xmin, ymin, width, height) xys = M.transform(offset_layout) - (offsetx, offsety) return (bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent) def set_bbox(self, rectprops): if rectprops is not None: props = rectprops.copy() boxstyle = props.pop('boxstyle', None) pad = props.pop('pad', None) if boxstyle is None: boxstyle = 'square' if pad is None: pad = 4 pad /= self.get_size() elif pad is None: pad = 0.3 if isinstance(boxstyle, str) and 'pad' not in boxstyle: boxstyle += ',pad=%0.2f' % pad self._bbox_patch = FancyBboxPatch((0, 0), 1, 1, boxstyle=boxstyle, transform=IdentityTransform(), **props) else: self._bbox_patch = None self._update_clip_properties() def get_bbox_patch(self): return self._bbox_patch def update_bbox_position_size(self, renderer): if self._bbox_patch: posx = float(self.convert_xunits(self._x)) posy = float(self.convert_yunits(self._y)) (posx, posy) = self.get_transform().transform((posx, posy)) (x_box, y_box, w_box, h_box) = _get_textbox(self, renderer) self._bbox_patch.set_bounds(0.0, 0.0, w_box, h_box) self._bbox_patch.set_transform(Affine2D().rotate_deg(self.get_rotation()).translate(posx + x_box, posy + y_box)) fontsize_in_pixel = renderer.points_to_pixels(self.get_size()) self._bbox_patch.set_mutation_scale(fontsize_in_pixel) def _update_clip_properties(self): if self._bbox_patch: clipprops = dict(clip_box=self.clipbox, clip_path=self._clippath, clip_on=self._clipon) self._bbox_patch.update(clipprops) def set_clip_box(self, clipbox): super().set_clip_box(clipbox) self._update_clip_properties() def set_clip_path(self, path, transform=None): super().set_clip_path(path, transform) self._update_clip_properties() def set_clip_on(self, b): super().set_clip_on(b) self._update_clip_properties() def get_wrap(self): return self._wrap def set_wrap(self, wrap): self._wrap = wrap def _get_wrap_line_width(self): (x0, y0) = self.get_transform().transform(self.get_position()) figure_box = self.get_figure().get_window_extent() alignment = self.get_horizontalalignment() self.set_rotation_mode('anchor') rotation = self.get_rotation() left = self._get_dist_to_box(rotation, x0, y0, figure_box) right = self._get_dist_to_box((180 + rotation) % 360, x0, y0, figure_box) if alignment == 'left': line_width = left elif alignment == 'right': line_width = right else: line_width = 2 * min(left, right) return line_width def _get_dist_to_box(self, rotation, x0, y0, figure_box): if rotation > 270: quad = rotation - 270 h1 = (y0 - figure_box.y0) / math.cos(math.radians(quad)) h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad)) elif rotation > 180: quad = rotation - 180 h1 = (x0 - figure_box.x0) / math.cos(math.radians(quad)) h2 = (y0 - figure_box.y0) / math.cos(math.radians(90 - quad)) elif rotation > 90: quad = rotation - 90 h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad)) h2 = (x0 - figure_box.x0) / math.cos(math.radians(90 - quad)) else: h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation)) h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation)) return min(h1, h2) def _get_rendered_text_width(self, text): (w, h, d) = self._renderer.get_text_width_height_descent(text, self.get_fontproperties(), cbook.is_math_text(text)) return math.ceil(w) def _get_wrapped_text(self): if not self.get_wrap(): return self.get_text() if self.get_usetex(): return self.get_text() line_width = self._get_wrap_line_width() wrapped_lines = [] unwrapped_lines = self.get_text().split('\n') for unwrapped_line in unwrapped_lines: sub_words = unwrapped_line.split(' ') while len(sub_words) > 0: if len(sub_words) == 1: wrapped_lines.append(sub_words.pop(0)) continue for i in range(2, len(sub_words) + 1): line = ' '.join(sub_words[:i]) current_width = self._get_rendered_text_width(line) if current_width > line_width: wrapped_lines.append(' '.join(sub_words[:i - 1])) sub_words = sub_words[i - 1:] break elif i == len(sub_words): wrapped_lines.append(' '.join(sub_words[:i])) sub_words = [] break return '\n'.join(wrapped_lines) @artist.allow_rasterization def draw(self, renderer): if renderer is not None: self._renderer = renderer if not self.get_visible(): return if self.get_text() == '': return renderer.open_group('text', self.get_gid()) with self._cm_set(text=self._get_wrapped_text()): (bbox, info, descent) = self._get_layout(renderer) trans = self.get_transform() posx = float(self.convert_xunits(self._x)) posy = float(self.convert_yunits(self._y)) (posx, posy) = trans.transform((posx, posy)) if not np.isfinite(posx) or not np.isfinite(posy): _log.warning('posx and posy should be finite values') return (canvasw, canvash) = renderer.get_canvas_width_height() if self._bbox_patch: self.update_bbox_position_size(renderer) self._bbox_patch.draw(renderer) gc = renderer.new_gc() gc.set_foreground(self.get_color()) gc.set_alpha(self.get_alpha()) gc.set_url(self._url) gc.set_antialiased(self._antialiased) self._set_gc_clip(gc) angle = self.get_rotation() for (line, wh, x, y) in info: mtext = self if len(info) == 1 else None x = x + posx y = y + posy if renderer.flipy(): y = canvash - y (clean_line, ismath) = self._preprocess_math(line) if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer textrenderer = PathEffectRenderer(self.get_path_effects(), renderer) else: textrenderer = renderer if self.get_usetex(): textrenderer.draw_tex(gc, x, y, clean_line, self._fontproperties, angle, mtext=mtext) else: textrenderer.draw_text(gc, x, y, clean_line, self._fontproperties, angle, ismath=ismath, mtext=mtext) gc.restore() renderer.close_group('text') self.stale = False def get_color(self): return self._color def get_fontproperties(self): return self._fontproperties def get_fontfamily(self): return self._fontproperties.get_family() def get_fontname(self): return self._fontproperties.get_name() def get_fontstyle(self): return self._fontproperties.get_style() def get_fontsize(self): return self._fontproperties.get_size_in_points() def get_fontvariant(self): return self._fontproperties.get_variant() def get_fontweight(self): return self._fontproperties.get_weight() def get_stretch(self): return self._fontproperties.get_stretch() def get_horizontalalignment(self): return self._horizontalalignment def get_unitless_position(self): x = float(self.convert_xunits(self._x)) y = float(self.convert_yunits(self._y)) return (x, y) def get_position(self): return (self._x, self._y) def get_text(self): return self._text def get_verticalalignment(self): return self._verticalalignment def get_window_extent(self, renderer=None, dpi=None): if not self.get_visible(): return Bbox.unit() fig = self.get_figure(root=True) if dpi is None: dpi = fig.dpi if self.get_text() == '': with cbook._setattr_cm(fig, dpi=dpi): (tx, ty) = self._get_xy_display() return Bbox.from_bounds(tx, ty, 0, 0) if renderer is not None: self._renderer = renderer if self._renderer is None: self._renderer = fig._get_renderer() if self._renderer is None: raise RuntimeError("Cannot get window extent of text w/o renderer. You likely want to call 'figure.draw_without_rendering()' first.") with cbook._setattr_cm(fig, dpi=dpi): (bbox, info, descent) = self._get_layout(self._renderer) (x, y) = self.get_unitless_position() (x, y) = self.get_transform().transform((x, y)) bbox = bbox.translated(x, y) return bbox def set_backgroundcolor(self, color): if self._bbox_patch is None: self.set_bbox(dict(facecolor=color, edgecolor=color)) else: self._bbox_patch.update(dict(facecolor=color)) self._update_clip_properties() self.stale = True def set_color(self, color): if not cbook._str_equal(color, 'auto'): mpl.colors._check_color_like(color=color) self._color = color self.stale = True def set_horizontalalignment(self, align): _api.check_in_list(['center', 'right', 'left'], align=align) self._horizontalalignment = align self.stale = True def set_multialignment(self, align): _api.check_in_list(['center', 'right', 'left'], align=align) self._multialignment = align self.stale = True def set_linespacing(self, spacing): _api.check_isinstance(Real, spacing=spacing) self._linespacing = spacing self.stale = True def set_fontfamily(self, fontname): self._fontproperties.set_family(fontname) self.stale = True def set_fontvariant(self, variant): self._fontproperties.set_variant(variant) self.stale = True def set_fontstyle(self, fontstyle): self._fontproperties.set_style(fontstyle) self.stale = True def set_fontsize(self, fontsize): self._fontproperties.set_size(fontsize) self.stale = True def get_math_fontfamily(self): return self._fontproperties.get_math_fontfamily() def set_math_fontfamily(self, fontfamily): self._fontproperties.set_math_fontfamily(fontfamily) def set_fontweight(self, weight): self._fontproperties.set_weight(weight) self.stale = True def set_fontstretch(self, stretch): self._fontproperties.set_stretch(stretch) self.stale = True def set_position(self, xy): self.set_x(xy[0]) self.set_y(xy[1]) def set_x(self, x): self._x = x self.stale = True def set_y(self, y): self._y = y self.stale = True def set_rotation(self, s): if isinstance(s, Real): self._rotation = float(s) % 360 elif cbook._str_equal(s, 'horizontal') or s is None: self._rotation = 0.0 elif cbook._str_equal(s, 'vertical'): self._rotation = 90.0 else: raise ValueError(f"rotation must be 'vertical', 'horizontal' or a number, not {s}") self.stale = True def set_transform_rotates_text(self, t): self._transform_rotates_text = t self.stale = True def set_verticalalignment(self, align): _api.check_in_list(['top', 'bottom', 'center', 'baseline', 'center_baseline'], align=align) self._verticalalignment = align self.stale = True def set_text(self, s): s = '' if s is None else str(s) if s != self._text: self._text = s self.stale = True def _preprocess_math(self, s): if self.get_usetex(): if s == ' ': s = '\\ ' return (s, 'TeX') elif not self.get_parse_math(): return (s, False) elif cbook.is_math_text(s): return (s, True) else: return (s.replace('\\$', '$'), False) def set_fontproperties(self, fp): self._fontproperties = FontProperties._from_any(fp).copy() self.stale = True @_docstring.kwarg_doc('bool, default: :rc:`text.usetex`') def set_usetex(self, usetex): if usetex is None: self._usetex = mpl.rcParams['text.usetex'] else: self._usetex = bool(usetex) self.stale = True def get_usetex(self): return self._usetex def set_parse_math(self, parse_math): self._parse_math = bool(parse_math) def get_parse_math(self): return self._parse_math def set_fontname(self, fontname): self.set_fontfamily(fontname) class OffsetFrom: def __init__(self, artist, ref_coord, unit='points'): self._artist = artist (x, y) = ref_coord self._ref_coord = (x, y) self.set_unit(unit) def set_unit(self, unit): _api.check_in_list(['points', 'pixels'], unit=unit) self._unit = unit def get_unit(self): return self._unit def __call__(self, renderer): if isinstance(self._artist, Artist): bbox = self._artist.get_window_extent(renderer) (xf, yf) = self._ref_coord x = bbox.x0 + bbox.width * xf y = bbox.y0 + bbox.height * yf elif isinstance(self._artist, BboxBase): bbox = self._artist (xf, yf) = self._ref_coord x = bbox.x0 + bbox.width * xf y = bbox.y0 + bbox.height * yf elif isinstance(self._artist, Transform): (x, y) = self._artist.transform(self._ref_coord) else: _api.check_isinstance((Artist, BboxBase, Transform), artist=self._artist) scale = 1 if self._unit == 'pixels' else renderer.points_to_pixels(1) return Affine2D().scale(scale).translate(x, y) class _AnnotationBase: def __init__(self, xy, xycoords='data', annotation_clip=None): (x, y) = xy self.xy = (x, y) self.xycoords = xycoords self.set_annotation_clip(annotation_clip) self._draggable = None def _get_xy(self, renderer, xy, coords): (x, y) = xy (xcoord, ycoord) = coords if isinstance(coords, tuple) else (coords, coords) if xcoord == 'data': x = float(self.convert_xunits(x)) if ycoord == 'data': y = float(self.convert_yunits(y)) return self._get_xy_transform(renderer, coords).transform((x, y)) def _get_xy_transform(self, renderer, coords): if isinstance(coords, tuple): (xcoord, ycoord) = coords from matplotlib.transforms import blended_transform_factory tr1 = self._get_xy_transform(renderer, xcoord) tr2 = self._get_xy_transform(renderer, ycoord) return blended_transform_factory(tr1, tr2) elif callable(coords): tr = coords(renderer) if isinstance(tr, BboxBase): return BboxTransformTo(tr) elif isinstance(tr, Transform): return tr else: raise TypeError(f'xycoords callable must return a BboxBase or Transform, not a {type(tr).__name__}') elif isinstance(coords, Artist): bbox = coords.get_window_extent(renderer) return BboxTransformTo(bbox) elif isinstance(coords, BboxBase): return BboxTransformTo(coords) elif isinstance(coords, Transform): return coords elif not isinstance(coords, str): raise TypeError(f"'xycoords' must be an instance of str, tuple[str, str], Artist, Transform, or Callable, not a {type(coords).__name__}") if coords == 'data': return self.axes.transData elif coords == 'polar': from matplotlib.projections import PolarAxes tr = PolarAxes.PolarTransform(apply_theta_transforms=False) trans = tr + self.axes.transData return trans try: (bbox_name, unit) = coords.split() except ValueError: raise ValueError(f'{coords!r} is not a valid coordinate') from None (bbox0, xy0) = (None, None) if bbox_name == 'figure': bbox0 = self.get_figure(root=False).figbbox elif bbox_name == 'subfigure': bbox0 = self.get_figure(root=False).bbox elif bbox_name == 'axes': bbox0 = self.axes.bbox if bbox0 is not None: xy0 = bbox0.p0 elif bbox_name == 'offset': xy0 = self._get_position_xy(renderer) else: raise ValueError(f'{coords!r} is not a valid coordinate') if unit == 'points': tr = Affine2D().scale(self.get_figure(root=True).dpi / 72) elif unit == 'pixels': tr = Affine2D() elif unit == 'fontsize': tr = Affine2D().scale(self.get_size() * self.get_figure(root=True).dpi / 72) elif unit == 'fraction': tr = Affine2D().scale(*bbox0.size) else: raise ValueError(f'{unit!r} is not a recognized unit') return tr.translate(*xy0) def set_annotation_clip(self, b): self._annotation_clip = b def get_annotation_clip(self): return self._annotation_clip def _get_position_xy(self, renderer): return self._get_xy(renderer, self.xy, self.xycoords) def _check_xy(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() b = self.get_annotation_clip() if b or (b is None and self.xycoords == 'data'): xy_pixel = self._get_position_xy(renderer) return self.axes.contains_point(xy_pixel) return True def draggable(self, state=None, use_blit=False): from matplotlib.offsetbox import DraggableAnnotation is_draggable = self._draggable is not None if state is None: state = not is_draggable if state: if self._draggable is None: self._draggable = DraggableAnnotation(self, use_blit) else: if self._draggable is not None: self._draggable.disconnect() self._draggable = None return self._draggable class Annotation(Text, _AnnotationBase): def __str__(self): return f'Annotation({self.xy[0]:g}, {self.xy[1]:g}, {self._text!r})' def __init__(self, text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None, annotation_clip=None, **kwargs): _AnnotationBase.__init__(self, xy, xycoords=xycoords, annotation_clip=annotation_clip) if xytext is None and textcoords is not None and (textcoords != xycoords): _api.warn_external('You have used the `textcoords` kwarg, but not the `xytext` kwarg. This can lead to surprising results.') if textcoords is None: textcoords = self.xycoords self._textcoords = textcoords if xytext is None: xytext = self.xy (x, y) = xytext self.arrowprops = arrowprops if arrowprops is not None: arrowprops = arrowprops.copy() if 'arrowstyle' in arrowprops: self._arrow_relpos = arrowprops.pop('relpos', (0.5, 0.5)) else: for key in ['width', 'headwidth', 'headlength', 'shrink']: arrowprops.pop(key, None) if 'frac' in arrowprops: _api.warn_deprecated('3.8', name="the (unused) 'frac' key in 'arrowprops'") arrowprops.pop('frac') self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops) else: self.arrow_patch = None Text.__init__(self, x, y, text, **kwargs) def contains(self, mouseevent): if self._different_canvas(mouseevent): return (False, {}) (contains, tinfo) = Text.contains(self, mouseevent) if self.arrow_patch is not None: (in_patch, _) = self.arrow_patch.contains(mouseevent) contains = contains or in_patch return (contains, tinfo) @property def xycoords(self): return self._xycoords @xycoords.setter def xycoords(self, xycoords): def is_offset(s): return isinstance(s, str) and s.startswith('offset') if isinstance(xycoords, tuple) and any(map(is_offset, xycoords)) or is_offset(xycoords): raise ValueError('xycoords cannot be an offset coordinate') self._xycoords = xycoords @property def xyann(self): return self.get_position() @xyann.setter def xyann(self, xytext): self.set_position(xytext) def get_anncoords(self): return self._textcoords def set_anncoords(self, coords): self._textcoords = coords anncoords = property(get_anncoords, set_anncoords, doc='\n The coordinate system to use for `.Annotation.xyann`.') def set_figure(self, fig): if self.arrow_patch is not None: self.arrow_patch.set_figure(fig) Artist.set_figure(self, fig) def update_positions(self, renderer): self.set_transform(self._get_xy_transform(renderer, self.anncoords)) arrowprops = self.arrowprops if arrowprops is None: return bbox = Text.get_window_extent(self, renderer) arrow_end = (x1, y1) = self._get_position_xy(renderer) ms = arrowprops.get('mutation_scale', self.get_size()) self.arrow_patch.set_mutation_scale(ms) if 'arrowstyle' not in arrowprops: shrink = arrowprops.get('shrink', 0.0) width = arrowprops.get('width', 4) headwidth = arrowprops.get('headwidth', 12) headlength = arrowprops.get('headlength', 12) stylekw = dict(head_length=headlength / ms, head_width=headwidth / ms, tail_width=width / ms) self.arrow_patch.set_arrowstyle('simple', **stylekw) xpos = [(bbox.x0, 0), ((bbox.x0 + bbox.x1) / 2, 0.5), (bbox.x1, 1)] ypos = [(bbox.y0, 0), ((bbox.y0 + bbox.y1) / 2, 0.5), (bbox.y1, 1)] (x, relposx) = min(xpos, key=lambda v: abs(v[0] - x1)) (y, relposy) = min(ypos, key=lambda v: abs(v[0] - y1)) self._arrow_relpos = (relposx, relposy) r = np.hypot(y - y1, x - x1) shrink_pts = shrink * r / renderer.points_to_pixels(1) self.arrow_patch.shrinkA = self.arrow_patch.shrinkB = shrink_pts arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos self.arrow_patch.set_positions(arrow_begin, arrow_end) if 'patchA' in arrowprops: patchA = arrowprops['patchA'] elif self._bbox_patch: patchA = self._bbox_patch elif self.get_text() == '': patchA = None else: pad = renderer.points_to_pixels(4) patchA = Rectangle(xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2), width=bbox.width + pad, height=bbox.height + pad, transform=IdentityTransform(), clip_on=False) self.arrow_patch.set_patchA(patchA) @artist.allow_rasterization def draw(self, renderer): if renderer is not None: self._renderer = renderer if not self.get_visible() or not self._check_xy(renderer): return self.update_positions(renderer) self.update_bbox_position_size(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) Text.draw(self, renderer) def get_window_extent(self, renderer=None): if not self.get_visible() or not self._check_xy(renderer): return Bbox.unit() if renderer is not None: self._renderer = renderer if self._renderer is None: self._renderer = self.get_figure(root=True)._get_renderer() if self._renderer is None: raise RuntimeError('Cannot get window extent without renderer') self.update_positions(self._renderer) text_bbox = Text.get_window_extent(self) bboxes = [text_bbox] if self.arrow_patch is not None: bboxes.append(self.arrow_patch.get_window_extent()) return Bbox.union(bboxes) def get_tightbbox(self, renderer=None): if not self._check_xy(renderer): return Bbox.null() return super().get_tightbbox(renderer) _docstring.interpd.update(Annotation=Annotation.__init__.__doc__) # File: matplotlib-main/lib/matplotlib/textpath.py from collections import OrderedDict import logging import urllib.parse import numpy as np from matplotlib import _text_helpers, dviread from matplotlib.font_manager import FontProperties, get_font, fontManager as _fontManager from matplotlib.ft2font import LOAD_NO_HINTING, LOAD_TARGET_LIGHT from matplotlib.mathtext import MathTextParser from matplotlib.path import Path from matplotlib.texmanager import TexManager from matplotlib.transforms import Affine2D _log = logging.getLogger(__name__) class TextToPath: FONT_SCALE = 100.0 DPI = 72 def __init__(self): self.mathtext_parser = MathTextParser('path') self._texmanager = None def _get_font(self, prop): filenames = _fontManager._find_fonts_by_props(prop) font = get_font(filenames) font.set_size(self.FONT_SCALE, self.DPI) return font def _get_hinting_flag(self): return LOAD_NO_HINTING def _get_char_id(self, font, ccode): return urllib.parse.quote(f'{font.postscript_name}-{ccode:x}') def get_text_width_height_descent(self, s, prop, ismath): fontsize = prop.get_size_in_points() if ismath == 'TeX': return TexManager().get_text_width_height_descent(s, fontsize) scale = fontsize / self.FONT_SCALE if ismath: prop = prop.copy() prop.set_size(self.FONT_SCALE) (width, height, descent, *_) = self.mathtext_parser.parse(s, 72, prop) return (width * scale, height * scale, descent * scale) font = self._get_font(prop) font.set_text(s, 0.0, flags=LOAD_NO_HINTING) (w, h) = font.get_width_height() w /= 64.0 h /= 64.0 d = font.get_descent() d /= 64.0 return (w * scale, h * scale, d * scale) def get_text_path(self, prop, s, ismath=False): if ismath == 'TeX': (glyph_info, glyph_map, rects) = self.get_glyphs_tex(prop, s) elif not ismath: font = self._get_font(prop) (glyph_info, glyph_map, rects) = self.get_glyphs_with_font(font, s) else: (glyph_info, glyph_map, rects) = self.get_glyphs_mathtext(prop, s) (verts, codes) = ([], []) for (glyph_id, xposition, yposition, scale) in glyph_info: (verts1, codes1) = glyph_map[glyph_id] verts.extend(verts1 * scale + [xposition, yposition]) codes.extend(codes1) for (verts1, codes1) in rects: verts.extend(verts1) codes.extend(codes1) if not verts: verts = np.empty((0, 2)) return (verts, codes) def get_glyphs_with_font(self, font, s, glyph_map=None, return_new_glyphs_only=False): if glyph_map is None: glyph_map = OrderedDict() if return_new_glyphs_only: glyph_map_new = OrderedDict() else: glyph_map_new = glyph_map xpositions = [] glyph_ids = [] for item in _text_helpers.layout(s, font): char_id = self._get_char_id(item.ft_object, ord(item.char)) glyph_ids.append(char_id) xpositions.append(item.x) if char_id not in glyph_map: glyph_map_new[char_id] = item.ft_object.get_path() ypositions = [0] * len(xpositions) sizes = [1.0] * len(xpositions) rects = [] return (list(zip(glyph_ids, xpositions, ypositions, sizes)), glyph_map_new, rects) def get_glyphs_mathtext(self, prop, s, glyph_map=None, return_new_glyphs_only=False): prop = prop.copy() prop.set_size(self.FONT_SCALE) (width, height, descent, glyphs, rects) = self.mathtext_parser.parse(s, self.DPI, prop) if not glyph_map: glyph_map = OrderedDict() if return_new_glyphs_only: glyph_map_new = OrderedDict() else: glyph_map_new = glyph_map xpositions = [] ypositions = [] glyph_ids = [] sizes = [] for (font, fontsize, ccode, ox, oy) in glyphs: char_id = self._get_char_id(font, ccode) if char_id not in glyph_map: font.clear() font.set_size(self.FONT_SCALE, self.DPI) font.load_char(ccode, flags=LOAD_NO_HINTING) glyph_map_new[char_id] = font.get_path() xpositions.append(ox) ypositions.append(oy) glyph_ids.append(char_id) size = fontsize / self.FONT_SCALE sizes.append(size) myrects = [] for (ox, oy, w, h) in rects: vert1 = [(ox, oy), (ox, oy + h), (ox + w, oy + h), (ox + w, oy), (ox, oy), (0, 0)] code1 = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] myrects.append((vert1, code1)) return (list(zip(glyph_ids, xpositions, ypositions, sizes)), glyph_map_new, myrects) def get_glyphs_tex(self, prop, s, glyph_map=None, return_new_glyphs_only=False): dvifile = TexManager().make_dvi(s, self.FONT_SCALE) with dviread.Dvi(dvifile, self.DPI) as dvi: (page,) = dvi if glyph_map is None: glyph_map = OrderedDict() if return_new_glyphs_only: glyph_map_new = OrderedDict() else: glyph_map_new = glyph_map (glyph_ids, xpositions, ypositions, sizes) = ([], [], [], []) for text in page.text: font = get_font(text.font_path) char_id = self._get_char_id(font, text.glyph) if char_id not in glyph_map: font.clear() font.set_size(self.FONT_SCALE, self.DPI) glyph_name_or_index = text.glyph_name_or_index if isinstance(glyph_name_or_index, str): index = font.get_name_index(glyph_name_or_index) font.load_glyph(index, flags=LOAD_TARGET_LIGHT) elif isinstance(glyph_name_or_index, int): self._select_native_charmap(font) font.load_char(glyph_name_or_index, flags=LOAD_TARGET_LIGHT) else: raise TypeError(f'Glyph spec of unexpected type: {glyph_name_or_index!r}') glyph_map_new[char_id] = font.get_path() glyph_ids.append(char_id) xpositions.append(text.x) ypositions.append(text.y) sizes.append(text.font_size / self.FONT_SCALE) myrects = [] for (ox, oy, h, w) in page.boxes: vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h), (ox, oy + h), (ox, oy), (0, 0)] code1 = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] myrects.append((vert1, code1)) return (list(zip(glyph_ids, xpositions, ypositions, sizes)), glyph_map_new, myrects) @staticmethod def _select_native_charmap(font): for charmap_code in [1094992451, 1094995778]: try: font.select_charmap(charmap_code) except (ValueError, RuntimeError): pass else: break else: _log.warning('No supported encoding in font (%s).', font.fname) text_to_path = TextToPath() class TextPath(Path): def __init__(self, xy, s, size=None, prop=None, _interpolation_steps=1, usetex=False): from matplotlib.text import Text prop = FontProperties._from_any(prop) if size is None: size = prop.get_size_in_points() self._xy = xy self.set_size(size) self._cached_vertices = None (s, ismath) = Text(usetex=usetex)._preprocess_math(s) super().__init__(*text_to_path.get_text_path(prop, s, ismath=ismath), _interpolation_steps=_interpolation_steps, readonly=True) self._should_simplify = False def set_size(self, size): self._size = size self._invalid = True def get_size(self): return self._size @property def vertices(self): self._revalidate_path() return self._cached_vertices @property def codes(self): return self._codes def _revalidate_path(self): if self._invalid or self._cached_vertices is None: tr = Affine2D().scale(self._size / text_to_path.FONT_SCALE).translate(*self._xy) self._cached_vertices = tr.transform(self._vertices) self._cached_vertices.flags.writeable = False self._invalid = False # File: matplotlib-main/lib/matplotlib/ticker.py """""" import itertools import logging import locale import math from numbers import Integral import string import numpy as np import matplotlib as mpl from matplotlib import _api, cbook from matplotlib import transforms as mtransforms _log = logging.getLogger(__name__) __all__ = ('TickHelper', 'Formatter', 'FixedFormatter', 'NullFormatter', 'FuncFormatter', 'FormatStrFormatter', 'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter', 'LogFormatterExponent', 'LogFormatterMathtext', 'LogFormatterSciNotation', 'LogitFormatter', 'EngFormatter', 'PercentFormatter', 'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator', 'LinearLocator', 'LogLocator', 'AutoLocator', 'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator', 'SymmetricalLogLocator', 'AsinhLocator', 'LogitLocator') class _DummyAxis: __name__ = 'dummy' def __init__(self, minpos=0): self._data_interval = (0, 1) self._view_interval = (0, 1) self._minpos = minpos def get_view_interval(self): return self._view_interval def set_view_interval(self, vmin, vmax): self._view_interval = (vmin, vmax) def get_minpos(self): return self._minpos def get_data_interval(self): return self._data_interval def set_data_interval(self, vmin, vmax): self._data_interval = (vmin, vmax) def get_tick_space(self): return 9 class TickHelper: axis = None def set_axis(self, axis): self.axis = axis def create_dummy_axis(self, **kwargs): if self.axis is None: self.axis = _DummyAxis(**kwargs) class Formatter(TickHelper): locs = [] def __call__(self, x, pos=None): raise NotImplementedError('Derived must override') def format_ticks(self, values): self.set_locs(values) return [self(value, i) for (i, value) in enumerate(values)] def format_data(self, value): return self.__call__(value) def format_data_short(self, value): return self.format_data(value) def get_offset(self): return '' def set_locs(self, locs): self.locs = locs @staticmethod def fix_minus(s): return s.replace('-', '−') if mpl.rcParams['axes.unicode_minus'] else s def _set_locator(self, locator): pass class NullFormatter(Formatter): def __call__(self, x, pos=None): return '' class FixedFormatter(Formatter): def __init__(self, seq): self.seq = seq self.offset_string = '' def __call__(self, x, pos=None): if pos is None or pos >= len(self.seq): return '' else: return self.seq[pos] def get_offset(self): return self.offset_string def set_offset_string(self, ofs): self.offset_string = ofs class FuncFormatter(Formatter): def __init__(self, func): self.func = func self.offset_string = '' def __call__(self, x, pos=None): return self.func(x, pos) def get_offset(self): return self.offset_string def set_offset_string(self, ofs): self.offset_string = ofs class FormatStrFormatter(Formatter): def __init__(self, fmt): self.fmt = fmt def __call__(self, x, pos=None): return self.fmt % x class _UnicodeMinusFormat(string.Formatter): def format_field(self, value, format_spec): return Formatter.fix_minus(super().format_field(value, format_spec)) class StrMethodFormatter(Formatter): def __init__(self, fmt): self.fmt = fmt def __call__(self, x, pos=None): return _UnicodeMinusFormat().format(self.fmt, x=x, pos=pos) class ScalarFormatter(Formatter): def __init__(self, useOffset=None, useMathText=None, useLocale=None): if useOffset is None: useOffset = mpl.rcParams['axes.formatter.useoffset'] self._offset_threshold = mpl.rcParams['axes.formatter.offset_threshold'] self.set_useOffset(useOffset) self._usetex = mpl.rcParams['text.usetex'] self.set_useMathText(useMathText) self.orderOfMagnitude = 0 self.format = '' self._scientific = True self._powerlimits = mpl.rcParams['axes.formatter.limits'] self.set_useLocale(useLocale) def get_useOffset(self): return self._useOffset def set_useOffset(self, val): if val in [True, False]: self.offset = 0 self._useOffset = val else: self._useOffset = False self.offset = val useOffset = property(fget=get_useOffset, fset=set_useOffset) def get_useLocale(self): return self._useLocale def set_useLocale(self, val): if val is None: self._useLocale = mpl.rcParams['axes.formatter.use_locale'] else: self._useLocale = val useLocale = property(fget=get_useLocale, fset=set_useLocale) def _format_maybe_minus_and_locale(self, fmt, arg): return self.fix_minus((','.join((locale.format_string(part, (arg,), True).replace(',', '{,}') for part in fmt.split(','))) if self._useMathText else locale.format_string(fmt, (arg,), True)) if self._useLocale else fmt % arg) def get_useMathText(self): return self._useMathText def set_useMathText(self, val): if val is None: self._useMathText = mpl.rcParams['axes.formatter.use_mathtext'] if self._useMathText is False: try: from matplotlib import font_manager ufont = font_manager.findfont(font_manager.FontProperties(mpl.rcParams['font.family']), fallback_to_default=False) except ValueError: ufont = None if ufont == str(cbook._get_data_path('fonts/ttf/cmr10.ttf')): _api.warn_external('cmr10 font should ideally be used with mathtext, set axes.formatter.use_mathtext to True') else: self._useMathText = val useMathText = property(fget=get_useMathText, fset=set_useMathText) def __call__(self, x, pos=None): if len(self.locs) == 0: return '' else: xp = (x - self.offset) / 10.0 ** self.orderOfMagnitude if abs(xp) < 1e-08: xp = 0 return self._format_maybe_minus_and_locale(self.format, xp) def set_scientific(self, b): self._scientific = bool(b) def set_powerlimits(self, lims): if len(lims) != 2: raise ValueError("'lims' must be a sequence of length 2") self._powerlimits = lims def format_data_short(self, value): if value is np.ma.masked: return '' if isinstance(value, Integral): fmt = '%d' else: if getattr(self.axis, '__name__', '') in ['xaxis', 'yaxis']: if self.axis.__name__ == 'xaxis': axis_trf = self.axis.axes.get_xaxis_transform() axis_inv_trf = axis_trf.inverted() screen_xy = axis_trf.transform((value, 0)) neighbor_values = axis_inv_trf.transform(screen_xy + [[-1, 0], [+1, 0]])[:, 0] else: axis_trf = self.axis.axes.get_yaxis_transform() axis_inv_trf = axis_trf.inverted() screen_xy = axis_trf.transform((0, value)) neighbor_values = axis_inv_trf.transform(screen_xy + [[0, -1], [0, +1]])[:, 1] delta = abs(neighbor_values - value).max() else: (a, b) = self.axis.get_view_interval() delta = (b - a) / 10000.0 fmt = f'%-#.{cbook._g_sig_digits(value, delta)}g' return self._format_maybe_minus_and_locale(fmt, value) def format_data(self, value): e = math.floor(math.log10(abs(value))) s = round(value / 10 ** e, 10) significand = self._format_maybe_minus_and_locale('%d' if s % 1 == 0 else '%1.10g', s) if e == 0: return significand exponent = self._format_maybe_minus_and_locale('%d', e) if self._useMathText or self._usetex: exponent = '10^{%s}' % exponent return exponent if s == 1 else f'{significand} \\times {exponent}' else: return f'{significand}e{exponent}' def get_offset(self): if len(self.locs) == 0: return '' if self.orderOfMagnitude or self.offset: offsetStr = '' sciNotStr = '' if self.offset: offsetStr = self.format_data(self.offset) if self.offset > 0: offsetStr = '+' + offsetStr if self.orderOfMagnitude: if self._usetex or self._useMathText: sciNotStr = self.format_data(10 ** self.orderOfMagnitude) else: sciNotStr = '1e%d' % self.orderOfMagnitude if self._useMathText or self._usetex: if sciNotStr != '': sciNotStr = '\\times\\mathdefault{%s}' % sciNotStr s = f'${sciNotStr}\\mathdefault{{{offsetStr}}}$' else: s = ''.join((sciNotStr, offsetStr)) return self.fix_minus(s) return '' def set_locs(self, locs): self.locs = locs if len(self.locs) > 0: if self._useOffset: self._compute_offset() self._set_order_of_magnitude() self._set_format() def _compute_offset(self): locs = self.locs (vmin, vmax) = sorted(self.axis.get_view_interval()) locs = np.asarray(locs) locs = locs[(vmin <= locs) & (locs <= vmax)] if not len(locs): self.offset = 0 return (lmin, lmax) = (locs.min(), locs.max()) if lmin == lmax or lmin <= 0 <= lmax: self.offset = 0 return (abs_min, abs_max) = sorted([abs(float(lmin)), abs(float(lmax))]) sign = math.copysign(1, lmin) oom_max = np.ceil(math.log10(abs_max)) oom = 1 + next((oom for oom in itertools.count(oom_max, -1) if abs_min // 10 ** oom != abs_max // 10 ** oom)) if (abs_max - abs_min) / 10 ** oom <= 0.01: oom = 1 + next((oom for oom in itertools.count(oom_max, -1) if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)) n = self._offset_threshold - 1 self.offset = sign * (abs_max // 10 ** oom) * 10 ** oom if abs_max // 10 ** oom >= 10 ** n else 0 def _set_order_of_magnitude(self): if not self._scientific: self.orderOfMagnitude = 0 return if self._powerlimits[0] == self._powerlimits[1] != 0: self.orderOfMagnitude = self._powerlimits[0] return (vmin, vmax) = sorted(self.axis.get_view_interval()) locs = np.asarray(self.locs) locs = locs[(vmin <= locs) & (locs <= vmax)] locs = np.abs(locs) if not len(locs): self.orderOfMagnitude = 0 return if self.offset: oom = math.floor(math.log10(vmax - vmin)) else: val = locs.max() if val == 0: oom = 0 else: oom = math.floor(math.log10(val)) if oom <= self._powerlimits[0]: self.orderOfMagnitude = oom elif oom >= self._powerlimits[1]: self.orderOfMagnitude = oom else: self.orderOfMagnitude = 0 def _set_format(self): if len(self.locs) < 2: _locs = [*self.locs, *self.axis.get_view_interval()] else: _locs = self.locs locs = (np.asarray(_locs) - self.offset) / 10.0 ** self.orderOfMagnitude loc_range = np.ptp(locs) if loc_range == 0: loc_range = np.max(np.abs(locs)) if loc_range == 0: loc_range = 1 if len(self.locs) < 2: locs = locs[:-2] loc_range_oom = int(math.floor(math.log10(loc_range))) sigfigs = max(0, 3 - loc_range_oom) thresh = 0.001 * 10 ** loc_range_oom while sigfigs >= 0: if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh: sigfigs -= 1 else: break sigfigs += 1 self.format = f'%1.{sigfigs}f' if self._usetex or self._useMathText: self.format = '$\\mathdefault{%s}$' % self.format class LogFormatter(Formatter): def __init__(self, base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None): self.set_base(base) self.set_label_minor(labelOnlyBase) if minor_thresholds is None: if mpl.rcParams['_internal.classic_mode']: minor_thresholds = (0, 0) else: minor_thresholds = (1, 0.4) self.minor_thresholds = minor_thresholds self._sublabels = None self._linthresh = linthresh def set_base(self, base): self._base = float(base) def set_label_minor(self, labelOnlyBase): self.labelOnlyBase = labelOnlyBase def set_locs(self, locs=None): if np.isinf(self.minor_thresholds[0]): self._sublabels = None return linthresh = self._linthresh if linthresh is None: try: linthresh = self.axis.get_transform().linthresh except AttributeError: pass (vmin, vmax) = self.axis.get_view_interval() if vmin > vmax: (vmin, vmax) = (vmax, vmin) if linthresh is None and vmin <= 0: self._sublabels = {1} return b = self._base if linthresh is not None: numdec = 0 if vmin < -linthresh: rhs = min(vmax, -linthresh) numdec += math.log(vmin / rhs) / math.log(b) if vmax > linthresh: lhs = max(vmin, linthresh) numdec += math.log(vmax / lhs) / math.log(b) else: vmin = math.log(vmin) / math.log(b) vmax = math.log(vmax) / math.log(b) numdec = abs(vmax - vmin) if numdec > self.minor_thresholds[0]: self._sublabels = {1} elif numdec > self.minor_thresholds[1]: c = np.geomspace(1, b, int(b) // 2 + 1) self._sublabels = set(np.round(c)) else: self._sublabels = set(np.arange(1, b + 1)) def _num_to_string(self, x, vmin, vmax): if x > 10000: s = '%1.0e' % x elif x < 1: s = '%1.0e' % x else: s = self._pprint_val(x, vmax - vmin) return s def __call__(self, x, pos=None): if x == 0.0: return '0' x = abs(x) b = self._base fx = math.log(x) / math.log(b) is_x_decade = _is_close_to_int(fx) exponent = round(fx) if is_x_decade else np.floor(fx) coeff = round(b ** (fx - exponent)) if self.labelOnlyBase and (not is_x_decade): return '' if self._sublabels is not None and coeff not in self._sublabels: return '' (vmin, vmax) = self.axis.get_view_interval() (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=0.05) s = self._num_to_string(x, vmin, vmax) return self.fix_minus(s) def format_data(self, value): with cbook._setattr_cm(self, labelOnlyBase=False): return cbook.strip_math(self.__call__(value)) def format_data_short(self, value): return ('%-12g' % value).rstrip() def _pprint_val(self, x, d): if abs(x) < 10000.0 and x == int(x): return '%d' % x fmt = '%1.3e' if d < 0.01 else '%1.3f' if d <= 1 else '%1.2f' if d <= 10 else '%1.1f' if d <= 100000.0 else '%1.1e' s = fmt % x tup = s.split('e') if len(tup) == 2: mantissa = tup[0].rstrip('0').rstrip('.') exponent = int(tup[1]) if exponent: s = '%se%d' % (mantissa, exponent) else: s = mantissa else: s = s.rstrip('0').rstrip('.') return s class LogFormatterExponent(LogFormatter): def _num_to_string(self, x, vmin, vmax): fx = math.log(x) / math.log(self._base) if abs(fx) > 10000: s = '%1.0g' % fx elif abs(fx) < 1: s = '%1.0g' % fx else: fd = math.log(vmax - vmin) / math.log(self._base) s = self._pprint_val(fx, fd) return s class LogFormatterMathtext(LogFormatter): def _non_decade_format(self, sign_string, base, fx, usetex): return '$\\mathdefault{%s%s^{%.2f}}$' % (sign_string, base, fx) def __call__(self, x, pos=None): if x == 0: return '$\\mathdefault{0}$' sign_string = '-' if x < 0 else '' x = abs(x) b = self._base fx = math.log(x) / math.log(b) is_x_decade = _is_close_to_int(fx) exponent = round(fx) if is_x_decade else np.floor(fx) coeff = round(b ** (fx - exponent)) if self.labelOnlyBase and (not is_x_decade): return '' if self._sublabels is not None and coeff not in self._sublabels: return '' if is_x_decade: fx = round(fx) if b % 1 == 0.0: base = '%d' % b else: base = '%s' % b if abs(fx) < mpl.rcParams['axes.formatter.min_exponent']: return '$\\mathdefault{%s%g}$' % (sign_string, x) elif not is_x_decade: usetex = mpl.rcParams['text.usetex'] return self._non_decade_format(sign_string, base, fx, usetex) else: return '$\\mathdefault{%s%s^{%d}}$' % (sign_string, base, fx) class LogFormatterSciNotation(LogFormatterMathtext): def _non_decade_format(self, sign_string, base, fx, usetex): b = float(base) exponent = math.floor(fx) coeff = b ** (fx - exponent) if _is_close_to_int(coeff): coeff = round(coeff) return '$\\mathdefault{%s%g\\times%s^{%d}}$' % (sign_string, coeff, base, exponent) class LogitFormatter(Formatter): def __init__(self, *, use_overline=False, one_half='\\frac{1}{2}', minor=False, minor_threshold=25, minor_number=6): self._use_overline = use_overline self._one_half = one_half self._minor = minor self._labelled = set() self._minor_threshold = minor_threshold self._minor_number = minor_number def use_overline(self, use_overline): self._use_overline = use_overline def set_one_half(self, one_half): self._one_half = one_half def set_minor_threshold(self, minor_threshold): self._minor_threshold = minor_threshold def set_minor_number(self, minor_number): self._minor_number = minor_number def set_locs(self, locs): self.locs = np.array(locs) self._labelled.clear() if not self._minor: return None if all((_is_decade(x, rtol=1e-07) or _is_decade(1 - x, rtol=1e-07) or (_is_close_to_int(2 * x) and int(np.round(2 * x)) == 1) for x in locs)): return None if len(locs) < self._minor_threshold: if len(locs) < self._minor_number: self._labelled.update(locs) else: diff = np.diff(-np.log(1 / self.locs - 1)) space_pessimistic = np.minimum(np.concatenate(((np.inf,), diff)), np.concatenate((diff, (np.inf,)))) space_sum = np.concatenate(((0,), diff)) + np.concatenate((diff, (0,))) good_minor = sorted(range(len(self.locs)), key=lambda i: (space_pessimistic[i], space_sum[i]))[-self._minor_number:] self._labelled.update((locs[i] for i in good_minor)) def _format_value(self, x, locs, sci_notation=True): if sci_notation: exponent = math.floor(np.log10(x)) min_precision = 0 else: exponent = 0 min_precision = 1 value = x * 10 ** (-exponent) if len(locs) < 2: precision = min_precision else: diff = np.sort(np.abs(locs - x))[1] precision = -np.log10(diff) + exponent precision = int(np.round(precision)) if _is_close_to_int(precision) else math.ceil(precision) if precision < min_precision: precision = min_precision mantissa = '%.*f' % (precision, value) if not sci_notation: return mantissa s = '%s\\cdot10^{%d}' % (mantissa, exponent) return s def _one_minus(self, s): if self._use_overline: return '\\overline{%s}' % s else: return f'1-{s}' def __call__(self, x, pos=None): if self._minor and x not in self._labelled: return '' if x <= 0 or x >= 1: return '' if _is_close_to_int(2 * x) and round(2 * x) == 1: s = self._one_half elif x < 0.5 and _is_decade(x, rtol=1e-07): exponent = round(math.log10(x)) s = '10^{%d}' % exponent elif x > 0.5 and _is_decade(1 - x, rtol=1e-07): exponent = round(math.log10(1 - x)) s = self._one_minus('10^{%d}' % exponent) elif x < 0.1: s = self._format_value(x, self.locs) elif x > 0.9: s = self._one_minus(self._format_value(1 - x, 1 - self.locs)) else: s = self._format_value(x, self.locs, sci_notation=False) return '$\\mathdefault{%s}$' % s def format_data_short(self, value): if value < 0.1: return f'{value:e}' if value < 0.9: return f'{value:f}' return f'1-{1 - value:e}' class EngFormatter(Formatter): ENG_PREFIXES = {-30: 'q', -27: 'r', -24: 'y', -21: 'z', -18: 'a', -15: 'f', -12: 'p', -9: 'n', -6: 'µ', -3: 'm', 0: '', 3: 'k', 6: 'M', 9: 'G', 12: 'T', 15: 'P', 18: 'E', 21: 'Z', 24: 'Y', 27: 'R', 30: 'Q'} def __init__(self, unit='', places=None, sep=' ', *, usetex=None, useMathText=None): self.unit = unit self.places = places self.sep = sep self.set_usetex(usetex) self.set_useMathText(useMathText) def get_usetex(self): return self._usetex def set_usetex(self, val): if val is None: self._usetex = mpl.rcParams['text.usetex'] else: self._usetex = val usetex = property(fget=get_usetex, fset=set_usetex) def get_useMathText(self): return self._useMathText def set_useMathText(self, val): if val is None: self._useMathText = mpl.rcParams['axes.formatter.use_mathtext'] else: self._useMathText = val useMathText = property(fget=get_useMathText, fset=set_useMathText) def __call__(self, x, pos=None): s = f'{self.format_eng(x)}{self.unit}' if self.sep and s.endswith(self.sep): s = s[:-len(self.sep)] return self.fix_minus(s) def format_eng(self, num): sign = 1 fmt = 'g' if self.places is None else f'.{self.places:d}f' if num < 0: sign = -1 num = -num if num != 0: pow10 = int(math.floor(math.log10(num) / 3) * 3) else: pow10 = 0 num = 0.0 pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES)) mant = sign * num / 10.0 ** pow10 if abs(float(format(mant, fmt))) >= 1000 and pow10 < max(self.ENG_PREFIXES): mant /= 1000 pow10 += 3 prefix = self.ENG_PREFIXES[int(pow10)] if self._usetex or self._useMathText: formatted = f'${mant:{fmt}}${self.sep}{prefix}' else: formatted = f'{mant:{fmt}}{self.sep}{prefix}' return formatted class PercentFormatter(Formatter): def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False): self.xmax = xmax + 0.0 self.decimals = decimals self._symbol = symbol self._is_latex = is_latex def __call__(self, x, pos=None): (ax_min, ax_max) = self.axis.get_view_interval() display_range = abs(ax_max - ax_min) return self.fix_minus(self.format_pct(x, display_range)) def format_pct(self, x, display_range): x = self.convert_to_pct(x) if self.decimals is None: scaled_range = self.convert_to_pct(display_range) if scaled_range <= 0: decimals = 0 else: decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range)) if decimals > 5: decimals = 5 elif decimals < 0: decimals = 0 else: decimals = self.decimals s = f'{x:0.{int(decimals)}f}' return s + self.symbol def convert_to_pct(self, x): return 100.0 * (x / self.xmax) @property def symbol(self): symbol = self._symbol if not symbol: symbol = '' elif not self._is_latex and mpl.rcParams['text.usetex']: for spec in '\\#$%&~_^{}': symbol = symbol.replace(spec, '\\' + spec) return symbol @symbol.setter def symbol(self, symbol): self._symbol = symbol class Locator(TickHelper): MAXTICKS = 1000 def tick_values(self, vmin, vmax): raise NotImplementedError('Derived must override') def set_params(self, **kwargs): _api.warn_external("'set_params()' not defined for locator of type " + str(type(self))) def __call__(self): raise NotImplementedError('Derived must override') def raise_if_exceeds(self, locs): if len(locs) >= self.MAXTICKS: _log.warning('Locator attempting to generate %s ticks ([%s, ..., %s]), which exceeds Locator.MAXTICKS (%s).', len(locs), locs[0], locs[-1], self.MAXTICKS) return locs def nonsingular(self, v0, v1): return mtransforms.nonsingular(v0, v1, expander=0.05) def view_limits(self, vmin, vmax): return mtransforms.nonsingular(vmin, vmax) class IndexLocator(Locator): def __init__(self, base, offset): self._base = base self.offset = offset def set_params(self, base=None, offset=None): if base is not None: self._base = base if offset is not None: self.offset = offset def __call__(self): (dmin, dmax) = self.axis.get_data_interval() return self.tick_values(dmin, dmax) def tick_values(self, vmin, vmax): return self.raise_if_exceeds(np.arange(vmin + self.offset, vmax + 1, self._base)) class FixedLocator(Locator): def __init__(self, locs, nbins=None): self.locs = np.asarray(locs) _api.check_shape((None,), locs=self.locs) self.nbins = max(nbins, 2) if nbins is not None else None def set_params(self, nbins=None): if nbins is not None: self.nbins = nbins def __call__(self): return self.tick_values(None, None) def tick_values(self, vmin, vmax): if self.nbins is None: return self.locs step = max(int(np.ceil(len(self.locs) / self.nbins)), 1) ticks = self.locs[::step] for i in range(1, step): ticks1 = self.locs[i::step] if np.abs(ticks1).min() < np.abs(ticks).min(): ticks = ticks1 return self.raise_if_exceeds(ticks) class NullLocator(Locator): def __call__(self): return self.tick_values(None, None) def tick_values(self, vmin, vmax): return [] class LinearLocator(Locator): def __init__(self, numticks=None, presets=None): self.numticks = numticks if presets is None: self.presets = {} else: self.presets = presets @property def numticks(self): return self._numticks if self._numticks is not None else 11 @numticks.setter def numticks(self, numticks): self._numticks = numticks def set_params(self, numticks=None, presets=None): if presets is not None: self.presets = presets if numticks is not None: self.numticks = numticks def __call__(self): (vmin, vmax) = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=0.05) if (vmin, vmax) in self.presets: return self.presets[vmin, vmax] if self.numticks == 0: return [] ticklocs = np.linspace(vmin, vmax, self.numticks) return self.raise_if_exceeds(ticklocs) def view_limits(self, vmin, vmax): if vmax < vmin: (vmin, vmax) = (vmax, vmin) if vmin == vmax: vmin -= 1 vmax += 1 if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': (exponent, remainder) = divmod(math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1))) exponent -= remainder < 0.5 scale = max(self.numticks - 1, 1) ** (-exponent) vmin = math.floor(scale * vmin) / scale vmax = math.ceil(scale * vmax) / scale return mtransforms.nonsingular(vmin, vmax) class MultipleLocator(Locator): def __init__(self, base=1.0, offset=0.0): self._edge = _Edge_integer(base, 0) self._offset = offset def set_params(self, base=None, offset=None): if base is not None: self._edge = _Edge_integer(base, 0) if offset is not None: self._offset = offset def __call__(self): (vmin, vmax) = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if vmax < vmin: (vmin, vmax) = (vmax, vmin) step = self._edge.step vmin -= self._offset vmax -= self._offset vmin = self._edge.ge(vmin) * step n = (vmax - vmin + 0.001 * step) // step locs = vmin - step + np.arange(n + 3) * step + self._offset return self.raise_if_exceeds(locs) def view_limits(self, dmin, dmax): if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': vmin = self._edge.le(dmin - self._offset) * self._edge.step + self._offset vmax = self._edge.ge(dmax - self._offset) * self._edge.step + self._offset if vmin == vmax: vmin -= 1 vmax += 1 else: vmin = dmin vmax = dmax return mtransforms.nonsingular(vmin, vmax) def scale_range(vmin, vmax, n=1, threshold=100): dv = abs(vmax - vmin) meanv = (vmax + vmin) / 2 if abs(meanv) / dv < threshold: offset = 0 else: offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv) scale = 10 ** (math.log10(dv / n) // 1) return (scale, offset) class _Edge_integer: def __init__(self, step, offset): if step <= 0: raise ValueError("'step' must be positive") self.step = step self._offset = abs(offset) def closeto(self, ms, edge): if self._offset > 0: digits = np.log10(self._offset / self.step) tol = max(1e-10, 10 ** (digits - 12)) tol = min(0.4999, tol) else: tol = 1e-10 return abs(ms - edge) < tol def le(self, x): (d, m) = divmod(x, self.step) if self.closeto(m / self.step, 1): return d + 1 return d def ge(self, x): (d, m) = divmod(x, self.step) if self.closeto(m / self.step, 0): return d return d + 1 class MaxNLocator(Locator): default_params = dict(nbins=10, steps=None, integer=False, symmetric=False, prune=None, min_n_ticks=2) def __init__(self, nbins=None, **kwargs): if nbins is not None: kwargs['nbins'] = nbins self.set_params(**{**self.default_params, **kwargs}) @staticmethod def _validate_steps(steps): if not np.iterable(steps): raise ValueError('steps argument must be an increasing sequence of numbers between 1 and 10 inclusive') steps = np.asarray(steps) if np.any(np.diff(steps) <= 0) or steps[-1] > 10 or steps[0] < 1: raise ValueError('steps argument must be an increasing sequence of numbers between 1 and 10 inclusive') if steps[0] != 1: steps = np.concatenate([[1], steps]) if steps[-1] != 10: steps = np.concatenate([steps, [10]]) return steps @staticmethod def _staircase(steps): return np.concatenate([0.1 * steps[:-1], steps, [10 * steps[1]]]) def set_params(self, **kwargs): if 'nbins' in kwargs: self._nbins = kwargs.pop('nbins') if self._nbins != 'auto': self._nbins = int(self._nbins) if 'symmetric' in kwargs: self._symmetric = kwargs.pop('symmetric') if 'prune' in kwargs: prune = kwargs.pop('prune') _api.check_in_list(['upper', 'lower', 'both', None], prune=prune) self._prune = prune if 'min_n_ticks' in kwargs: self._min_n_ticks = max(1, kwargs.pop('min_n_ticks')) if 'steps' in kwargs: steps = kwargs.pop('steps') if steps is None: self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) else: self._steps = self._validate_steps(steps) self._extended_steps = self._staircase(self._steps) if 'integer' in kwargs: self._integer = kwargs.pop('integer') if kwargs: raise _api.kwarg_error('set_params', kwargs) def _raw_ticks(self, vmin, vmax): if self._nbins == 'auto': if self.axis is not None: nbins = np.clip(self.axis.get_tick_space(), max(1, self._min_n_ticks - 1), 9) else: nbins = 9 else: nbins = self._nbins (scale, offset) = scale_range(vmin, vmax, nbins) _vmin = vmin - offset _vmax = vmax - offset steps = self._extended_steps * scale if self._integer: igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001) steps = steps[igood] raw_step = (_vmax - _vmin) / nbins if hasattr(self.axis, 'axes') and self.axis.axes.name == '3d': raw_step = raw_step * 23 / 24 large_steps = steps >= raw_step if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': floored_vmins = _vmin // steps * steps floored_vmaxs = floored_vmins + steps * nbins large_steps = large_steps & (floored_vmaxs >= _vmax) if any(large_steps): istep = np.nonzero(large_steps)[0][0] else: istep = len(steps) - 1 for step in steps[:istep + 1][::-1]: if self._integer and np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1: step = max(1, step) best_vmin = _vmin // step * step edge = _Edge_integer(step, offset) low = edge.le(_vmin - best_vmin) high = edge.ge(_vmax - best_vmin) ticks = np.arange(low, high + 1) * step + best_vmin nticks = ((ticks <= _vmax) & (ticks >= _vmin)).sum() if nticks >= self._min_n_ticks: break return ticks + offset def __call__(self): (vmin, vmax) = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if self._symmetric: vmax = max(abs(vmin), abs(vmax)) vmin = -vmax (vmin, vmax) = mtransforms.nonsingular(vmin, vmax, expander=1e-13, tiny=1e-14) locs = self._raw_ticks(vmin, vmax) prune = self._prune if prune == 'lower': locs = locs[1:] elif prune == 'upper': locs = locs[:-1] elif prune == 'both': locs = locs[1:-1] return self.raise_if_exceeds(locs) def view_limits(self, dmin, dmax): if self._symmetric: dmax = max(abs(dmin), abs(dmax)) dmin = -dmax (dmin, dmax) = mtransforms.nonsingular(dmin, dmax, expander=1e-12, tiny=1e-13) if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': return self._raw_ticks(dmin, dmax)[[0, -1]] else: return (dmin, dmax) def _is_decade(x, *, base=10, rtol=None): if not np.isfinite(x): return False if x == 0.0: return True lx = np.log(abs(x)) / np.log(base) if rtol is None: return np.isclose(lx, np.round(lx)) else: return np.isclose(lx, np.round(lx), rtol=rtol) def _decade_less_equal(x, base): return x if x == 0 else -_decade_greater_equal(-x, base) if x < 0 else base ** np.floor(np.log(x) / np.log(base)) def _decade_greater_equal(x, base): return x if x == 0 else -_decade_less_equal(-x, base) if x < 0 else base ** np.ceil(np.log(x) / np.log(base)) def _decade_less(x, base): if x < 0: return -_decade_greater(-x, base) less = _decade_less_equal(x, base) if less == x: less /= base return less def _decade_greater(x, base): if x < 0: return -_decade_less(-x, base) greater = _decade_greater_equal(x, base) if greater == x: greater *= base return greater def _is_close_to_int(x): return math.isclose(x, round(x)) class LogLocator(Locator): def __init__(self, base=10.0, subs=(1.0,), *, numticks=None): if numticks is None: if mpl.rcParams['_internal.classic_mode']: numticks = 15 else: numticks = 'auto' self._base = float(base) self._set_subs(subs) self.numticks = numticks def set_params(self, base=None, subs=None, *, numticks=None): if base is not None: self._base = float(base) if subs is not None: self._set_subs(subs) if numticks is not None: self.numticks = numticks def _set_subs(self, subs): if subs is None: self._subs = 'auto' elif isinstance(subs, str): _api.check_in_list(('all', 'auto'), subs=subs) self._subs = subs else: try: self._subs = np.asarray(subs, dtype=float) except ValueError as e: raise ValueError(f"subs must be None, 'all', 'auto' or a sequence of floats, not {subs}.") from e if self._subs.ndim != 1: raise ValueError(f'A sequence passed to subs must be 1-dimensional, not {self._subs.ndim}-dimensional.') def __call__(self): (vmin, vmax) = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): if self.numticks == 'auto': if self.axis is not None: numticks = np.clip(self.axis.get_tick_space(), 2, 9) else: numticks = 9 else: numticks = self.numticks b = self._base if vmin <= 0.0: if self.axis is not None: vmin = self.axis.get_minpos() if vmin <= 0.0 or not np.isfinite(vmin): raise ValueError('Data has no positive values, and therefore cannot be log-scaled.') _log.debug('vmin %s vmax %s', vmin, vmax) if vmax < vmin: (vmin, vmax) = (vmax, vmin) log_vmin = math.log(vmin) / math.log(b) log_vmax = math.log(vmax) / math.log(b) numdec = math.floor(log_vmax) - math.ceil(log_vmin) if isinstance(self._subs, str): if numdec > 10 or b < 3: if self._subs == 'auto': return np.array([]) else: subs = np.array([1.0]) else: _first = 2.0 if self._subs == 'auto' else 1.0 subs = np.arange(_first, b) else: subs = self._subs stride = max(math.ceil(numdec / (numticks - 1)), 1) if mpl.rcParams['_internal.classic_mode'] else numdec // numticks + 1 if stride >= numdec: stride = max(1, numdec - 1) have_subs = len(subs) > 1 or (len(subs) == 1 and subs[0] != 1.0) decades = np.arange(math.floor(log_vmin) - stride, math.ceil(log_vmax) + 2 * stride, stride) if have_subs: if stride == 1: ticklocs = np.concatenate([subs * decade_start for decade_start in b ** decades]) else: ticklocs = np.array([]) else: ticklocs = b ** decades _log.debug('ticklocs %r', ticklocs) if len(subs) > 1 and stride == 1 and (((vmin <= ticklocs) & (ticklocs <= vmax)).sum() <= 1): return AutoLocator().tick_values(vmin, vmax) else: return self.raise_if_exceeds(ticklocs) def view_limits(self, vmin, vmax): b = self._base (vmin, vmax) = self.nonsingular(vmin, vmax) if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': vmin = _decade_less_equal(vmin, b) vmax = _decade_greater_equal(vmax, b) return (vmin, vmax) def nonsingular(self, vmin, vmax): if vmin > vmax: (vmin, vmax) = (vmax, vmin) if not np.isfinite(vmin) or not np.isfinite(vmax): (vmin, vmax) = (1, 10) elif vmax <= 0: _api.warn_external('Data has no positive values, and therefore cannot be log-scaled.') (vmin, vmax) = (1, 10) else: minpos = min((axis.get_minpos() for axis in self.axis._get_shared_axis())) if not np.isfinite(minpos): minpos = 1e-300 if vmin <= 0: vmin = minpos if vmin == vmax: vmin = _decade_less(vmin, self._base) vmax = _decade_greater(vmax, self._base) return (vmin, vmax) class SymmetricalLogLocator(Locator): def __init__(self, transform=None, subs=None, linthresh=None, base=None): if transform is not None: self._base = transform.base self._linthresh = transform.linthresh elif linthresh is not None and base is not None: self._base = base self._linthresh = linthresh else: raise ValueError('Either transform, or both linthresh and base, must be provided.') if subs is None: self._subs = [1.0] else: self._subs = subs self.numticks = 15 def set_params(self, subs=None, numticks=None): if numticks is not None: self.numticks = numticks if subs is not None: self._subs = subs def __call__(self): (vmin, vmax) = self.axis.get_view_interval() return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): linthresh = self._linthresh if vmax < vmin: (vmin, vmax) = (vmax, vmin) if -linthresh <= vmin < vmax <= linthresh: return sorted({vmin, 0, vmax}) has_a = vmin < -linthresh has_c = vmax > linthresh has_b = has_a and vmax > -linthresh or (has_c and vmin < linthresh) base = self._base def get_log_range(lo, hi): lo = np.floor(np.log(lo) / np.log(base)) hi = np.ceil(np.log(hi) / np.log(base)) return (lo, hi) (a_lo, a_hi) = (0, 0) if has_a: a_upper_lim = min(-linthresh, vmax) (a_lo, a_hi) = get_log_range(abs(a_upper_lim), abs(vmin) + 1) (c_lo, c_hi) = (0, 0) if has_c: c_lower_lim = max(linthresh, vmin) (c_lo, c_hi) = get_log_range(c_lower_lim, vmax + 1) total_ticks = a_hi - a_lo + (c_hi - c_lo) if has_b: total_ticks += 1 stride = max(total_ticks // (self.numticks - 1), 1) decades = [] if has_a: decades.extend(-1 * base ** np.arange(a_lo, a_hi, stride)[::-1]) if has_b: decades.append(0.0) if has_c: decades.extend(base ** np.arange(c_lo, c_hi, stride)) subs = np.asarray(self._subs) if len(subs) > 1 or subs[0] != 1.0: ticklocs = [] for decade in decades: if decade == 0: ticklocs.append(decade) else: ticklocs.extend(subs * decade) else: ticklocs = decades return self.raise_if_exceeds(np.array(ticklocs)) def view_limits(self, vmin, vmax): b = self._base if vmax < vmin: (vmin, vmax) = (vmax, vmin) if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers': vmin = _decade_less_equal(vmin, b) vmax = _decade_greater_equal(vmax, b) if vmin == vmax: vmin = _decade_less(vmin, b) vmax = _decade_greater(vmax, b) return mtransforms.nonsingular(vmin, vmax) class AsinhLocator(Locator): def __init__(self, linear_width, numticks=11, symthresh=0.2, base=10, subs=None): super().__init__() self.linear_width = linear_width self.numticks = numticks self.symthresh = symthresh self.base = base self.subs = subs def set_params(self, numticks=None, symthresh=None, base=None, subs=None): if numticks is not None: self.numticks = numticks if symthresh is not None: self.symthresh = symthresh if base is not None: self.base = base if subs is not None: self.subs = subs if len(subs) > 0 else None def __call__(self): (vmin, vmax) = self.axis.get_view_interval() if vmin * vmax < 0 and abs(1 + vmax / vmin) < self.symthresh: bound = max(abs(vmin), abs(vmax)) return self.tick_values(-bound, bound) else: return self.tick_values(vmin, vmax) def tick_values(self, vmin, vmax): (ymin, ymax) = self.linear_width * np.arcsinh(np.array([vmin, vmax]) / self.linear_width) ys = np.linspace(ymin, ymax, self.numticks) zero_dev = abs(ys / (ymax - ymin)) if ymin * ymax < 0: ys = np.hstack([ys[zero_dev > 0.5 / self.numticks], 0.0]) xs = self.linear_width * np.sinh(ys / self.linear_width) zero_xs = ys == 0 with np.errstate(divide='ignore'): if self.base > 1: pows = np.sign(xs) * self.base ** np.floor(np.log(abs(xs)) / math.log(self.base)) qs = np.outer(pows, self.subs).flatten() if self.subs else pows else: pows = np.where(zero_xs, 1, 10 ** np.floor(np.log10(abs(xs)))) qs = pows * np.round(xs / pows) ticks = np.array(sorted(set(qs))) return ticks if len(ticks) >= 2 else np.linspace(vmin, vmax, self.numticks) class LogitLocator(MaxNLocator): def __init__(self, minor=False, *, nbins='auto'): self._minor = minor super().__init__(nbins=nbins, steps=[1, 2, 5, 10]) def set_params(self, minor=None, **kwargs): if minor is not None: self._minor = minor super().set_params(**kwargs) @property def minor(self): return self._minor @minor.setter def minor(self, value): self.set_params(minor=value) def tick_values(self, vmin, vmax): if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar': raise NotImplementedError('Polar axis cannot be logit scaled yet') if self._nbins == 'auto': if self.axis is not None: nbins = self.axis.get_tick_space() if nbins < 2: nbins = 2 else: nbins = 9 else: nbins = self._nbins def ideal_ticks(x): return 10 ** x if x < 0 else 1 - 10 ** (-x) if x > 0 else 0.5 (vmin, vmax) = self.nonsingular(vmin, vmax) binf = int(np.floor(np.log10(vmin)) if vmin < 0.5 else 0 if vmin < 0.9 else -np.ceil(np.log10(1 - vmin))) bsup = int(np.ceil(np.log10(vmax)) if vmax <= 0.5 else 1 if vmax <= 0.9 else -np.floor(np.log10(1 - vmax))) numideal = bsup - binf - 1 if numideal >= 2: if numideal > nbins: subsampling_factor = math.ceil(numideal / nbins) if self._minor: ticklocs = [ideal_ticks(b) for b in range(binf, bsup + 1) if b % subsampling_factor != 0] else: ticklocs = [ideal_ticks(b) for b in range(binf, bsup + 1) if b % subsampling_factor == 0] return self.raise_if_exceeds(np.array(ticklocs)) if self._minor: ticklocs = [] for b in range(binf, bsup): if b < -1: ticklocs.extend(np.arange(2, 10) * 10 ** b) elif b == -1: ticklocs.extend(np.arange(2, 5) / 10) elif b == 0: ticklocs.extend(np.arange(6, 9) / 10) else: ticklocs.extend(1 - np.arange(2, 10)[::-1] * 10 ** (-b - 1)) return self.raise_if_exceeds(np.array(ticklocs)) ticklocs = [ideal_ticks(b) for b in range(binf, bsup + 1)] return self.raise_if_exceeds(np.array(ticklocs)) if self._minor: return [] return super().tick_values(vmin, vmax) def nonsingular(self, vmin, vmax): standard_minpos = 1e-07 initial_range = (standard_minpos, 1 - standard_minpos) if vmin > vmax: (vmin, vmax) = (vmax, vmin) if not np.isfinite(vmin) or not np.isfinite(vmax): (vmin, vmax) = initial_range elif vmax <= 0 or vmin >= 1: _api.warn_external('Data has no values between 0 and 1, and therefore cannot be logit-scaled.') (vmin, vmax) = initial_range else: minpos = self.axis.get_minpos() if self.axis is not None else standard_minpos if not np.isfinite(minpos): minpos = standard_minpos if vmin <= 0: vmin = minpos if vmax >= 1: vmax = 1 - minpos if vmin == vmax: (vmin, vmax) = (0.1 * vmin, 1 - 0.1 * vmin) return (vmin, vmax) class AutoLocator(MaxNLocator): def __init__(self): if mpl.rcParams['_internal.classic_mode']: nbins = 9 steps = [1, 2, 5, 10] else: nbins = 'auto' steps = [1, 2, 2.5, 5, 10] super().__init__(nbins=nbins, steps=steps) class AutoMinorLocator(Locator): def __init__(self, n=None): self.ndivs = n def __call__(self): if self.axis.get_scale() == 'log': _api.warn_external('AutoMinorLocator does not work on logarithmic scales') return [] majorlocs = np.unique(self.axis.get_majorticklocs()) if len(majorlocs) < 2: return [] majorstep = majorlocs[1] - majorlocs[0] if self.ndivs is None: self.ndivs = mpl.rcParams['ytick.minor.ndivs' if self.axis.axis_name == 'y' else 'xtick.minor.ndivs'] if self.ndivs == 'auto': majorstep_mantissa = 10 ** (np.log10(majorstep) % 1) ndivs = 5 if np.isclose(majorstep_mantissa, [1, 2.5, 5, 10]).any() else 4 else: ndivs = self.ndivs minorstep = majorstep / ndivs (vmin, vmax) = sorted(self.axis.get_view_interval()) t0 = majorlocs[0] tmin = round((vmin - t0) / minorstep) tmax = round((vmax - t0) / minorstep) + 1 locs = np.arange(tmin, tmax) * minorstep + t0 return self.raise_if_exceeds(locs) def tick_values(self, vmin, vmax): raise NotImplementedError(f'Cannot get tick locations for a {type(self).__name__}') # File: matplotlib-main/lib/matplotlib/transforms.py """""" import copy import functools import itertools import textwrap import weakref import math import numpy as np from numpy.linalg import inv from matplotlib import _api from matplotlib._path import affine_transform, count_bboxes_overlapping_bbox, update_path_extents from .path import Path DEBUG = False def _make_str_method(*args, **kwargs): indent = functools.partial(textwrap.indent, prefix=' ' * 4) def strrepr(x): return repr(x) if isinstance(x, str) else str(x) return lambda self: type(self).__name__ + '(' + ','.join([*(indent('\n' + strrepr(getattr(self, arg))) for arg in args), *(indent('\n' + k + '=' + strrepr(getattr(self, arg))) for (k, arg) in kwargs.items())]) + ')' class TransformNode: INVALID_NON_AFFINE = _api.deprecated('3.8')(_api.classproperty(lambda cls: 1)) INVALID_AFFINE = _api.deprecated('3.8')(_api.classproperty(lambda cls: 2)) INVALID = _api.deprecated('3.8')(_api.classproperty(lambda cls: 3)) (_VALID, _INVALID_AFFINE_ONLY, _INVALID_FULL) = range(3) is_affine = False is_bbox = _api.deprecated('3.9')(_api.classproperty(lambda cls: False)) pass_through = False '' def __init__(self, shorthand_name=None): self._parents = {} self._invalid = self._INVALID_FULL self._shorthand_name = shorthand_name or '' if DEBUG: def __str__(self): return self._shorthand_name or repr(self) def __getstate__(self): return {**self.__dict__, '_parents': {k: v() for (k, v) in self._parents.items()}} def __setstate__(self, data_dict): self.__dict__ = data_dict self._parents = {k: weakref.ref(v, lambda _, pop=self._parents.pop, k=k: pop(k)) for (k, v) in self._parents.items() if v is not None} def __copy__(self): other = copy.copy(super()) other._parents = {} for (key, val) in vars(self).items(): if isinstance(val, TransformNode) and id(self) in val._parents: other.set_children(val) return other def invalidate(self): return self._invalidate_internal(level=self._INVALID_AFFINE_ONLY if self.is_affine else self._INVALID_FULL, invalidating_node=self) def _invalidate_internal(self, level, invalidating_node): if level <= self._invalid and (not self.pass_through): return self._invalid = level for parent in list(self._parents.values()): parent = parent() if parent is not None: parent._invalidate_internal(level=level, invalidating_node=self) def set_children(self, *children): id_self = id(self) for child in children: ref = weakref.ref(self, lambda _, pop=child._parents.pop, k=id_self: pop(k)) child._parents[id_self] = ref def frozen(self): return self class BboxBase(TransformNode): is_bbox = _api.deprecated('3.9')(_api.classproperty(lambda cls: True)) is_affine = True if DEBUG: @staticmethod def _check(points): if isinstance(points, np.ma.MaskedArray): _api.warn_external('Bbox bounds are a masked array.') points = np.asarray(points) if any(points[1, :] - points[0, :] == 0): _api.warn_external('Singular Bbox.') def frozen(self): return Bbox(self.get_points().copy()) frozen.__doc__ = TransformNode.__doc__ def __array__(self, *args, **kwargs): return self.get_points() @property def x0(self): return self.get_points()[0, 0] @property def y0(self): return self.get_points()[0, 1] @property def x1(self): return self.get_points()[1, 0] @property def y1(self): return self.get_points()[1, 1] @property def p0(self): return self.get_points()[0] @property def p1(self): return self.get_points()[1] @property def xmin(self): return np.min(self.get_points()[:, 0]) @property def ymin(self): return np.min(self.get_points()[:, 1]) @property def xmax(self): return np.max(self.get_points()[:, 0]) @property def ymax(self): return np.max(self.get_points()[:, 1]) @property def min(self): return np.min(self.get_points(), axis=0) @property def max(self): return np.max(self.get_points(), axis=0) @property def intervalx(self): return self.get_points()[:, 0] @property def intervaly(self): return self.get_points()[:, 1] @property def width(self): points = self.get_points() return points[1, 0] - points[0, 0] @property def height(self): points = self.get_points() return points[1, 1] - points[0, 1] @property def size(self): points = self.get_points() return points[1] - points[0] @property def bounds(self): ((x0, y0), (x1, y1)) = self.get_points() return (x0, y0, x1 - x0, y1 - y0) @property def extents(self): return self.get_points().flatten() def get_points(self): raise NotImplementedError def containsx(self, x): (x0, x1) = self.intervalx return x0 <= x <= x1 or x0 >= x >= x1 def containsy(self, y): (y0, y1) = self.intervaly return y0 <= y <= y1 or y0 >= y >= y1 def contains(self, x, y): return self.containsx(x) and self.containsy(y) def overlaps(self, other): (ax1, ay1, ax2, ay2) = self.extents (bx1, by1, bx2, by2) = other.extents if ax2 < ax1: (ax2, ax1) = (ax1, ax2) if ay2 < ay1: (ay2, ay1) = (ay1, ay2) if bx2 < bx1: (bx2, bx1) = (bx1, bx2) if by2 < by1: (by2, by1) = (by1, by2) return ax1 <= bx2 and bx1 <= ax2 and (ay1 <= by2) and (by1 <= ay2) def fully_containsx(self, x): (x0, x1) = self.intervalx return x0 < x < x1 or x0 > x > x1 def fully_containsy(self, y): (y0, y1) = self.intervaly return y0 < y < y1 or y0 > y > y1 def fully_contains(self, x, y): return self.fully_containsx(x) and self.fully_containsy(y) def fully_overlaps(self, other): (ax1, ay1, ax2, ay2) = self.extents (bx1, by1, bx2, by2) = other.extents if ax2 < ax1: (ax2, ax1) = (ax1, ax2) if ay2 < ay1: (ay2, ay1) = (ay1, ay2) if bx2 < bx1: (bx2, bx1) = (bx1, bx2) if by2 < by1: (by2, by1) = (by1, by2) return ax1 < bx2 and bx1 < ax2 and (ay1 < by2) and (by1 < ay2) def transformed(self, transform): pts = self.get_points() (ll, ul, lr) = transform.transform(np.array([pts[0], [pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]])) return Bbox([ll, [lr[0], ul[1]]]) coefs = {'C': (0.5, 0.5), 'SW': (0, 0), 'S': (0.5, 0), 'SE': (1.0, 0), 'E': (1.0, 0.5), 'NE': (1.0, 1.0), 'N': (0.5, 1.0), 'NW': (0, 1.0), 'W': (0, 0.5)} def anchored(self, c, container=None): if container is None: _api.warn_deprecated('3.8', message='Calling anchored() with no container bbox returns a frozen copy of the original bbox and is deprecated since %(since)s.') container = self (l, b, w, h) = container.bounds (L, B, W, H) = self.bounds (cx, cy) = self.coefs[c] if isinstance(c, str) else c return Bbox(self._points + [l + cx * (w - W) - L, b + cy * (h - H) - B]) def shrunk(self, mx, my): (w, h) = self.size return Bbox([self._points[0], self._points[0] + [mx * w, my * h]]) def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0): if box_aspect <= 0 or fig_aspect <= 0: raise ValueError("'box_aspect' and 'fig_aspect' must be positive") if container is None: container = self (w, h) = container.size H = w * box_aspect / fig_aspect if H <= h: W = w else: W = h * fig_aspect / box_aspect H = h return Bbox([self._points[0], self._points[0] + (W, H)]) def splitx(self, *args): xf = [0, *args, 1] (x0, y0, x1, y1) = self.extents w = x1 - x0 return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]]) for (xf0, xf1) in itertools.pairwise(xf)] def splity(self, *args): yf = [0, *args, 1] (x0, y0, x1, y1) = self.extents h = y1 - y0 return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]]) for (yf0, yf1) in itertools.pairwise(yf)] def count_contains(self, vertices): if len(vertices) == 0: return 0 vertices = np.asarray(vertices) with np.errstate(invalid='ignore'): return ((self.min < vertices) & (vertices < self.max)).all(axis=1).sum() def count_overlaps(self, bboxes): return count_bboxes_overlapping_bbox(self, np.atleast_3d([np.array(x) for x in bboxes])) def expanded(self, sw, sh): width = self.width height = self.height deltaw = (sw * width - width) / 2.0 deltah = (sh * height - height) / 2.0 a = np.array([[-deltaw, -deltah], [deltaw, deltah]]) return Bbox(self._points + a) def padded(self, w_pad, h_pad=None): points = self.get_points() if h_pad is None: h_pad = w_pad return Bbox(points + [[-w_pad, -h_pad], [w_pad, h_pad]]) def translated(self, tx, ty): return Bbox(self._points + (tx, ty)) def corners(self): ((x0, y0), (x1, y1)) = self.get_points() return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]]) def rotated(self, radians): corners = self.corners() corners_rotated = Affine2D().rotate(radians).transform(corners) bbox = Bbox.unit() bbox.update_from_data_xy(corners_rotated, ignore=True) return bbox @staticmethod def union(bboxes): if not len(bboxes): raise ValueError("'bboxes' cannot be empty") x0 = np.min([bbox.xmin for bbox in bboxes]) x1 = np.max([bbox.xmax for bbox in bboxes]) y0 = np.min([bbox.ymin for bbox in bboxes]) y1 = np.max([bbox.ymax for bbox in bboxes]) return Bbox([[x0, y0], [x1, y1]]) @staticmethod def intersection(bbox1, bbox2): x0 = np.maximum(bbox1.xmin, bbox2.xmin) x1 = np.minimum(bbox1.xmax, bbox2.xmax) y0 = np.maximum(bbox1.ymin, bbox2.ymin) y1 = np.minimum(bbox1.ymax, bbox2.ymax) return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None _default_minpos = np.array([np.inf, np.inf]) class Bbox(BboxBase): def __init__(self, points, **kwargs): super().__init__(**kwargs) points = np.asarray(points, float) if points.shape != (2, 2): raise ValueError('Bbox points must be of the form "[[x0, y0], [x1, y1]]".') self._points = points self._minpos = _default_minpos.copy() self._ignore = True self._points_orig = self._points.copy() if DEBUG: ___init__ = __init__ def __init__(self, points, **kwargs): self._check(points) self.___init__(points, **kwargs) def invalidate(self): self._check(self._points) super().invalidate() def frozen(self): frozen_bbox = super().frozen() frozen_bbox._minpos = self.minpos.copy() return frozen_bbox @staticmethod def unit(): return Bbox([[0, 0], [1, 1]]) @staticmethod def null(): return Bbox([[np.inf, np.inf], [-np.inf, -np.inf]]) @staticmethod def from_bounds(x0, y0, width, height): return Bbox.from_extents(x0, y0, x0 + width, y0 + height) @staticmethod def from_extents(*args, minpos=None): bbox = Bbox(np.reshape(args, (2, 2))) if minpos is not None: bbox._minpos[:] = minpos return bbox def __format__(self, fmt): return 'Bbox(x0={0.x0:{1}}, y0={0.y0:{1}}, x1={0.x1:{1}}, y1={0.y1:{1}})'.format(self, fmt) def __str__(self): return format(self, '') def __repr__(self): return 'Bbox([[{0.x0}, {0.y0}], [{0.x1}, {0.y1}]])'.format(self) def ignore(self, value): self._ignore = value def update_from_path(self, path, ignore=None, updatex=True, updatey=True): if ignore is None: ignore = self._ignore if path.vertices.size == 0: return (points, minpos, changed) = update_path_extents(path, None, self._points, self._minpos, ignore) if changed: self.invalidate() if updatex: self._points[:, 0] = points[:, 0] self._minpos[0] = minpos[0] if updatey: self._points[:, 1] = points[:, 1] self._minpos[1] = minpos[1] def update_from_data_x(self, x, ignore=None): x = np.ravel(x) self.update_from_data_xy(np.column_stack([x, np.ones(x.size)]), ignore=ignore, updatey=False) def update_from_data_y(self, y, ignore=None): y = np.ravel(y) self.update_from_data_xy(np.column_stack([np.ones(y.size), y]), ignore=ignore, updatex=False) def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True): if len(xy) == 0: return path = Path(xy) self.update_from_path(path, ignore=ignore, updatex=updatex, updatey=updatey) @BboxBase.x0.setter def x0(self, val): self._points[0, 0] = val self.invalidate() @BboxBase.y0.setter def y0(self, val): self._points[0, 1] = val self.invalidate() @BboxBase.x1.setter def x1(self, val): self._points[1, 0] = val self.invalidate() @BboxBase.y1.setter def y1(self, val): self._points[1, 1] = val self.invalidate() @BboxBase.p0.setter def p0(self, val): self._points[0] = val self.invalidate() @BboxBase.p1.setter def p1(self, val): self._points[1] = val self.invalidate() @BboxBase.intervalx.setter def intervalx(self, interval): self._points[:, 0] = interval self.invalidate() @BboxBase.intervaly.setter def intervaly(self, interval): self._points[:, 1] = interval self.invalidate() @BboxBase.bounds.setter def bounds(self, bounds): (l, b, w, h) = bounds points = np.array([[l, b], [l + w, b + h]], float) if np.any(self._points != points): self._points = points self.invalidate() @property def minpos(self): return self._minpos @minpos.setter def minpos(self, val): self._minpos[:] = val @property def minposx(self): return self._minpos[0] @minposx.setter def minposx(self, val): self._minpos[0] = val @property def minposy(self): return self._minpos[1] @minposy.setter def minposy(self, val): self._minpos[1] = val def get_points(self): self._invalid = 0 return self._points def set_points(self, points): if np.any(self._points != points): self._points = points self.invalidate() def set(self, other): if np.any(self._points != other.get_points()): self._points = other.get_points() self.invalidate() def mutated(self): return self.mutatedx() or self.mutatedy() def mutatedx(self): return self._points[0, 0] != self._points_orig[0, 0] or self._points[1, 0] != self._points_orig[1, 0] def mutatedy(self): return self._points[0, 1] != self._points_orig[0, 1] or self._points[1, 1] != self._points_orig[1, 1] class TransformedBbox(BboxBase): def __init__(self, bbox, transform, **kwargs): _api.check_isinstance(BboxBase, bbox=bbox) _api.check_isinstance(Transform, transform=transform) if transform.input_dims != 2 or transform.output_dims != 2: raise ValueError("The input and output dimensions of 'transform' must be 2") super().__init__(**kwargs) self._bbox = bbox self._transform = transform self.set_children(bbox, transform) self._points = None __str__ = _make_str_method('_bbox', '_transform') def get_points(self): if self._invalid: p = self._bbox.get_points() points = self._transform.transform([[p[0, 0], p[0, 1]], [p[1, 0], p[0, 1]], [p[0, 0], p[1, 1]], [p[1, 0], p[1, 1]]]) points = np.ma.filled(points, 0.0) xs = (min(points[:, 0]), max(points[:, 0])) if p[0, 0] > p[1, 0]: xs = xs[::-1] ys = (min(points[:, 1]), max(points[:, 1])) if p[0, 1] > p[1, 1]: ys = ys[::-1] self._points = np.array([[xs[0], ys[0]], [xs[1], ys[1]]]) self._invalid = 0 return self._points if DEBUG: _get_points = get_points def get_points(self): points = self._get_points() self._check(points) return points def contains(self, x, y): return self._bbox.contains(*self._transform.inverted().transform((x, y))) def fully_contains(self, x, y): return self._bbox.fully_contains(*self._transform.inverted().transform((x, y))) class LockableBbox(BboxBase): def __init__(self, bbox, x0=None, y0=None, x1=None, y1=None, **kwargs): _api.check_isinstance(BboxBase, bbox=bbox) super().__init__(**kwargs) self._bbox = bbox self.set_children(bbox) self._points = None fp = [x0, y0, x1, y1] mask = [val is None for val in fp] self._locked_points = np.ma.array(fp, float, mask=mask).reshape((2, 2)) __str__ = _make_str_method('_bbox', '_locked_points') def get_points(self): if self._invalid: points = self._bbox.get_points() self._points = np.where(self._locked_points.mask, points, self._locked_points) self._invalid = 0 return self._points if DEBUG: _get_points = get_points def get_points(self): points = self._get_points() self._check(points) return points @property def locked_x0(self): if self._locked_points.mask[0, 0]: return None else: return self._locked_points[0, 0] @locked_x0.setter def locked_x0(self, x0): self._locked_points.mask[0, 0] = x0 is None self._locked_points.data[0, 0] = x0 self.invalidate() @property def locked_y0(self): if self._locked_points.mask[0, 1]: return None else: return self._locked_points[0, 1] @locked_y0.setter def locked_y0(self, y0): self._locked_points.mask[0, 1] = y0 is None self._locked_points.data[0, 1] = y0 self.invalidate() @property def locked_x1(self): if self._locked_points.mask[1, 0]: return None else: return self._locked_points[1, 0] @locked_x1.setter def locked_x1(self, x1): self._locked_points.mask[1, 0] = x1 is None self._locked_points.data[1, 0] = x1 self.invalidate() @property def locked_y1(self): if self._locked_points.mask[1, 1]: return None else: return self._locked_points[1, 1] @locked_y1.setter def locked_y1(self, y1): self._locked_points.mask[1, 1] = y1 is None self._locked_points.data[1, 1] = y1 self.invalidate() class Transform(TransformNode): input_dims = None '' output_dims = None '' is_separable = False '' has_inverse = False '' def __init_subclass__(cls): if sum(('is_separable' in vars(parent) for parent in cls.__mro__)) == 1 and cls.input_dims == cls.output_dims == 1: cls.is_separable = True if sum(('has_inverse' in vars(parent) for parent in cls.__mro__)) == 1 and hasattr(cls, 'inverted') and (cls.inverted is not Transform.inverted): cls.has_inverse = True def __add__(self, other): return composite_transform_factory(self, other) if isinstance(other, Transform) else NotImplemented def _iter_break_from_left_to_right(self): yield (IdentityTransform(), self) @property def depth(self): return 1 def contains_branch(self, other): if self.depth < other.depth: return False for (_, sub_tree) in self._iter_break_from_left_to_right(): if sub_tree == other: return True return False def contains_branch_seperately(self, other_transform): if self.output_dims != 2: raise ValueError('contains_branch_seperately only supports transforms with 2 output dimensions') return (self.contains_branch(other_transform),) * 2 def __sub__(self, other): if not isinstance(other, Transform): return NotImplemented for (remainder, sub_tree) in self._iter_break_from_left_to_right(): if sub_tree == other: return remainder for (remainder, sub_tree) in other._iter_break_from_left_to_right(): if sub_tree == self: if not remainder.has_inverse: raise ValueError("The shortcut cannot be computed since 'other' includes a non-invertible component") return remainder.inverted() if other.has_inverse: return self + other.inverted() else: raise ValueError('It is not possible to compute transA - transB since transB cannot be inverted and there is no shortcut possible.') def __array__(self, *args, **kwargs): return self.get_affine().get_matrix() def transform(self, values): values = np.asanyarray(values) ndim = values.ndim values = values.reshape((-1, self.input_dims)) res = self.transform_affine(self.transform_non_affine(values)) if ndim == 0: assert not np.ma.is_masked(res) return res[0, 0] if ndim == 1: return res.reshape(-1) elif ndim == 2: return res raise ValueError('Input values must have shape (N, {dims}) or ({dims},)'.format(dims=self.input_dims)) def transform_affine(self, values): return self.get_affine().transform(values) def transform_non_affine(self, values): return values def transform_bbox(self, bbox): return Bbox(self.transform(bbox.get_points())) def get_affine(self): return IdentityTransform() def get_matrix(self): return self.get_affine().get_matrix() def transform_point(self, point): if len(point) != self.input_dims: raise ValueError("The length of 'point' must be 'self.input_dims'") return self.transform(point) def transform_path(self, path): return self.transform_path_affine(self.transform_path_non_affine(path)) def transform_path_affine(self, path): return self.get_affine().transform_path_affine(path) def transform_path_non_affine(self, path): x = self.transform_non_affine(path.vertices) return Path._fast_from_codes_and_verts(x, path.codes, path) def transform_angles(self, angles, pts, radians=False, pushoff=1e-05): if self.input_dims != 2 or self.output_dims != 2: raise NotImplementedError('Only defined in 2D') angles = np.asarray(angles) pts = np.asarray(pts) _api.check_shape((None, 2), pts=pts) _api.check_shape((None,), angles=angles) if len(angles) != len(pts): raise ValueError("There must be as many 'angles' as 'pts'") if not radians: angles = np.deg2rad(angles) pts2 = pts + pushoff * np.column_stack([np.cos(angles), np.sin(angles)]) tpts = self.transform(pts) tpts2 = self.transform(pts2) d = tpts2 - tpts a = np.arctan2(d[:, 1], d[:, 0]) if not radians: a = np.rad2deg(a) return a def inverted(self): raise NotImplementedError() class TransformWrapper(Transform): pass_through = True def __init__(self, child): _api.check_isinstance(Transform, child=child) super().__init__() self.set(child) def __eq__(self, other): return self._child.__eq__(other) __str__ = _make_str_method('_child') def frozen(self): return self._child.frozen() def set(self, child): if hasattr(self, '_child'): self.invalidate() new_dims = (child.input_dims, child.output_dims) old_dims = (self._child.input_dims, self._child.output_dims) if new_dims != old_dims: raise ValueError(f'The input and output dims of the new child {new_dims} do not match those of current child {old_dims}') self._child._parents.pop(id(self), None) self._child = child self.set_children(child) self.transform = child.transform self.transform_affine = child.transform_affine self.transform_non_affine = child.transform_non_affine self.transform_path = child.transform_path self.transform_path_affine = child.transform_path_affine self.transform_path_non_affine = child.transform_path_non_affine self.get_affine = child.get_affine self.inverted = child.inverted self.get_matrix = child.get_matrix self._invalid = 0 self.invalidate() self._invalid = 0 input_dims = property(lambda self: self._child.input_dims) output_dims = property(lambda self: self._child.output_dims) is_affine = property(lambda self: self._child.is_affine) is_separable = property(lambda self: self._child.is_separable) has_inverse = property(lambda self: self._child.has_inverse) class AffineBase(Transform): is_affine = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._inverted = None def __array__(self, *args, **kwargs): return self.get_matrix() def __eq__(self, other): if getattr(other, 'is_affine', False) and hasattr(other, 'get_matrix'): return (self.get_matrix() == other.get_matrix()).all() return NotImplemented def transform(self, values): return self.transform_affine(values) def transform_affine(self, values): raise NotImplementedError('Affine subclasses should override this method.') def transform_non_affine(self, values): return values def transform_path(self, path): return self.transform_path_affine(path) def transform_path_affine(self, path): return Path(self.transform_affine(path.vertices), path.codes, path._interpolation_steps) def transform_path_non_affine(self, path): return path def get_affine(self): return self class Affine2DBase(AffineBase): input_dims = 2 output_dims = 2 def frozen(self): return Affine2D(self.get_matrix().copy()) @property def is_separable(self): mtx = self.get_matrix() return mtx[0, 1] == mtx[1, 0] == 0.0 def to_values(self): mtx = self.get_matrix() return tuple(mtx[:2].swapaxes(0, 1).flat) def transform_affine(self, values): mtx = self.get_matrix() if isinstance(values, np.ma.MaskedArray): tpoints = affine_transform(values.data, mtx) return np.ma.MaskedArray(tpoints, mask=np.ma.getmask(values)) return affine_transform(values, mtx) if DEBUG: _transform_affine = transform_affine def transform_affine(self, values): if not isinstance(values, np.ndarray): _api.warn_external(f'A non-numpy array of type {type(values)} was passed in for transformation, which results in poor performance.') return self._transform_affine(values) def inverted(self): if self._inverted is None or self._invalid: mtx = self.get_matrix() shorthand_name = None if self._shorthand_name: shorthand_name = '(%s)-1' % self._shorthand_name self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name) self._invalid = 0 return self._inverted class Affine2D(Affine2DBase): def __init__(self, matrix=None, **kwargs): super().__init__(**kwargs) if matrix is None: matrix = IdentityTransform._mtx self._mtx = matrix.copy() self._invalid = 0 _base_str = _make_str_method('_mtx') def __str__(self): return self._base_str() if (self._mtx != np.diag(np.diag(self._mtx))).any() else f'Affine2D().scale({self._mtx[0, 0]}, {self._mtx[1, 1]})' if self._mtx[0, 0] != self._mtx[1, 1] else f'Affine2D().scale({self._mtx[0, 0]})' @staticmethod def from_values(a, b, c, d, e, f): return Affine2D(np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3))) def get_matrix(self): if self._invalid: self._inverted = None self._invalid = 0 return self._mtx def set_matrix(self, mtx): self._mtx = mtx self.invalidate() def set(self, other): _api.check_isinstance(Affine2DBase, other=other) self._mtx = other.get_matrix() self.invalidate() def clear(self): self._mtx = IdentityTransform._mtx.copy() self.invalidate() return self def rotate(self, theta): a = math.cos(theta) b = math.sin(theta) mtx = self._mtx ((xx, xy, x0), (yx, yy, y0), _) = mtx.tolist() mtx[0, 0] = a * xx - b * yx mtx[0, 1] = a * xy - b * yy mtx[0, 2] = a * x0 - b * y0 mtx[1, 0] = b * xx + a * yx mtx[1, 1] = b * xy + a * yy mtx[1, 2] = b * x0 + a * y0 self.invalidate() return self def rotate_deg(self, degrees): return self.rotate(math.radians(degrees)) def rotate_around(self, x, y, theta): return self.translate(-x, -y).rotate(theta).translate(x, y) def rotate_deg_around(self, x, y, degrees): (x, y) = (float(x), float(y)) return self.translate(-x, -y).rotate_deg(degrees).translate(x, y) def translate(self, tx, ty): self._mtx[0, 2] += tx self._mtx[1, 2] += ty self.invalidate() return self def scale(self, sx, sy=None): if sy is None: sy = sx self._mtx[0, 0] *= sx self._mtx[0, 1] *= sx self._mtx[0, 2] *= sx self._mtx[1, 0] *= sy self._mtx[1, 1] *= sy self._mtx[1, 2] *= sy self.invalidate() return self def skew(self, xShear, yShear): rx = math.tan(xShear) ry = math.tan(yShear) mtx = self._mtx ((xx, xy, x0), (yx, yy, y0), _) = mtx.tolist() mtx[0, 0] += rx * yx mtx[0, 1] += rx * yy mtx[0, 2] += rx * y0 mtx[1, 0] += ry * xx mtx[1, 1] += ry * xy mtx[1, 2] += ry * x0 self.invalidate() return self def skew_deg(self, xShear, yShear): return self.skew(math.radians(xShear), math.radians(yShear)) class IdentityTransform(Affine2DBase): _mtx = np.identity(3) def frozen(self): return self __str__ = _make_str_method() def get_matrix(self): return self._mtx def transform(self, values): return np.asanyarray(values) def transform_affine(self, values): return np.asanyarray(values) def transform_non_affine(self, values): return np.asanyarray(values) def transform_path(self, path): return path def transform_path_affine(self, path): return path def transform_path_non_affine(self, path): return path def get_affine(self): return self def inverted(self): return self class _BlendedMixin: def __eq__(self, other): if isinstance(other, (BlendedAffine2D, BlendedGenericTransform)): return self._x == other._x and self._y == other._y elif self._x == self._y: return self._x == other else: return NotImplemented def contains_branch_seperately(self, transform): return (self._x.contains_branch(transform), self._y.contains_branch(transform)) __str__ = _make_str_method('_x', '_y') class BlendedGenericTransform(_BlendedMixin, Transform): input_dims = 2 output_dims = 2 is_separable = True pass_through = True def __init__(self, x_transform, y_transform, **kwargs): Transform.__init__(self, **kwargs) self._x = x_transform self._y = y_transform self.set_children(x_transform, y_transform) self._affine = None @property def depth(self): return max(self._x.depth, self._y.depth) def contains_branch(self, other): return False is_affine = property(lambda self: self._x.is_affine and self._y.is_affine) has_inverse = property(lambda self: self._x.has_inverse and self._y.has_inverse) def frozen(self): return blended_transform_factory(self._x.frozen(), self._y.frozen()) def transform_non_affine(self, values): if self._x.is_affine and self._y.is_affine: return values x = self._x y = self._y if x == y and x.input_dims == 2: return x.transform_non_affine(values) if x.input_dims == 2: x_points = x.transform_non_affine(values)[:, 0:1] else: x_points = x.transform_non_affine(values[:, 0]) x_points = x_points.reshape((len(x_points), 1)) if y.input_dims == 2: y_points = y.transform_non_affine(values)[:, 1:] else: y_points = y.transform_non_affine(values[:, 1]) y_points = y_points.reshape((len(y_points), 1)) if isinstance(x_points, np.ma.MaskedArray) or isinstance(y_points, np.ma.MaskedArray): return np.ma.concatenate((x_points, y_points), 1) else: return np.concatenate((x_points, y_points), 1) def inverted(self): return BlendedGenericTransform(self._x.inverted(), self._y.inverted()) def get_affine(self): if self._invalid or self._affine is None: if self._x == self._y: self._affine = self._x.get_affine() else: x_mtx = self._x.get_affine().get_matrix() y_mtx = self._y.get_affine().get_matrix() mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]]) self._affine = Affine2D(mtx) self._invalid = 0 return self._affine class BlendedAffine2D(_BlendedMixin, Affine2DBase): is_separable = True def __init__(self, x_transform, y_transform, **kwargs): is_affine = x_transform.is_affine and y_transform.is_affine is_separable = x_transform.is_separable and y_transform.is_separable is_correct = is_affine and is_separable if not is_correct: raise ValueError('Both *x_transform* and *y_transform* must be 2D affine transforms') Transform.__init__(self, **kwargs) self._x = x_transform self._y = y_transform self.set_children(x_transform, y_transform) Affine2DBase.__init__(self) self._mtx = None def get_matrix(self): if self._invalid: if self._x == self._y: self._mtx = self._x.get_matrix() else: x_mtx = self._x.get_matrix() y_mtx = self._y.get_matrix() self._mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]]) self._inverted = None self._invalid = 0 return self._mtx def blended_transform_factory(x_transform, y_transform): if isinstance(x_transform, Affine2DBase) and isinstance(y_transform, Affine2DBase): return BlendedAffine2D(x_transform, y_transform) return BlendedGenericTransform(x_transform, y_transform) class CompositeGenericTransform(Transform): pass_through = True def __init__(self, a, b, **kwargs): if a.output_dims != b.input_dims: raise ValueError("The output dimension of 'a' must be equal to the input dimensions of 'b'") self.input_dims = a.input_dims self.output_dims = b.output_dims super().__init__(**kwargs) self._a = a self._b = b self.set_children(a, b) def frozen(self): self._invalid = 0 frozen = composite_transform_factory(self._a.frozen(), self._b.frozen()) if not isinstance(frozen, CompositeGenericTransform): return frozen.frozen() return frozen def _invalidate_internal(self, level, invalidating_node): if invalidating_node is self._a and (not self._b.is_affine): level = Transform._INVALID_FULL super()._invalidate_internal(level, invalidating_node) def __eq__(self, other): if isinstance(other, (CompositeGenericTransform, CompositeAffine2D)): return self is other or (self._a == other._a and self._b == other._b) else: return False def _iter_break_from_left_to_right(self): for (left, right) in self._a._iter_break_from_left_to_right(): yield (left, right + self._b) for (left, right) in self._b._iter_break_from_left_to_right(): yield (self._a + left, right) def contains_branch_seperately(self, other_transform): if self.output_dims != 2: raise ValueError('contains_branch_seperately only supports transforms with 2 output dimensions') if self == other_transform: return (True, True) return self._b.contains_branch_seperately(other_transform) depth = property(lambda self: self._a.depth + self._b.depth) is_affine = property(lambda self: self._a.is_affine and self._b.is_affine) is_separable = property(lambda self: self._a.is_separable and self._b.is_separable) has_inverse = property(lambda self: self._a.has_inverse and self._b.has_inverse) __str__ = _make_str_method('_a', '_b') def transform_affine(self, values): return self.get_affine().transform(values) def transform_non_affine(self, values): if self._a.is_affine and self._b.is_affine: return values elif not self._a.is_affine and self._b.is_affine: return self._a.transform_non_affine(values) else: return self._b.transform_non_affine(self._a.transform(values)) def transform_path_non_affine(self, path): if self._a.is_affine and self._b.is_affine: return path elif not self._a.is_affine and self._b.is_affine: return self._a.transform_path_non_affine(path) else: return self._b.transform_path_non_affine(self._a.transform_path(path)) def get_affine(self): if not self._b.is_affine: return self._b.get_affine() else: return Affine2D(np.dot(self._b.get_affine().get_matrix(), self._a.get_affine().get_matrix())) def inverted(self): return CompositeGenericTransform(self._b.inverted(), self._a.inverted()) class CompositeAffine2D(Affine2DBase): def __init__(self, a, b, **kwargs): if not a.is_affine or not b.is_affine: raise ValueError("'a' and 'b' must be affine transforms") if a.output_dims != b.input_dims: raise ValueError("The output dimension of 'a' must be equal to the input dimensions of 'b'") self.input_dims = a.input_dims self.output_dims = b.output_dims super().__init__(**kwargs) self._a = a self._b = b self.set_children(a, b) self._mtx = None @property def depth(self): return self._a.depth + self._b.depth def _iter_break_from_left_to_right(self): for (left, right) in self._a._iter_break_from_left_to_right(): yield (left, right + self._b) for (left, right) in self._b._iter_break_from_left_to_right(): yield (self._a + left, right) __str__ = _make_str_method('_a', '_b') def get_matrix(self): if self._invalid: self._mtx = np.dot(self._b.get_matrix(), self._a.get_matrix()) self._inverted = None self._invalid = 0 return self._mtx def composite_transform_factory(a, b): if isinstance(a, IdentityTransform): return b elif isinstance(b, IdentityTransform): return a elif isinstance(a, Affine2D) and isinstance(b, Affine2D): return CompositeAffine2D(a, b) return CompositeGenericTransform(a, b) class BboxTransform(Affine2DBase): is_separable = True def __init__(self, boxin, boxout, **kwargs): _api.check_isinstance(BboxBase, boxin=boxin, boxout=boxout) super().__init__(**kwargs) self._boxin = boxin self._boxout = boxout self.set_children(boxin, boxout) self._mtx = None self._inverted = None __str__ = _make_str_method('_boxin', '_boxout') def get_matrix(self): if self._invalid: (inl, inb, inw, inh) = self._boxin.bounds (outl, outb, outw, outh) = self._boxout.bounds x_scale = outw / inw y_scale = outh / inh if DEBUG and (x_scale == 0 or y_scale == 0): raise ValueError('Transforming from or to a singular bounding box') self._mtx = np.array([[x_scale, 0.0, -inl * x_scale + outl], [0.0, y_scale, -inb * y_scale + outb], [0.0, 0.0, 1.0]], float) self._inverted = None self._invalid = 0 return self._mtx class BboxTransformTo(Affine2DBase): is_separable = True def __init__(self, boxout, **kwargs): _api.check_isinstance(BboxBase, boxout=boxout) super().__init__(**kwargs) self._boxout = boxout self.set_children(boxout) self._mtx = None self._inverted = None __str__ = _make_str_method('_boxout') def get_matrix(self): if self._invalid: (outl, outb, outw, outh) = self._boxout.bounds if DEBUG and (outw == 0 or outh == 0): raise ValueError('Transforming to a singular bounding box.') self._mtx = np.array([[outw, 0.0, outl], [0.0, outh, outb], [0.0, 0.0, 1.0]], float) self._inverted = None self._invalid = 0 return self._mtx @_api.deprecated('3.9') class BboxTransformToMaxOnly(BboxTransformTo): def get_matrix(self): if self._invalid: (xmax, ymax) = self._boxout.max if DEBUG and (xmax == 0 or ymax == 0): raise ValueError('Transforming to a singular bounding box.') self._mtx = np.array([[xmax, 0.0, 0.0], [0.0, ymax, 0.0], [0.0, 0.0, 1.0]], float) self._inverted = None self._invalid = 0 return self._mtx class BboxTransformFrom(Affine2DBase): is_separable = True def __init__(self, boxin, **kwargs): _api.check_isinstance(BboxBase, boxin=boxin) super().__init__(**kwargs) self._boxin = boxin self.set_children(boxin) self._mtx = None self._inverted = None __str__ = _make_str_method('_boxin') def get_matrix(self): if self._invalid: (inl, inb, inw, inh) = self._boxin.bounds if DEBUG and (inw == 0 or inh == 0): raise ValueError('Transforming from a singular bounding box.') x_scale = 1.0 / inw y_scale = 1.0 / inh self._mtx = np.array([[x_scale, 0.0, -inl * x_scale], [0.0, y_scale, -inb * y_scale], [0.0, 0.0, 1.0]], float) self._inverted = None self._invalid = 0 return self._mtx class ScaledTranslation(Affine2DBase): def __init__(self, xt, yt, scale_trans, **kwargs): super().__init__(**kwargs) self._t = (xt, yt) self._scale_trans = scale_trans self.set_children(scale_trans) self._mtx = None self._inverted = None __str__ = _make_str_method('_t') def get_matrix(self): if self._invalid: self._mtx = IdentityTransform._mtx.copy() self._mtx[:2, 2] = self._scale_trans.transform(self._t) self._invalid = 0 self._inverted = None return self._mtx class AffineDeltaTransform(Affine2DBase): pass_through = True def __init__(self, transform, **kwargs): super().__init__(**kwargs) self._base_transform = transform self.set_children(transform) __str__ = _make_str_method('_base_transform') def get_matrix(self): if self._invalid: self._mtx = self._base_transform.get_matrix().copy() self._mtx[:2, -1] = 0 return self._mtx class TransformedPath(TransformNode): def __init__(self, path, transform): _api.check_isinstance(Transform, transform=transform) super().__init__() self._path = path self._transform = transform self.set_children(transform) self._transformed_path = None self._transformed_points = None def _revalidate(self): if self._invalid == self._INVALID_FULL or self._transformed_path is None: self._transformed_path = self._transform.transform_path_non_affine(self._path) self._transformed_points = Path._fast_from_codes_and_verts(self._transform.transform_non_affine(self._path.vertices), None, self._path) self._invalid = 0 def get_transformed_points_and_affine(self): self._revalidate() return (self._transformed_points, self.get_affine()) def get_transformed_path_and_affine(self): self._revalidate() return (self._transformed_path, self.get_affine()) def get_fully_transformed_path(self): self._revalidate() return self._transform.transform_path_affine(self._transformed_path) def get_affine(self): return self._transform.get_affine() class TransformedPatchPath(TransformedPath): def __init__(self, patch): super().__init__(patch.get_path(), patch.get_transform()) self._patch = patch def _revalidate(self): patch_path = self._patch.get_path() if patch_path != self._path: self._path = patch_path self._transformed_path = None super()._revalidate() def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): if not np.isfinite(vmin) or not np.isfinite(vmax): return (-expander, expander) swapped = False if vmax < vmin: (vmin, vmax) = (vmax, vmin) swapped = True (vmin, vmax) = map(float, [vmin, vmax]) maxabsvalue = max(abs(vmin), abs(vmax)) if maxabsvalue < 1000000.0 / tiny * np.finfo(float).tiny: vmin = -expander vmax = expander elif vmax - vmin <= maxabsvalue * tiny: if vmax == 0 and vmin == 0: vmin = -expander vmax = expander else: vmin -= expander * abs(vmin) vmax += expander * abs(vmax) if swapped and (not increasing): (vmin, vmax) = (vmax, vmin) return (vmin, vmax) def interval_contains(interval, val): (a, b) = interval if a > b: (a, b) = (b, a) return a <= val <= b def _interval_contains_close(interval, val, rtol=1e-10): (a, b) = interval if a > b: (a, b) = (b, a) rtol = (b - a) * rtol return a - rtol <= val <= b + rtol def interval_contains_open(interval, val): (a, b) = interval return a < val < b or a > val > b def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'): _api.check_in_list(['dots', 'points', 'inches'], units=units) if units == 'dots': return trans + Affine2D().translate(x, y) if fig is None: raise ValueError('For units of inches or points a fig kwarg is needed') if units == 'points': x /= 72.0 y /= 72.0 return trans + ScaledTranslation(x, y, fig.dpi_scale_trans) # File: matplotlib-main/lib/matplotlib/tri/__init__.py """""" from ._triangulation import Triangulation from ._tricontour import TriContourSet, tricontour, tricontourf from ._trifinder import TriFinder, TrapezoidMapTriFinder from ._triinterpolate import TriInterpolator, LinearTriInterpolator, CubicTriInterpolator from ._tripcolor import tripcolor from ._triplot import triplot from ._trirefine import TriRefiner, UniformTriRefiner from ._tritools import TriAnalyzer __all__ = ['Triangulation', 'TriContourSet', 'tricontour', 'tricontourf', 'TriFinder', 'TrapezoidMapTriFinder', 'TriInterpolator', 'LinearTriInterpolator', 'CubicTriInterpolator', 'tripcolor', 'triplot', 'TriRefiner', 'UniformTriRefiner', 'TriAnalyzer'] # File: matplotlib-main/lib/matplotlib/tri/_triangulation.py import sys import numpy as np from matplotlib import _api class Triangulation: def __init__(self, x, y, triangles=None, mask=None): from matplotlib import _qhull self.x = np.asarray(x, dtype=np.float64) self.y = np.asarray(y, dtype=np.float64) if self.x.shape != self.y.shape or self.x.ndim != 1: raise ValueError(f'x and y must be equal-length 1D arrays, but found shapes {self.x.shape!r} and {self.y.shape!r}') self.mask = None self._edges = None self._neighbors = None self.is_delaunay = False if triangles is None: (self.triangles, self._neighbors) = _qhull.delaunay(x, y, sys.flags.verbose) self.is_delaunay = True else: try: self.triangles = np.array(triangles, dtype=np.int32, order='C') except ValueError as e: raise ValueError(f'triangles must be a (N, 3) int array, not {triangles!r}') from e if self.triangles.ndim != 2 or self.triangles.shape[1] != 3: raise ValueError(f'triangles must be a (N, 3) int array, but found shape {self.triangles.shape!r}') if self.triangles.max() >= len(self.x): raise ValueError(f'triangles are indices into the points and must be in the range 0 <= i < {len(self.x)} but found value {self.triangles.max()}') if self.triangles.min() < 0: raise ValueError(f'triangles are indices into the points and must be in the range 0 <= i < {len(self.x)} but found value {self.triangles.min()}') self._cpp_triangulation = None self._trifinder = None self.set_mask(mask) def calculate_plane_coefficients(self, z): return self.get_cpp_triangulation().calculate_plane_coefficients(z) @property def edges(self): if self._edges is None: self._edges = self.get_cpp_triangulation().get_edges() return self._edges def get_cpp_triangulation(self): from matplotlib import _tri if self._cpp_triangulation is None: self._cpp_triangulation = _tri.Triangulation(self.x, self.y, self.triangles, self.mask if self.mask is not None else (), self._edges if self._edges is not None else (), self._neighbors if self._neighbors is not None else (), not self.is_delaunay) return self._cpp_triangulation def get_masked_triangles(self): if self.mask is not None: return self.triangles[~self.mask] else: return self.triangles @staticmethod def get_from_args_and_kwargs(*args, **kwargs): if isinstance(args[0], Triangulation): (triangulation, *args) = args if 'triangles' in kwargs: _api.warn_external("Passing the keyword 'triangles' has no effect when also passing a Triangulation") if 'mask' in kwargs: _api.warn_external("Passing the keyword 'mask' has no effect when also passing a Triangulation") else: (x, y, triangles, mask, args, kwargs) = Triangulation._extract_triangulation_params(args, kwargs) triangulation = Triangulation(x, y, triangles, mask) return (triangulation, args, kwargs) @staticmethod def _extract_triangulation_params(args, kwargs): (x, y, *args) = args triangles = kwargs.pop('triangles', None) from_args = False if triangles is None and args: triangles = args[0] from_args = True if triangles is not None: try: triangles = np.asarray(triangles, dtype=np.int32) except ValueError: triangles = None if triangles is not None and (triangles.ndim != 2 or triangles.shape[1] != 3): triangles = None if triangles is not None and from_args: args = args[1:] mask = kwargs.pop('mask', None) return (x, y, triangles, mask, args, kwargs) def get_trifinder(self): if self._trifinder is None: from matplotlib.tri._trifinder import TrapezoidMapTriFinder self._trifinder = TrapezoidMapTriFinder(self) return self._trifinder @property def neighbors(self): if self._neighbors is None: self._neighbors = self.get_cpp_triangulation().get_neighbors() return self._neighbors def set_mask(self, mask): if mask is None: self.mask = None else: self.mask = np.asarray(mask, dtype=bool) if self.mask.shape != (self.triangles.shape[0],): raise ValueError('mask array must have same length as triangles array') if self._cpp_triangulation is not None: self._cpp_triangulation.set_mask(self.mask if self.mask is not None else ()) self._edges = None self._neighbors = None if self._trifinder is not None: self._trifinder._initialize() # File: matplotlib-main/lib/matplotlib/tri/_tricontour.py import numpy as np from matplotlib import _docstring from matplotlib.contour import ContourSet from matplotlib.tri._triangulation import Triangulation @_docstring.dedent_interpd class TriContourSet(ContourSet): def __init__(self, ax, *args, **kwargs): super().__init__(ax, *args, **kwargs) def _process_args(self, *args, **kwargs): if isinstance(args[0], TriContourSet): C = args[0]._contour_generator if self.levels is None: self.levels = args[0].levels self.zmin = args[0].zmin self.zmax = args[0].zmax self._mins = args[0]._mins self._maxs = args[0]._maxs else: from matplotlib import _tri (tri, z) = self._contour_args(args, kwargs) C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z) self._mins = [tri.x.min(), tri.y.min()] self._maxs = [tri.x.max(), tri.y.max()] self._contour_generator = C return kwargs def _contour_args(self, args, kwargs): (tri, args, kwargs) = Triangulation.get_from_args_and_kwargs(*args, **kwargs) (z, *args) = args z = np.ma.asarray(z) if z.shape != tri.x.shape: raise ValueError('z array must have same length as triangulation x and y arrays') z_check = z[np.unique(tri.get_masked_triangles())] if np.ma.is_masked(z_check): raise ValueError('z must not contain masked points within the triangulation') if not np.isfinite(z_check).all(): raise ValueError('z array must not contain non-finite values within the triangulation') z = np.ma.masked_invalid(z, copy=False) self.zmax = float(z_check.max()) self.zmin = float(z_check.min()) if self.logscale and self.zmin <= 0: func = 'contourf' if self.filled else 'contour' raise ValueError(f'Cannot {func} log of negative values.') self._process_contour_level_args(args, z.dtype) return (tri, z) _docstring.interpd.update(_tricontour_doc='\nDraw contour %%(type)s on an unstructured triangular grid.\n\nCall signatures::\n\n %%(func)s(triangulation, z, [levels], ...)\n %%(func)s(x, y, z, [levels], *, [triangles=triangles], [mask=mask], ...)\n\nThe triangular grid can be specified either by passing a `.Triangulation`\nobject as the first parameter, or by passing the points *x*, *y* and\noptionally the *triangles* and a *mask*. See `.Triangulation` for an\nexplanation of these parameters. If neither of *triangulation* or\n*triangles* are given, the triangulation is calculated on the fly.\n\nIt is possible to pass *triangles* positionally, i.e.\n``%%(func)s(x, y, triangles, z, ...)``. However, this is discouraged. For more\nclarity, pass *triangles* via keyword argument.\n\nParameters\n----------\ntriangulation : `.Triangulation`, optional\n An already created triangular grid.\n\nx, y, triangles, mask\n Parameters defining the triangular grid. See `.Triangulation`.\n This is mutually exclusive with specifying *triangulation*.\n\nz : array-like\n The height values over which the contour is drawn. Color-mapping is\n controlled by *cmap*, *norm*, *vmin*, and *vmax*.\n\n .. note::\n All values in *z* must be finite. Hence, nan and inf values must\n either be removed or `~.Triangulation.set_mask` be used.\n\nlevels : int or array-like, optional\n Determines the number and positions of the contour lines / regions.\n\n If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries to\n automatically choose no more than *n+1* "nice" contour levels between\n between minimum and maximum numeric values of *Z*.\n\n If array-like, draw contour lines at the specified levels. The values must\n be in increasing order.\n\nReturns\n-------\n`~matplotlib.tri.TriContourSet`\n\nOther Parameters\n----------------\ncolors : :mpltype:`color` or list of :mpltype:`color`, optional\n The colors of the levels, i.e., the contour %%(type)s.\n\n The sequence is cycled for the levels in ascending order. If the sequence\n is shorter than the number of levels, it is repeated.\n\n As a shortcut, single color strings may be used in place of one-element\n lists, i.e. ``\'red\'`` instead of ``[\'red\']`` to color all levels with the\n same color. This shortcut does only work for color strings, not for other\n ways of specifying colors.\n\n By default (value *None*), the colormap specified by *cmap* will be used.\n\nalpha : float, default: 1\n The alpha blending value, between 0 (transparent) and 1 (opaque).\n\n%(cmap_doc)s\n\n This parameter is ignored if *colors* is set.\n\n%(norm_doc)s\n\n This parameter is ignored if *colors* is set.\n\n%(vmin_vmax_doc)s\n\n If *vmin* or *vmax* are not given, the default color scaling is based on\n *levels*.\n\n This parameter is ignored if *colors* is set.\n\norigin : {*None*, \'upper\', \'lower\', \'image\'}, default: None\n Determines the orientation and exact position of *z* by specifying the\n position of ``z[0, 0]``. This is only relevant, if *X*, *Y* are not given.\n\n - *None*: ``z[0, 0]`` is at X=0, Y=0 in the lower left corner.\n - \'lower\': ``z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.\n - \'upper\': ``z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left corner.\n - \'image\': Use the value from :rc:`image.origin`.\n\nextent : (x0, x1, y0, y1), optional\n If *origin* is not *None*, then *extent* is interpreted as in `.imshow`: it\n gives the outer pixel boundaries. In this case, the position of z[0, 0] is\n the center of the pixel, not a corner. If *origin* is *None*, then\n (*x0*, *y0*) is the position of z[0, 0], and (*x1*, *y1*) is the position\n of z[-1, -1].\n\n This argument is ignored if *X* and *Y* are specified in the call to\n contour.\n\nlocator : ticker.Locator subclass, optional\n The locator is used to determine the contour levels if they are not given\n explicitly via *levels*.\n Defaults to `~.ticker.MaxNLocator`.\n\nextend : {\'neither\', \'both\', \'min\', \'max\'}, default: \'neither\'\n Determines the ``%%(func)s``-coloring of values that are outside the\n *levels* range.\n\n If \'neither\', values outside the *levels* range are not colored. If \'min\',\n \'max\' or \'both\', color the values below, above or below and above the\n *levels* range.\n\n Values below ``min(levels)`` and above ``max(levels)`` are mapped to the\n under/over values of the `.Colormap`. Note that most colormaps do not have\n dedicated colors for these by default, so that the over and under values\n are the edge values of the colormap. You may want to set these values\n explicitly using `.Colormap.set_under` and `.Colormap.set_over`.\n\n .. note::\n\n An existing `.TriContourSet` does not get notified if properties of its\n colormap are changed. Therefore, an explicit call to\n `.ContourSet.changed()` is needed after modifying the colormap. The\n explicit call can be left out, if a colorbar is assigned to the\n `.TriContourSet` because it internally calls `.ContourSet.changed()`.\n\nxunits, yunits : registered units, optional\n Override axis units by specifying an instance of a\n :class:`matplotlib.units.ConversionInterface`.\n\nantialiased : bool, optional\n Enable antialiasing, overriding the defaults. For\n filled contours, the default is *True*. For line contours,\n it is taken from :rc:`lines.antialiased`.' % _docstring.interpd.params) @_docstring.Substitution(func='tricontour', type='lines') @_docstring.dedent_interpd def tricontour(ax, *args, **kwargs): kwargs['filled'] = False return TriContourSet(ax, *args, **kwargs) @_docstring.Substitution(func='tricontourf', type='regions') @_docstring.dedent_interpd def tricontourf(ax, *args, **kwargs): kwargs['filled'] = True return TriContourSet(ax, *args, **kwargs) # File: matplotlib-main/lib/matplotlib/tri/_trifinder.py import numpy as np from matplotlib import _api from matplotlib.tri import Triangulation class TriFinder: def __init__(self, triangulation): _api.check_isinstance(Triangulation, triangulation=triangulation) self._triangulation = triangulation def __call__(self, x, y): raise NotImplementedError class TrapezoidMapTriFinder(TriFinder): def __init__(self, triangulation): from matplotlib import _tri super().__init__(triangulation) self._cpp_trifinder = _tri.TrapezoidMapTriFinder(triangulation.get_cpp_triangulation()) self._initialize() def __call__(self, x, y): x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) if x.shape != y.shape: raise ValueError('x and y must be array-like with the same shape') indices = self._cpp_trifinder.find_many(x.ravel(), y.ravel()).reshape(x.shape) return indices def _get_tree_stats(self): return self._cpp_trifinder.get_tree_stats() def _initialize(self): self._cpp_trifinder.initialize() def _print_tree(self): self._cpp_trifinder.print_tree() # File: matplotlib-main/lib/matplotlib/tri/_triinterpolate.py """""" import numpy as np from matplotlib import _api from matplotlib.tri import Triangulation from matplotlib.tri._trifinder import TriFinder from matplotlib.tri._tritools import TriAnalyzer __all__ = ('TriInterpolator', 'LinearTriInterpolator', 'CubicTriInterpolator') class TriInterpolator: def __init__(self, triangulation, z, trifinder=None): _api.check_isinstance(Triangulation, triangulation=triangulation) self._triangulation = triangulation self._z = np.asarray(z) if self._z.shape != self._triangulation.x.shape: raise ValueError('z array must have same length as triangulation x and y arrays') _api.check_isinstance((TriFinder, None), trifinder=trifinder) self._trifinder = trifinder or self._triangulation.get_trifinder() self._unit_x = 1.0 self._unit_y = 1.0 self._tri_renum = None _docstring__call__ = '\n Returns a masked array containing interpolated values at the specified\n (x, y) points.\n\n Parameters\n ----------\n x, y : array-like\n x and y coordinates of the same shape and any number of\n dimensions.\n\n Returns\n -------\n np.ma.array\n Masked array of the same shape as *x* and *y*; values corresponding\n to (*x*, *y*) points outside of the triangulation are masked out.\n\n ' _docstringgradient = '\n Returns a list of 2 masked arrays containing interpolated derivatives\n at the specified (x, y) points.\n\n Parameters\n ----------\n x, y : array-like\n x and y coordinates of the same shape and any number of\n dimensions.\n\n Returns\n -------\n dzdx, dzdy : np.ma.array\n 2 masked arrays of the same shape as *x* and *y*; values\n corresponding to (x, y) points outside of the triangulation\n are masked out.\n The first returned array contains the values of\n :math:`\\frac{\\partial z}{\\partial x}` and the second those of\n :math:`\\frac{\\partial z}{\\partial y}`.\n\n ' def _interpolate_multikeys(self, x, y, tri_index=None, return_keys=('z',)): x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) sh_ret = x.shape if x.shape != y.shape: raise ValueError(f'x and y shall have same shapes. Given: {x.shape} and {y.shape}') x = np.ravel(x) y = np.ravel(y) x_scaled = x / self._unit_x y_scaled = y / self._unit_y size_ret = np.size(x_scaled) if tri_index is None: tri_index = self._trifinder(x, y) else: if tri_index.shape != sh_ret: raise ValueError(f'tri_index array is provided and shall have same shape as x and y. Given: {tri_index.shape} and {sh_ret}') tri_index = np.ravel(tri_index) mask_in = tri_index != -1 if self._tri_renum is None: valid_tri_index = tri_index[mask_in] else: valid_tri_index = self._tri_renum[tri_index[mask_in]] valid_x = x_scaled[mask_in] valid_y = y_scaled[mask_in] ret = [] for return_key in return_keys: try: return_index = {'z': 0, 'dzdx': 1, 'dzdy': 2}[return_key] except KeyError as err: raise ValueError("return_keys items shall take values in {'z', 'dzdx', 'dzdy'}") from err scale = [1.0, 1.0 / self._unit_x, 1.0 / self._unit_y][return_index] ret_loc = np.empty(size_ret, dtype=np.float64) ret_loc[~mask_in] = np.nan ret_loc[mask_in] = self._interpolate_single_key(return_key, valid_tri_index, valid_x, valid_y) * scale ret += [np.ma.masked_invalid(ret_loc.reshape(sh_ret), copy=False)] return ret def _interpolate_single_key(self, return_key, tri_index, x, y): raise NotImplementedError('TriInterpolator subclasses' + 'should implement _interpolate_single_key!') class LinearTriInterpolator(TriInterpolator): def __init__(self, triangulation, z, trifinder=None): super().__init__(triangulation, z, trifinder) self._plane_coefficients = self._triangulation.calculate_plane_coefficients(self._z) def __call__(self, x, y): return self._interpolate_multikeys(x, y, tri_index=None, return_keys=('z',))[0] __call__.__doc__ = TriInterpolator._docstring__call__ def gradient(self, x, y): return self._interpolate_multikeys(x, y, tri_index=None, return_keys=('dzdx', 'dzdy')) gradient.__doc__ = TriInterpolator._docstringgradient def _interpolate_single_key(self, return_key, tri_index, x, y): _api.check_in_list(['z', 'dzdx', 'dzdy'], return_key=return_key) if return_key == 'z': return self._plane_coefficients[tri_index, 0] * x + self._plane_coefficients[tri_index, 1] * y + self._plane_coefficients[tri_index, 2] elif return_key == 'dzdx': return self._plane_coefficients[tri_index, 0] else: return self._plane_coefficients[tri_index, 1] class CubicTriInterpolator(TriInterpolator): def __init__(self, triangulation, z, kind='min_E', trifinder=None, dz=None): super().__init__(triangulation, z, trifinder) self._triangulation.get_cpp_triangulation() tri_analyzer = TriAnalyzer(self._triangulation) (compressed_triangles, compressed_x, compressed_y, tri_renum, node_renum) = tri_analyzer._get_compressed_triangulation() self._triangles = compressed_triangles self._tri_renum = tri_renum valid_node = node_renum != -1 self._z[node_renum[valid_node]] = self._z[valid_node] self._unit_x = np.ptp(compressed_x) self._unit_y = np.ptp(compressed_y) self._pts = np.column_stack([compressed_x / self._unit_x, compressed_y / self._unit_y]) self._tris_pts = self._pts[self._triangles] self._eccs = self._compute_tri_eccentricities(self._tris_pts) _api.check_in_list(['user', 'geom', 'min_E'], kind=kind) self._dof = self._compute_dof(kind, dz=dz) self._ReferenceElement = _ReducedHCT_Element() def __call__(self, x, y): return self._interpolate_multikeys(x, y, tri_index=None, return_keys=('z',))[0] __call__.__doc__ = TriInterpolator._docstring__call__ def gradient(self, x, y): return self._interpolate_multikeys(x, y, tri_index=None, return_keys=('dzdx', 'dzdy')) gradient.__doc__ = TriInterpolator._docstringgradient def _interpolate_single_key(self, return_key, tri_index, x, y): _api.check_in_list(['z', 'dzdx', 'dzdy'], return_key=return_key) tris_pts = self._tris_pts[tri_index] alpha = self._get_alpha_vec(x, y, tris_pts) ecc = self._eccs[tri_index] dof = np.expand_dims(self._dof[tri_index], axis=1) if return_key == 'z': return self._ReferenceElement.get_function_values(alpha, ecc, dof) else: J = self._get_jacobian(tris_pts) dzdx = self._ReferenceElement.get_function_derivatives(alpha, J, ecc, dof) if return_key == 'dzdx': return dzdx[:, 0, 0] else: return dzdx[:, 1, 0] def _compute_dof(self, kind, dz=None): if kind == 'user': if dz is None: raise ValueError("For a CubicTriInterpolator with *kind*='user', a valid *dz* argument is expected.") TE = _DOF_estimator_user(self, dz=dz) elif kind == 'geom': TE = _DOF_estimator_geom(self) else: TE = _DOF_estimator_min_E(self) return TE.compute_dof_from_df() @staticmethod def _get_alpha_vec(x, y, tris_pts): ndim = tris_pts.ndim - 2 a = tris_pts[:, 1, :] - tris_pts[:, 0, :] b = tris_pts[:, 2, :] - tris_pts[:, 0, :] abT = np.stack([a, b], axis=-1) ab = _transpose_vectorized(abT) OM = np.stack([x, y], axis=1) - tris_pts[:, 0, :] metric = ab @ abT metric_inv = _pseudo_inv22sym_vectorized(metric) Covar = ab @ _transpose_vectorized(np.expand_dims(OM, ndim)) ksi = metric_inv @ Covar alpha = _to_matrix_vectorized([[1 - ksi[:, 0, 0] - ksi[:, 1, 0]], [ksi[:, 0, 0]], [ksi[:, 1, 0]]]) return alpha @staticmethod def _get_jacobian(tris_pts): a = np.array(tris_pts[:, 1, :] - tris_pts[:, 0, :]) b = np.array(tris_pts[:, 2, :] - tris_pts[:, 0, :]) J = _to_matrix_vectorized([[a[:, 0], a[:, 1]], [b[:, 0], b[:, 1]]]) return J @staticmethod def _compute_tri_eccentricities(tris_pts): a = np.expand_dims(tris_pts[:, 2, :] - tris_pts[:, 1, :], axis=2) b = np.expand_dims(tris_pts[:, 0, :] - tris_pts[:, 2, :], axis=2) c = np.expand_dims(tris_pts[:, 1, :] - tris_pts[:, 0, :], axis=2) dot_a = (_transpose_vectorized(a) @ a)[:, 0, 0] dot_b = (_transpose_vectorized(b) @ b)[:, 0, 0] dot_c = (_transpose_vectorized(c) @ c)[:, 0, 0] return _to_matrix_vectorized([[(dot_c - dot_b) / dot_a], [(dot_a - dot_c) / dot_b], [(dot_b - dot_a) / dot_c]]) class _ReducedHCT_Element: M = np.array([[0.0, 0.0, 0.0, 4.5, 4.5, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.25, 0.0, 0.0, 0.5, 1.25, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.25, 0.0, 0.0, 1.25, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0], [0.5, 1.0, 0.0, -1.5, 0.0, 3.0, 3.0, 0.0, 0.0, 3.0], [0.0, 0.0, 0.0, -0.25, 0.25, 0.0, 1.0, 0.0, 0.0, 0.5], [0.25, 0.0, 0.0, -0.5, -0.25, 1.0, 0.0, 0.0, 0.0, 1.0], [0.5, 0.0, 1.0, 0.0, -1.5, 0.0, 0.0, 3.0, 3.0, 3.0], [0.25, 0.0, 0.0, -0.25, -0.5, 0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.25, -0.25, 0.0, 0.0, 1.0, 0.0, 0.5]]) M0 = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 1.5, 1.5, 0.0, 0.0, 0.0, 0.0, -3.0], [-0.5, 0.0, 0.0, 0.75, 0.75, 0.0, 0.0, 0.0, 0.0, -1.5], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, -1.5, -1.5, 0.0, 0.0, 0.0, 0.0, 3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.5, 0.0, 0.0, -0.75, -0.75, 0.0, 0.0, 0.0, 0.0, 1.5]]) M1 = np.array([[-0.5, 0.0, 0.0, 1.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.25, 0.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.5, 0.0, 0.0, -1.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.25, 0.0, 0.0, -0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) M2 = np.array([[0.5, 0.0, 0.0, 0.0, -1.5, 0.0, 0.0, 0.0, 0.0, 0.0], [0.25, 0.0, 0.0, 0.0, -0.75, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.5, 0.0, 0.0, 0.0, 1.5, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.25, 0.0, 0.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) rotate_dV = np.array([[1.0, 0.0], [0.0, 1.0], [0.0, 1.0], [-1.0, -1.0], [-1.0, -1.0], [1.0, 0.0]]) rotate_d2V = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, -2.0, -1.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [-2.0, 0.0, -1.0]]) n_gauss = 9 gauss_pts = np.array([[13.0 / 18.0, 4.0 / 18.0, 1.0 / 18.0], [4.0 / 18.0, 13.0 / 18.0, 1.0 / 18.0], [7.0 / 18.0, 7.0 / 18.0, 4.0 / 18.0], [1.0 / 18.0, 13.0 / 18.0, 4.0 / 18.0], [1.0 / 18.0, 4.0 / 18.0, 13.0 / 18.0], [4.0 / 18.0, 7.0 / 18.0, 7.0 / 18.0], [4.0 / 18.0, 1.0 / 18.0, 13.0 / 18.0], [13.0 / 18.0, 1.0 / 18.0, 4.0 / 18.0], [7.0 / 18.0, 4.0 / 18.0, 7.0 / 18.0]], dtype=np.float64) gauss_w = np.ones([9], dtype=np.float64) / 9.0 E = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 2.0]]) J0_to_J1 = np.array([[-1.0, 1.0], [-1.0, 0.0]]) J0_to_J2 = np.array([[0.0, -1.0], [1.0, -1.0]]) def get_function_values(self, alpha, ecc, dofs): subtri = np.argmin(alpha, axis=1)[:, 0] ksi = _roll_vectorized(alpha, -subtri, axis=0) E = _roll_vectorized(ecc, -subtri, axis=0) x = ksi[:, 0, 0] y = ksi[:, 1, 0] z = ksi[:, 2, 0] x_sq = x * x y_sq = y * y z_sq = z * z V = _to_matrix_vectorized([[x_sq * x], [y_sq * y], [z_sq * z], [x_sq * z], [x_sq * y], [y_sq * x], [y_sq * z], [z_sq * y], [z_sq * x], [x * y * z]]) prod = self.M @ V prod += _scalar_vectorized(E[:, 0, 0], self.M0 @ V) prod += _scalar_vectorized(E[:, 1, 0], self.M1 @ V) prod += _scalar_vectorized(E[:, 2, 0], self.M2 @ V) s = _roll_vectorized(prod, 3 * subtri, axis=0) return (dofs @ s)[:, 0, 0] def get_function_derivatives(self, alpha, J, ecc, dofs): subtri = np.argmin(alpha, axis=1)[:, 0] ksi = _roll_vectorized(alpha, -subtri, axis=0) E = _roll_vectorized(ecc, -subtri, axis=0) x = ksi[:, 0, 0] y = ksi[:, 1, 0] z = ksi[:, 2, 0] x_sq = x * x y_sq = y * y z_sq = z * z dV = _to_matrix_vectorized([[-3.0 * x_sq, -3.0 * x_sq], [3.0 * y_sq, 0.0], [0.0, 3.0 * z_sq], [-2.0 * x * z, -2.0 * x * z + x_sq], [-2.0 * x * y + x_sq, -2.0 * x * y], [2.0 * x * y - y_sq, -y_sq], [2.0 * y * z, y_sq], [z_sq, 2.0 * y * z], [-z_sq, 2.0 * x * z - z_sq], [x * z - y * z, x * y - y * z]]) dV = dV @ _extract_submatrices(self.rotate_dV, subtri, block_size=2, axis=0) prod = self.M @ dV prod += _scalar_vectorized(E[:, 0, 0], self.M0 @ dV) prod += _scalar_vectorized(E[:, 1, 0], self.M1 @ dV) prod += _scalar_vectorized(E[:, 2, 0], self.M2 @ dV) dsdksi = _roll_vectorized(prod, 3 * subtri, axis=0) dfdksi = dofs @ dsdksi J_inv = _safe_inv22_vectorized(J) dfdx = J_inv @ _transpose_vectorized(dfdksi) return dfdx def get_function_hessians(self, alpha, J, ecc, dofs): d2sdksi2 = self.get_d2Sidksij2(alpha, ecc) d2fdksi2 = dofs @ d2sdksi2 H_rot = self.get_Hrot_from_J(J) d2fdx2 = d2fdksi2 @ H_rot return _transpose_vectorized(d2fdx2) def get_d2Sidksij2(self, alpha, ecc): subtri = np.argmin(alpha, axis=1)[:, 0] ksi = _roll_vectorized(alpha, -subtri, axis=0) E = _roll_vectorized(ecc, -subtri, axis=0) x = ksi[:, 0, 0] y = ksi[:, 1, 0] z = ksi[:, 2, 0] d2V = _to_matrix_vectorized([[6.0 * x, 6.0 * x, 6.0 * x], [6.0 * y, 0.0, 0.0], [0.0, 6.0 * z, 0.0], [2.0 * z, 2.0 * z - 4.0 * x, 2.0 * z - 2.0 * x], [2.0 * y - 4.0 * x, 2.0 * y, 2.0 * y - 2.0 * x], [2.0 * x - 4.0 * y, 0.0, -2.0 * y], [2.0 * z, 0.0, 2.0 * y], [0.0, 2.0 * y, 2.0 * z], [0.0, 2.0 * x - 4.0 * z, -2.0 * z], [-2.0 * z, -2.0 * y, x - y - z]]) d2V = d2V @ _extract_submatrices(self.rotate_d2V, subtri, block_size=3, axis=0) prod = self.M @ d2V prod += _scalar_vectorized(E[:, 0, 0], self.M0 @ d2V) prod += _scalar_vectorized(E[:, 1, 0], self.M1 @ d2V) prod += _scalar_vectorized(E[:, 2, 0], self.M2 @ d2V) d2sdksi2 = _roll_vectorized(prod, 3 * subtri, axis=0) return d2sdksi2 def get_bending_matrices(self, J, ecc): n = np.size(ecc, 0) J1 = self.J0_to_J1 @ J J2 = self.J0_to_J2 @ J DOF_rot = np.zeros([n, 9, 9], dtype=np.float64) DOF_rot[:, 0, 0] = 1 DOF_rot[:, 3, 3] = 1 DOF_rot[:, 6, 6] = 1 DOF_rot[:, 1:3, 1:3] = J DOF_rot[:, 4:6, 4:6] = J1 DOF_rot[:, 7:9, 7:9] = J2 (H_rot, area) = self.get_Hrot_from_J(J, return_area=True) K = np.zeros([n, 9, 9], dtype=np.float64) weights = self.gauss_w pts = self.gauss_pts for igauss in range(self.n_gauss): alpha = np.tile(pts[igauss, :], n).reshape(n, 3) alpha = np.expand_dims(alpha, 2) weight = weights[igauss] d2Skdksi2 = self.get_d2Sidksij2(alpha, ecc) d2Skdx2 = d2Skdksi2 @ H_rot K += weight * (d2Skdx2 @ self.E @ _transpose_vectorized(d2Skdx2)) K = _transpose_vectorized(DOF_rot) @ K @ DOF_rot return _scalar_vectorized(area, K) def get_Hrot_from_J(self, J, return_area=False): J_inv = _safe_inv22_vectorized(J) Ji00 = J_inv[:, 0, 0] Ji11 = J_inv[:, 1, 1] Ji10 = J_inv[:, 1, 0] Ji01 = J_inv[:, 0, 1] H_rot = _to_matrix_vectorized([[Ji00 * Ji00, Ji10 * Ji10, Ji00 * Ji10], [Ji01 * Ji01, Ji11 * Ji11, Ji01 * Ji11], [2 * Ji00 * Ji01, 2 * Ji11 * Ji10, Ji00 * Ji11 + Ji10 * Ji01]]) if not return_area: return H_rot else: area = 0.5 * (J[:, 0, 0] * J[:, 1, 1] - J[:, 0, 1] * J[:, 1, 0]) return (H_rot, area) def get_Kff_and_Ff(self, J, ecc, triangles, Uc): ntri = np.size(ecc, 0) vec_range = np.arange(ntri, dtype=np.int32) c_indices = np.full(ntri, -1, dtype=np.int32) f_dof = [1, 2, 4, 5, 7, 8] c_dof = [0, 3, 6] f_dof_indices = _to_matrix_vectorized([[c_indices, triangles[:, 0] * 2, triangles[:, 0] * 2 + 1, c_indices, triangles[:, 1] * 2, triangles[:, 1] * 2 + 1, c_indices, triangles[:, 2] * 2, triangles[:, 2] * 2 + 1]]) expand_indices = np.ones([ntri, 9, 1], dtype=np.int32) f_row_indices = _transpose_vectorized(expand_indices @ f_dof_indices) f_col_indices = expand_indices @ f_dof_indices K_elem = self.get_bending_matrices(J, ecc) Kff_vals = np.ravel(K_elem[np.ix_(vec_range, f_dof, f_dof)]) Kff_rows = np.ravel(f_row_indices[np.ix_(vec_range, f_dof, f_dof)]) Kff_cols = np.ravel(f_col_indices[np.ix_(vec_range, f_dof, f_dof)]) Kfc_elem = K_elem[np.ix_(vec_range, f_dof, c_dof)] Uc_elem = np.expand_dims(Uc, axis=2) Ff_elem = -(Kfc_elem @ Uc_elem)[:, :, 0] Ff_indices = f_dof_indices[np.ix_(vec_range, [0], f_dof)][:, 0, :] Ff = np.bincount(np.ravel(Ff_indices), weights=np.ravel(Ff_elem)) return (Kff_rows, Kff_cols, Kff_vals, Ff) class _DOF_estimator: def __init__(self, interpolator, **kwargs): _api.check_isinstance(CubicTriInterpolator, interpolator=interpolator) self._pts = interpolator._pts self._tris_pts = interpolator._tris_pts self.z = interpolator._z self._triangles = interpolator._triangles (self._unit_x, self._unit_y) = (interpolator._unit_x, interpolator._unit_y) self.dz = self.compute_dz(**kwargs) self.compute_dof_from_df() def compute_dz(self, **kwargs): raise NotImplementedError def compute_dof_from_df(self): J = CubicTriInterpolator._get_jacobian(self._tris_pts) tri_z = self.z[self._triangles] tri_dz = self.dz[self._triangles] tri_dof = self.get_dof_vec(tri_z, tri_dz, J) return tri_dof @staticmethod def get_dof_vec(tri_z, tri_dz, J): npt = tri_z.shape[0] dof = np.zeros([npt, 9], dtype=np.float64) J1 = _ReducedHCT_Element.J0_to_J1 @ J J2 = _ReducedHCT_Element.J0_to_J2 @ J col0 = J @ np.expand_dims(tri_dz[:, 0, :], axis=2) col1 = J1 @ np.expand_dims(tri_dz[:, 1, :], axis=2) col2 = J2 @ np.expand_dims(tri_dz[:, 2, :], axis=2) dfdksi = _to_matrix_vectorized([[col0[:, 0, 0], col1[:, 0, 0], col2[:, 0, 0]], [col0[:, 1, 0], col1[:, 1, 0], col2[:, 1, 0]]]) dof[:, 0:7:3] = tri_z dof[:, 1:8:3] = dfdksi[:, 0] dof[:, 2:9:3] = dfdksi[:, 1] return dof class _DOF_estimator_user(_DOF_estimator): def compute_dz(self, dz): (dzdx, dzdy) = dz dzdx = dzdx * self._unit_x dzdy = dzdy * self._unit_y return np.vstack([dzdx, dzdy]).T class _DOF_estimator_geom(_DOF_estimator): def compute_dz(self): el_geom_w = self.compute_geom_weights() el_geom_grad = self.compute_geom_grads() w_node_sum = np.bincount(np.ravel(self._triangles), weights=np.ravel(el_geom_w)) dfx_el_w = np.empty_like(el_geom_w) dfy_el_w = np.empty_like(el_geom_w) for iapex in range(3): dfx_el_w[:, iapex] = el_geom_w[:, iapex] * el_geom_grad[:, 0] dfy_el_w[:, iapex] = el_geom_w[:, iapex] * el_geom_grad[:, 1] dfx_node_sum = np.bincount(np.ravel(self._triangles), weights=np.ravel(dfx_el_w)) dfy_node_sum = np.bincount(np.ravel(self._triangles), weights=np.ravel(dfy_el_w)) dfx_estim = dfx_node_sum / w_node_sum dfy_estim = dfy_node_sum / w_node_sum return np.vstack([dfx_estim, dfy_estim]).T def compute_geom_weights(self): weights = np.zeros([np.size(self._triangles, 0), 3]) tris_pts = self._tris_pts for ipt in range(3): p0 = tris_pts[:, ipt % 3, :] p1 = tris_pts[:, (ipt + 1) % 3, :] p2 = tris_pts[:, (ipt - 1) % 3, :] alpha1 = np.arctan2(p1[:, 1] - p0[:, 1], p1[:, 0] - p0[:, 0]) alpha2 = np.arctan2(p2[:, 1] - p0[:, 1], p2[:, 0] - p0[:, 0]) angle = np.abs((alpha2 - alpha1) / np.pi % 1) weights[:, ipt] = 0.5 - np.abs(angle - 0.5) return weights def compute_geom_grads(self): tris_pts = self._tris_pts tris_f = self.z[self._triangles] dM1 = tris_pts[:, 1, :] - tris_pts[:, 0, :] dM2 = tris_pts[:, 2, :] - tris_pts[:, 0, :] dM = np.dstack([dM1, dM2]) dM_inv = _safe_inv22_vectorized(dM) dZ1 = tris_f[:, 1] - tris_f[:, 0] dZ2 = tris_f[:, 2] - tris_f[:, 0] dZ = np.vstack([dZ1, dZ2]).T df = np.empty_like(dZ) df[:, 0] = dZ[:, 0] * dM_inv[:, 0, 0] + dZ[:, 1] * dM_inv[:, 1, 0] df[:, 1] = dZ[:, 0] * dM_inv[:, 0, 1] + dZ[:, 1] * dM_inv[:, 1, 1] return df class _DOF_estimator_min_E(_DOF_estimator_geom): def __init__(self, Interpolator): self._eccs = Interpolator._eccs super().__init__(Interpolator) def compute_dz(self): dz_init = super().compute_dz() Uf0 = np.ravel(dz_init) reference_element = _ReducedHCT_Element() J = CubicTriInterpolator._get_jacobian(self._tris_pts) eccs = self._eccs triangles = self._triangles Uc = self.z[self._triangles] (Kff_rows, Kff_cols, Kff_vals, Ff) = reference_element.get_Kff_and_Ff(J, eccs, triangles, Uc) tol = 1e-10 n_dof = Ff.shape[0] Kff_coo = _Sparse_Matrix_coo(Kff_vals, Kff_rows, Kff_cols, shape=(n_dof, n_dof)) Kff_coo.compress_csc() (Uf, err) = _cg(A=Kff_coo, b=Ff, x0=Uf0, tol=tol) err0 = np.linalg.norm(Kff_coo.dot(Uf0) - Ff) if err0 < err: _api.warn_external('In TriCubicInterpolator initialization, PCG sparse solver did not converge after 1000 iterations. `geom` approximation is used instead of `min_E`') Uf = Uf0 dz = np.empty([self._pts.shape[0], 2], dtype=np.float64) dz[:, 0] = Uf[::2] dz[:, 1] = Uf[1::2] return dz class _Sparse_Matrix_coo: def __init__(self, vals, rows, cols, shape): (self.n, self.m) = shape self.vals = np.asarray(vals, dtype=np.float64) self.rows = np.asarray(rows, dtype=np.int32) self.cols = np.asarray(cols, dtype=np.int32) def dot(self, V): assert V.shape == (self.m,) return np.bincount(self.rows, weights=self.vals * V[self.cols], minlength=self.m) def compress_csc(self): (_, unique, indices) = np.unique(self.rows + self.n * self.cols, return_index=True, return_inverse=True) self.rows = self.rows[unique] self.cols = self.cols[unique] self.vals = np.bincount(indices, weights=self.vals) def compress_csr(self): (_, unique, indices) = np.unique(self.m * self.rows + self.cols, return_index=True, return_inverse=True) self.rows = self.rows[unique] self.cols = self.cols[unique] self.vals = np.bincount(indices, weights=self.vals) def to_dense(self): ret = np.zeros([self.n, self.m], dtype=np.float64) nvals = self.vals.size for i in range(nvals): ret[self.rows[i], self.cols[i]] += self.vals[i] return ret def __str__(self): return self.to_dense().__str__() @property def diag(self): in_diag = self.rows == self.cols diag = np.zeros(min(self.n, self.n), dtype=np.float64) diag[self.rows[in_diag]] = self.vals[in_diag] return diag def _cg(A, b, x0=None, tol=1e-10, maxiter=1000): n = b.size assert A.n == n assert A.m == n b_norm = np.linalg.norm(b) kvec = A.diag kvec = np.maximum(kvec, 1e-06) if x0 is None: x = np.zeros(n) else: x = x0 r = b - A.dot(x) w = r / kvec p = np.zeros(n) beta = 0.0 rho = np.dot(r, w) k = 0 while np.sqrt(abs(rho)) > tol * b_norm and k < maxiter: p = w + beta * p z = A.dot(p) alpha = rho / np.dot(p, z) r = r - alpha * z w = r / kvec rhoold = rho rho = np.dot(r, w) x = x + alpha * p beta = rho / rhoold k += 1 err = np.linalg.norm(A.dot(x) - b) return (x, err) def _safe_inv22_vectorized(M): _api.check_shape((None, 2, 2), M=M) M_inv = np.empty_like(M) prod1 = M[:, 0, 0] * M[:, 1, 1] delta = prod1 - M[:, 0, 1] * M[:, 1, 0] rank2 = np.abs(delta) > 1e-08 * np.abs(prod1) if np.all(rank2): delta_inv = 1.0 / delta else: delta_inv = np.zeros(M.shape[0]) delta_inv[rank2] = 1.0 / delta[rank2] M_inv[:, 0, 0] = M[:, 1, 1] * delta_inv M_inv[:, 0, 1] = -M[:, 0, 1] * delta_inv M_inv[:, 1, 0] = -M[:, 1, 0] * delta_inv M_inv[:, 1, 1] = M[:, 0, 0] * delta_inv return M_inv def _pseudo_inv22sym_vectorized(M): _api.check_shape((None, 2, 2), M=M) M_inv = np.empty_like(M) prod1 = M[:, 0, 0] * M[:, 1, 1] delta = prod1 - M[:, 0, 1] * M[:, 1, 0] rank2 = np.abs(delta) > 1e-08 * np.abs(prod1) if np.all(rank2): M_inv[:, 0, 0] = M[:, 1, 1] / delta M_inv[:, 0, 1] = -M[:, 0, 1] / delta M_inv[:, 1, 0] = -M[:, 1, 0] / delta M_inv[:, 1, 1] = M[:, 0, 0] / delta else: delta = delta[rank2] M_inv[rank2, 0, 0] = M[rank2, 1, 1] / delta M_inv[rank2, 0, 1] = -M[rank2, 0, 1] / delta M_inv[rank2, 1, 0] = -M[rank2, 1, 0] / delta M_inv[rank2, 1, 1] = M[rank2, 0, 0] / delta rank01 = ~rank2 tr = M[rank01, 0, 0] + M[rank01, 1, 1] tr_zeros = np.abs(tr) < 1e-08 sq_tr_inv = (1.0 - tr_zeros) / (tr ** 2 + tr_zeros) M_inv[rank01, 0, 0] = M[rank01, 0, 0] * sq_tr_inv M_inv[rank01, 0, 1] = M[rank01, 0, 1] * sq_tr_inv M_inv[rank01, 1, 0] = M[rank01, 1, 0] * sq_tr_inv M_inv[rank01, 1, 1] = M[rank01, 1, 1] * sq_tr_inv return M_inv def _scalar_vectorized(scalar, M): return scalar[:, np.newaxis, np.newaxis] * M def _transpose_vectorized(M): return np.transpose(M, [0, 2, 1]) def _roll_vectorized(M, roll_indices, axis): assert axis in [0, 1] ndim = M.ndim assert ndim == 3 ndim_roll = roll_indices.ndim assert ndim_roll == 1 sh = M.shape (r, c) = sh[-2:] assert sh[0] == roll_indices.shape[0] vec_indices = np.arange(sh[0], dtype=np.int32) M_roll = np.empty_like(M) if axis == 0: for ir in range(r): for ic in range(c): M_roll[:, ir, ic] = M[vec_indices, (-roll_indices + ir) % r, ic] else: for ir in range(r): for ic in range(c): M_roll[:, ir, ic] = M[vec_indices, ir, (-roll_indices + ic) % c] return M_roll def _to_matrix_vectorized(M): assert isinstance(M, (tuple, list)) assert all((isinstance(item, (tuple, list)) for item in M)) c_vec = np.asarray([len(item) for item in M]) assert np.all(c_vec - c_vec[0] == 0) r = len(M) c = c_vec[0] M00 = np.asarray(M[0][0]) dt = M00.dtype sh = [M00.shape[0], r, c] M_ret = np.empty(sh, dtype=dt) for irow in range(r): for icol in range(c): M_ret[:, irow, icol] = np.asarray(M[irow][icol]) return M_ret def _extract_submatrices(M, block_indices, block_size, axis): assert block_indices.ndim == 1 assert axis in [0, 1] (r, c) = M.shape if axis == 0: sh = [block_indices.shape[0], block_size, c] else: sh = [block_indices.shape[0], r, block_size] dt = M.dtype M_res = np.empty(sh, dtype=dt) if axis == 0: for ir in range(block_size): M_res[:, ir, :] = M[block_indices * block_size + ir, :] else: for ic in range(block_size): M_res[:, :, ic] = M[:, block_indices * block_size + ic] return M_res # File: matplotlib-main/lib/matplotlib/tri/_tripcolor.py import numpy as np from matplotlib import _api from matplotlib.collections import PolyCollection, TriMesh from matplotlib.tri._triangulation import Triangulation def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', facecolors=None, **kwargs): _api.check_in_list(['flat', 'gouraud'], shading=shading) (tri, args, kwargs) = Triangulation.get_from_args_and_kwargs(*args, **kwargs) if facecolors is not None: if args: _api.warn_external('Positional parameter c has no effect when the keyword facecolors is given') point_colors = None if len(facecolors) != len(tri.triangles): raise ValueError('The length of facecolors must match the number of triangles') else: if not args: raise TypeError("tripcolor() missing 1 required positional argument: 'c'; or 1 required keyword-only argument: 'facecolors'") elif len(args) > 1: raise TypeError(f'Unexpected positional parameters: {args[1:]!r}') c = np.asarray(args[0]) if len(c) == len(tri.x): point_colors = c facecolors = None elif len(c) == len(tri.triangles): point_colors = None facecolors = c else: raise ValueError('The length of c must match either the number of points or the number of triangles') linewidths = (0.25,) if 'linewidth' in kwargs: kwargs['linewidths'] = kwargs.pop('linewidth') kwargs.setdefault('linewidths', linewidths) edgecolors = 'none' if 'edgecolor' in kwargs: kwargs['edgecolors'] = kwargs.pop('edgecolor') ec = kwargs.setdefault('edgecolors', edgecolors) if 'antialiased' in kwargs: kwargs['antialiaseds'] = kwargs.pop('antialiased') if 'antialiaseds' not in kwargs and ec.lower() == 'none': kwargs['antialiaseds'] = False if shading == 'gouraud': if facecolors is not None: raise ValueError("shading='gouraud' can only be used when the colors are specified at the points, not at the faces.") collection = TriMesh(tri, alpha=alpha, array=point_colors, cmap=cmap, norm=norm, **kwargs) else: maskedTris = tri.get_masked_triangles() verts = np.stack((tri.x[maskedTris], tri.y[maskedTris]), axis=-1) if facecolors is None: colors = point_colors[maskedTris].mean(axis=1) elif tri.mask is not None: colors = facecolors[~tri.mask] else: colors = facecolors collection = PolyCollection(verts, alpha=alpha, array=colors, cmap=cmap, norm=norm, **kwargs) collection._scale_norm(norm, vmin, vmax) ax.grid(False) minx = tri.x.min() maxx = tri.x.max() miny = tri.y.min() maxy = tri.y.max() corners = ((minx, miny), (maxx, maxy)) ax.update_datalim(corners) ax.autoscale_view() ax.add_collection(collection) return collection # File: matplotlib-main/lib/matplotlib/tri/_triplot.py import numpy as np from matplotlib.tri._triangulation import Triangulation import matplotlib.cbook as cbook import matplotlib.lines as mlines def triplot(ax, *args, **kwargs): import matplotlib.axes (tri, args, kwargs) = Triangulation.get_from_args_and_kwargs(*args, **kwargs) (x, y, edges) = (tri.x, tri.y, tri.edges) fmt = args[0] if args else '' (linestyle, marker, color) = matplotlib.axes._base._process_plot_format(fmt) kw = cbook.normalize_kwargs(kwargs, mlines.Line2D) for (key, val) in zip(('linestyle', 'marker', 'color'), (linestyle, marker, color)): if val is not None: kw.setdefault(key, val) linestyle = kw['linestyle'] kw_lines = {**kw, 'marker': 'None', 'zorder': kw.get('zorder', 1)} if linestyle not in [None, 'None', '', ' ']: tri_lines_x = np.insert(x[edges], 2, np.nan, axis=1) tri_lines_y = np.insert(y[edges], 2, np.nan, axis=1) tri_lines = ax.plot(tri_lines_x.ravel(), tri_lines_y.ravel(), **kw_lines) else: tri_lines = ax.plot([], [], **kw_lines) marker = kw['marker'] kw_markers = {**kw, 'linestyle': 'None'} kw_markers.pop('label', None) if marker not in [None, 'None', '', ' ']: tri_markers = ax.plot(x, y, **kw_markers) else: tri_markers = ax.plot([], [], **kw_markers) return tri_lines + tri_markers # File: matplotlib-main/lib/matplotlib/tri/_trirefine.py """""" import numpy as np from matplotlib import _api from matplotlib.tri._triangulation import Triangulation import matplotlib.tri._triinterpolate class TriRefiner: def __init__(self, triangulation): _api.check_isinstance(Triangulation, triangulation=triangulation) self._triangulation = triangulation class UniformTriRefiner(TriRefiner): def __init__(self, triangulation): super().__init__(triangulation) def refine_triangulation(self, return_tri_index=False, subdiv=3): refi_triangulation = self._triangulation ntri = refi_triangulation.triangles.shape[0] ancestors = np.arange(ntri, dtype=np.int32) for _ in range(subdiv): (refi_triangulation, ancestors) = self._refine_triangulation_once(refi_triangulation, ancestors) refi_npts = refi_triangulation.x.shape[0] refi_triangles = refi_triangulation.triangles if return_tri_index: found_index = np.full(refi_npts, -1, dtype=np.int32) tri_mask = self._triangulation.mask if tri_mask is None: found_index[refi_triangles] = np.repeat(ancestors, 3).reshape(-1, 3) else: ancestor_mask = tri_mask[ancestors] found_index[refi_triangles[ancestor_mask, :]] = np.repeat(ancestors[ancestor_mask], 3).reshape(-1, 3) found_index[refi_triangles[~ancestor_mask, :]] = np.repeat(ancestors[~ancestor_mask], 3).reshape(-1, 3) return (refi_triangulation, found_index) else: return refi_triangulation def refine_field(self, z, triinterpolator=None, subdiv=3): if triinterpolator is None: interp = matplotlib.tri.CubicTriInterpolator(self._triangulation, z) else: _api.check_isinstance(matplotlib.tri.TriInterpolator, triinterpolator=triinterpolator) interp = triinterpolator (refi_tri, found_index) = self.refine_triangulation(subdiv=subdiv, return_tri_index=True) refi_z = interp._interpolate_multikeys(refi_tri.x, refi_tri.y, tri_index=found_index)[0] return (refi_tri, refi_z) @staticmethod def _refine_triangulation_once(triangulation, ancestors=None): x = triangulation.x y = triangulation.y neighbors = triangulation.neighbors triangles = triangulation.triangles npts = np.shape(x)[0] ntri = np.shape(triangles)[0] if ancestors is not None: ancestors = np.asarray(ancestors) if np.shape(ancestors) != (ntri,): raise ValueError(f'Incompatible shapes provide for triangulation.masked_triangles and ancestors: {np.shape(triangles)} and {np.shape(ancestors)}') borders = np.sum(neighbors == -1) added_pts = (3 * ntri + borders) // 2 refi_npts = npts + added_pts refi_x = np.zeros(refi_npts) refi_y = np.zeros(refi_npts) refi_x[:npts] = x refi_y[:npts] = y edge_elems = np.tile(np.arange(ntri, dtype=np.int32), 3) edge_apexes = np.repeat(np.arange(3, dtype=np.int32), ntri) edge_neighbors = neighbors[edge_elems, edge_apexes] mask_masters = edge_elems > edge_neighbors masters = edge_elems[mask_masters] apex_masters = edge_apexes[mask_masters] x_add = (x[triangles[masters, apex_masters]] + x[triangles[masters, (apex_masters + 1) % 3]]) * 0.5 y_add = (y[triangles[masters, apex_masters]] + y[triangles[masters, (apex_masters + 1) % 3]]) * 0.5 refi_x[npts:] = x_add refi_y[npts:] = y_add new_pt_corner = triangles new_pt_midside = np.empty([ntri, 3], dtype=np.int32) cum_sum = npts for imid in range(3): mask_st_loc = imid == apex_masters n_masters_loc = np.sum(mask_st_loc) elem_masters_loc = masters[mask_st_loc] new_pt_midside[:, imid][elem_masters_loc] = np.arange(n_masters_loc, dtype=np.int32) + cum_sum cum_sum += n_masters_loc mask_slaves = np.logical_not(mask_masters) slaves = edge_elems[mask_slaves] slaves_masters = edge_neighbors[mask_slaves] diff_table = np.abs(neighbors[slaves_masters, :] - np.outer(slaves, np.ones(3, dtype=np.int32))) slave_masters_apex = np.argmin(diff_table, axis=1) slaves_apex = edge_apexes[mask_slaves] new_pt_midside[slaves, slaves_apex] = new_pt_midside[slaves_masters, slave_masters_apex] child_triangles = np.empty([ntri * 4, 3], dtype=np.int32) child_triangles[0::4, :] = np.vstack([new_pt_corner[:, 0], new_pt_midside[:, 0], new_pt_midside[:, 2]]).T child_triangles[1::4, :] = np.vstack([new_pt_corner[:, 1], new_pt_midside[:, 1], new_pt_midside[:, 0]]).T child_triangles[2::4, :] = np.vstack([new_pt_corner[:, 2], new_pt_midside[:, 2], new_pt_midside[:, 1]]).T child_triangles[3::4, :] = np.vstack([new_pt_midside[:, 0], new_pt_midside[:, 1], new_pt_midside[:, 2]]).T child_triangulation = Triangulation(refi_x, refi_y, child_triangles) if triangulation.mask is not None: child_triangulation.set_mask(np.repeat(triangulation.mask, 4)) if ancestors is None: return child_triangulation else: return (child_triangulation, np.repeat(ancestors, 4)) # File: matplotlib-main/lib/matplotlib/tri/_tritools.py """""" import numpy as np from matplotlib import _api from matplotlib.tri import Triangulation class TriAnalyzer: def __init__(self, triangulation): _api.check_isinstance(Triangulation, triangulation=triangulation) self._triangulation = triangulation @property def scale_factors(self): compressed_triangles = self._triangulation.get_masked_triangles() node_used = np.bincount(np.ravel(compressed_triangles), minlength=self._triangulation.x.size) != 0 return (1 / np.ptp(self._triangulation.x[node_used]), 1 / np.ptp(self._triangulation.y[node_used])) def circle_ratios(self, rescale=True): if rescale: (kx, ky) = self.scale_factors else: (kx, ky) = (1.0, 1.0) pts = np.vstack([self._triangulation.x * kx, self._triangulation.y * ky]).T tri_pts = pts[self._triangulation.triangles] a = tri_pts[:, 1, :] - tri_pts[:, 0, :] b = tri_pts[:, 2, :] - tri_pts[:, 1, :] c = tri_pts[:, 0, :] - tri_pts[:, 2, :] a = np.hypot(a[:, 0], a[:, 1]) b = np.hypot(b[:, 0], b[:, 1]) c = np.hypot(c[:, 0], c[:, 1]) s = (a + b + c) * 0.5 prod = s * (a + b - s) * (a + c - s) * (b + c - s) bool_flat = prod == 0.0 if np.any(bool_flat): ntri = tri_pts.shape[0] circum_radius = np.empty(ntri, dtype=np.float64) circum_radius[bool_flat] = np.inf abc = a * b * c circum_radius[~bool_flat] = abc[~bool_flat] / (4.0 * np.sqrt(prod[~bool_flat])) else: circum_radius = a * b * c / (4.0 * np.sqrt(prod)) in_radius = a * b * c / (4.0 * circum_radius * s) circle_ratio = in_radius / circum_radius mask = self._triangulation.mask if mask is None: return circle_ratio else: return np.ma.array(circle_ratio, mask=mask) def get_flat_tri_mask(self, min_circle_ratio=0.01, rescale=True): ntri = self._triangulation.triangles.shape[0] mask_bad_ratio = self.circle_ratios(rescale) < min_circle_ratio current_mask = self._triangulation.mask if current_mask is None: current_mask = np.zeros(ntri, dtype=bool) valid_neighbors = np.copy(self._triangulation.neighbors) renum_neighbors = np.arange(ntri, dtype=np.int32) nadd = -1 while nadd != 0: wavefront = (np.min(valid_neighbors, axis=1) == -1) & ~current_mask added_mask = wavefront & mask_bad_ratio current_mask = added_mask | current_mask nadd = np.sum(added_mask) valid_neighbors[added_mask, :] = -1 renum_neighbors[added_mask] = -1 valid_neighbors = np.where(valid_neighbors == -1, -1, renum_neighbors[valid_neighbors]) return np.ma.filled(current_mask, True) def _get_compressed_triangulation(self): tri_mask = self._triangulation.mask compressed_triangles = self._triangulation.get_masked_triangles() ntri = self._triangulation.triangles.shape[0] if tri_mask is not None: tri_renum = self._total_to_compress_renum(~tri_mask) else: tri_renum = np.arange(ntri, dtype=np.int32) valid_node = np.bincount(np.ravel(compressed_triangles), minlength=self._triangulation.x.size) != 0 compressed_x = self._triangulation.x[valid_node] compressed_y = self._triangulation.y[valid_node] node_renum = self._total_to_compress_renum(valid_node) compressed_triangles = node_renum[compressed_triangles] return (compressed_triangles, compressed_x, compressed_y, tri_renum, node_renum) @staticmethod def _total_to_compress_renum(valid): renum = np.full(np.size(valid), -1, dtype=np.int32) n_valid = np.sum(valid) renum[valid] = np.arange(n_valid, dtype=np.int32) return renum # File: matplotlib-main/lib/matplotlib/typing.py """""" from collections.abc import Hashable, Sequence import pathlib from typing import Any, Literal, TypeAlias, TypeVar from . import path from ._enums import JoinStyle, CapStyle from .markers import MarkerStyle RGBColorType: TypeAlias = tuple[float, float, float] | str RGBAColorType: TypeAlias = str | tuple[float, float, float, float] | tuple[RGBColorType, float] | tuple[tuple[float, float, float, float], float] ColorType: TypeAlias = RGBColorType | RGBAColorType RGBColourType: TypeAlias = RGBColorType RGBAColourType: TypeAlias = RGBAColorType ColourType: TypeAlias = ColorType LineStyleType: TypeAlias = str | tuple[float, Sequence[float]] DrawStyleType: TypeAlias = Literal['default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'] MarkEveryType: TypeAlias = None | int | tuple[int, int] | slice | list[int] | float | tuple[float, float] | list[bool] MarkerType: TypeAlias = str | path.Path | MarkerStyle FillStyleType: TypeAlias = Literal['full', 'left', 'right', 'bottom', 'top', 'none'] JoinStyleType: TypeAlias = JoinStyle | Literal['miter', 'round', 'bevel'] CapStyleType: TypeAlias = CapStyle | Literal['butt', 'projecting', 'round'] RcStyleType: TypeAlias = str | dict[str, Any] | pathlib.Path | Sequence[str | pathlib.Path | dict[str, Any]] _HT = TypeVar('_HT', bound=Hashable) HashableList: TypeAlias = list[_HT | 'HashableList[_HT]'] '' # File: matplotlib-main/lib/matplotlib/units.py """""" from decimal import Decimal from numbers import Number import numpy as np from numpy import ma from matplotlib import cbook class ConversionError(TypeError): pass def _is_natively_supported(x): if np.iterable(x): for thisx in x: if thisx is ma.masked: continue return isinstance(thisx, Number) and (not isinstance(thisx, Decimal)) else: return isinstance(x, Number) and (not isinstance(x, Decimal)) class AxisInfo: def __init__(self, majloc=None, minloc=None, majfmt=None, minfmt=None, label=None, default_limits=None): self.majloc = majloc self.minloc = minloc self.majfmt = majfmt self.minfmt = minfmt self.label = label self.default_limits = default_limits class ConversionInterface: @staticmethod def axisinfo(unit, axis): return None @staticmethod def default_units(x, axis): return None @staticmethod def convert(obj, unit, axis): return obj class DecimalConverter(ConversionInterface): @staticmethod def convert(value, unit, axis): if isinstance(value, Decimal): return float(value) elif isinstance(value, ma.MaskedArray): return ma.asarray(value, dtype=float) else: return np.asarray(value, dtype=float) class Registry(dict): def get_converter(self, x): x = cbook._unpack_to_numpy(x) if isinstance(x, np.ndarray): x = np.ma.getdata(x).ravel() if not x.size: return self.get_converter(np.array([0], dtype=x.dtype)) for cls in type(x).__mro__: try: return self[cls] except KeyError: pass try: first = cbook._safe_first_finite(x) except (TypeError, StopIteration): pass else: if type(first) is not type(x): return self.get_converter(first) return None registry = Registry() registry[Decimal] = DecimalConverter() # File: matplotlib-main/lib/matplotlib/widgets.py """""" from contextlib import ExitStack import copy import itertools from numbers import Integral, Number from cycler import cycler import numpy as np import matplotlib as mpl from . import _api, _docstring, backend_tools, cbook, collections, colors, text as mtext, ticker, transforms from .lines import Line2D from .patches import Rectangle, Ellipse, Polygon from .transforms import TransformedPatchPath, Affine2D class LockDraw: def __init__(self): self._owner = None def __call__(self, o): if not self.available(o): raise ValueError('already locked') self._owner = o def release(self, o): if not self.available(o): raise ValueError('you do not own this lock') self._owner = None def available(self, o): return not self.locked() or self.isowner(o) def isowner(self, o): return self._owner is o def locked(self): return self._owner is not None class Widget: drawon = True eventson = True _active = True def set_active(self, active): self._active = active def get_active(self): return self._active active = property(get_active, set_active, doc='Is the widget active?') def ignore(self, event): return not self.active class AxesWidget(Widget): def __init__(self, ax): self.ax = ax self._cids = [] canvas = property(lambda self: self.ax.get_figure(root=True).canvas) def connect_event(self, event, callback): cid = self.canvas.mpl_connect(event, callback) self._cids.append(cid) def disconnect_events(self): for c in self._cids: self.canvas.mpl_disconnect(c) def _get_data_coords(self, event): return (event.xdata, event.ydata) if event.inaxes is self.ax else self.ax.transData.inverted().transform((event.x, event.y)) class Button(AxesWidget): def __init__(self, ax, label, image=None, color='0.85', hovercolor='0.95', *, useblit=True): super().__init__(ax) if image is not None: ax.imshow(image) self.label = ax.text(0.5, 0.5, label, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes) self._useblit = useblit and self.canvas.supports_blit self._observers = cbook.CallbackRegistry(signals=['clicked']) self.connect_event('button_press_event', self._click) self.connect_event('button_release_event', self._release) self.connect_event('motion_notify_event', self._motion) ax.set_navigate(False) ax.set_facecolor(color) ax.set_xticks([]) ax.set_yticks([]) self.color = color self.hovercolor = hovercolor def _click(self, event): if not self.eventson or self.ignore(event) or (not self.ax.contains(event)[0]): return if event.canvas.mouse_grabber != self.ax: event.canvas.grab_mouse(self.ax) def _release(self, event): if self.ignore(event) or event.canvas.mouse_grabber != self.ax: return event.canvas.release_mouse(self.ax) if self.eventson and self.ax.contains(event)[0]: self._observers.process('clicked', event) def _motion(self, event): if self.ignore(event): return c = self.hovercolor if self.ax.contains(event)[0] else self.color if not colors.same_color(c, self.ax.get_facecolor()): self.ax.set_facecolor(c) if self.drawon: if self._useblit: self.ax.draw_artist(self.ax) self.canvas.blit(self.ax.bbox) else: self.canvas.draw() def on_clicked(self, func): return self._observers.connect('clicked', lambda event: func(event)) def disconnect(self, cid): self._observers.disconnect(cid) class SliderBase(AxesWidget): def __init__(self, ax, orientation, closedmin, closedmax, valmin, valmax, valfmt, dragging, valstep): if ax.name == '3d': raise ValueError('Sliders cannot be added to 3D Axes') super().__init__(ax) _api.check_in_list(['horizontal', 'vertical'], orientation=orientation) self.orientation = orientation self.closedmin = closedmin self.closedmax = closedmax self.valmin = valmin self.valmax = valmax self.valstep = valstep self.drag_active = False self.valfmt = valfmt if orientation == 'vertical': ax.set_ylim((valmin, valmax)) axis = ax.yaxis else: ax.set_xlim((valmin, valmax)) axis = ax.xaxis self._fmt = axis.get_major_formatter() if not isinstance(self._fmt, ticker.ScalarFormatter): self._fmt = ticker.ScalarFormatter() self._fmt.set_axis(axis) self._fmt.set_useOffset(False) self._fmt.set_useMathText(True) ax.set_axis_off() ax.set_navigate(False) self.connect_event('button_press_event', self._update) self.connect_event('button_release_event', self._update) if dragging: self.connect_event('motion_notify_event', self._update) self._observers = cbook.CallbackRegistry(signals=['changed']) def _stepped_value(self, val): if isinstance(self.valstep, Number): val = self.valmin + round((val - self.valmin) / self.valstep) * self.valstep elif self.valstep is not None: valstep = np.asanyarray(self.valstep) if valstep.ndim != 1: raise ValueError(f'valstep must have 1 dimension but has {valstep.ndim}') val = valstep[np.argmin(np.abs(valstep - val))] return val def disconnect(self, cid): self._observers.disconnect(cid) def reset(self): if np.any(self.val != self.valinit): self.set_val(self.valinit) class Slider(SliderBase): def __init__(self, ax, label, valmin, valmax, *, valinit=0.5, valfmt=None, closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, valstep=None, orientation='horizontal', initcolor='r', track_color='lightgrey', handle_style=None, **kwargs): super().__init__(ax, orientation, closedmin, closedmax, valmin, valmax, valfmt, dragging, valstep) if slidermin is not None and (not hasattr(slidermin, 'val')): raise ValueError(f"Argument slidermin ({type(slidermin)}) has no 'val'") if slidermax is not None and (not hasattr(slidermax, 'val')): raise ValueError(f"Argument slidermax ({type(slidermax)}) has no 'val'") self.slidermin = slidermin self.slidermax = slidermax valinit = self._value_in_bounds(valinit) if valinit is None: valinit = valmin self.val = valinit self.valinit = valinit defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10} handle_style = {} if handle_style is None else handle_style marker_props = {f'marker{k}': v for (k, v) in {**defaults, **handle_style}.items()} if orientation == 'vertical': self.track = Rectangle((0.25, 0), 0.5, 1, transform=ax.transAxes, facecolor=track_color) ax.add_patch(self.track) self.poly = ax.axhspan(valmin, valinit, 0.25, 0.75, **kwargs) self.hline = ax.axhline(valinit, 0, 1, color=initcolor, lw=1, clip_path=TransformedPatchPath(self.track)) handleXY = [[0.5], [valinit]] else: self.track = Rectangle((0, 0.25), 1, 0.5, transform=ax.transAxes, facecolor=track_color) ax.add_patch(self.track) self.poly = ax.axvspan(valmin, valinit, 0.25, 0.75, **kwargs) self.vline = ax.axvline(valinit, 0, 1, color=initcolor, lw=1, clip_path=TransformedPatchPath(self.track)) handleXY = [[valinit], [0.5]] (self._handle,) = ax.plot(*handleXY, 'o', **marker_props, clip_on=False) if orientation == 'vertical': self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes, verticalalignment='bottom', horizontalalignment='center') self.valtext = ax.text(0.5, -0.02, self._format(valinit), transform=ax.transAxes, verticalalignment='top', horizontalalignment='center') else: self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.valtext = ax.text(1.02, 0.5, self._format(valinit), transform=ax.transAxes, verticalalignment='center', horizontalalignment='left') self.set_val(valinit) def _value_in_bounds(self, val): val = self._stepped_value(val) if val <= self.valmin: if not self.closedmin: return val = self.valmin elif val >= self.valmax: if not self.closedmax: return val = self.valmax if self.slidermin is not None and val <= self.slidermin.val: if not self.closedmin: return val = self.slidermin.val if self.slidermax is not None and val >= self.slidermax.val: if not self.closedmax: return val = self.slidermax.val return val def _update(self, event): if self.ignore(event) or event.button != 1: return if event.name == 'button_press_event' and self.ax.contains(event)[0]: self.drag_active = True event.canvas.grab_mouse(self.ax) if not self.drag_active: return if event.name == 'button_release_event' or (event.name == 'button_press_event' and (not self.ax.contains(event)[0])): self.drag_active = False event.canvas.release_mouse(self.ax) return (xdata, ydata) = self._get_data_coords(event) val = self._value_in_bounds(xdata if self.orientation == 'horizontal' else ydata) if val not in [None, self.val]: self.set_val(val) def _format(self, val): if self.valfmt is not None: return self.valfmt % val else: (_, s, _) = self._fmt.format_ticks([self.valmin, val, self.valmax]) return s + self._fmt.get_offset() def set_val(self, val): if self.orientation == 'vertical': self.poly.set_height(val - self.poly.get_y()) self._handle.set_ydata([val]) else: self.poly.set_width(val - self.poly.get_x()) self._handle.set_xdata([val]) self.valtext.set_text(self._format(val)) if self.drawon: self.ax.get_figure(root=True).canvas.draw_idle() self.val = val if self.eventson: self._observers.process('changed', val) def on_changed(self, func): return self._observers.connect('changed', lambda val: func(val)) class RangeSlider(SliderBase): def __init__(self, ax, label, valmin, valmax, *, valinit=None, valfmt=None, closedmin=True, closedmax=True, dragging=True, valstep=None, orientation='horizontal', track_color='lightgrey', handle_style=None, **kwargs): super().__init__(ax, orientation, closedmin, closedmax, valmin, valmax, valfmt, dragging, valstep) self.val = (valmin, valmax) if valinit is None: extent = valmax - valmin valinit = np.array([valmin + extent * 0.25, valmin + extent * 0.75]) else: valinit = self._value_in_bounds(valinit) self.val = valinit self.valinit = valinit defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10} handle_style = {} if handle_style is None else handle_style marker_props = {f'marker{k}': v for (k, v) in {**defaults, **handle_style}.items()} if orientation == 'vertical': self.track = Rectangle((0.25, 0), 0.5, 2, transform=ax.transAxes, facecolor=track_color) ax.add_patch(self.track) poly_transform = self.ax.get_yaxis_transform(which='grid') handleXY_1 = [0.5, valinit[0]] handleXY_2 = [0.5, valinit[1]] else: self.track = Rectangle((0, 0.25), 1, 0.5, transform=ax.transAxes, facecolor=track_color) ax.add_patch(self.track) poly_transform = self.ax.get_xaxis_transform(which='grid') handleXY_1 = [valinit[0], 0.5] handleXY_2 = [valinit[1], 0.5] self.poly = Polygon(np.zeros([5, 2]), **kwargs) self._update_selection_poly(*valinit) self.poly.set_transform(poly_transform) self.poly.get_path()._interpolation_steps = 100 self.ax.add_patch(self.poly) self.ax._request_autoscale_view() self._handles = [ax.plot(*handleXY_1, 'o', **marker_props, clip_on=False)[0], ax.plot(*handleXY_2, 'o', **marker_props, clip_on=False)[0]] if orientation == 'vertical': self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes, verticalalignment='bottom', horizontalalignment='center') self.valtext = ax.text(0.5, -0.02, self._format(valinit), transform=ax.transAxes, verticalalignment='top', horizontalalignment='center') else: self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.valtext = ax.text(1.02, 0.5, self._format(valinit), transform=ax.transAxes, verticalalignment='center', horizontalalignment='left') self._active_handle = None self.set_val(valinit) def _update_selection_poly(self, vmin, vmax): verts = self.poly.xy if self.orientation == 'vertical': verts[0] = verts[4] = (0.25, vmin) verts[1] = (0.25, vmax) verts[2] = (0.75, vmax) verts[3] = (0.75, vmin) else: verts[0] = verts[4] = (vmin, 0.25) verts[1] = (vmin, 0.75) verts[2] = (vmax, 0.75) verts[3] = (vmax, 0.25) def _min_in_bounds(self, min): if min <= self.valmin: if not self.closedmin: return self.val[0] min = self.valmin if min > self.val[1]: min = self.val[1] return self._stepped_value(min) def _max_in_bounds(self, max): if max >= self.valmax: if not self.closedmax: return self.val[1] max = self.valmax if max <= self.val[0]: max = self.val[0] return self._stepped_value(max) def _value_in_bounds(self, vals): return (self._min_in_bounds(vals[0]), self._max_in_bounds(vals[1])) def _update_val_from_pos(self, pos): idx = np.argmin(np.abs(self.val - pos)) if idx == 0: val = self._min_in_bounds(pos) self.set_min(val) else: val = self._max_in_bounds(pos) self.set_max(val) if self._active_handle: if self.orientation == 'vertical': self._active_handle.set_ydata([val]) else: self._active_handle.set_xdata([val]) def _update(self, event): if self.ignore(event) or event.button != 1: return if event.name == 'button_press_event' and self.ax.contains(event)[0]: self.drag_active = True event.canvas.grab_mouse(self.ax) if not self.drag_active: return if event.name == 'button_release_event' or (event.name == 'button_press_event' and (not self.ax.contains(event)[0])): self.drag_active = False event.canvas.release_mouse(self.ax) self._active_handle = None return (xdata, ydata) = self._get_data_coords(event) handle_index = np.argmin(np.abs([h.get_xdata()[0] - xdata for h in self._handles] if self.orientation == 'horizontal' else [h.get_ydata()[0] - ydata for h in self._handles])) handle = self._handles[handle_index] if handle is not self._active_handle: self._active_handle = handle self._update_val_from_pos(xdata if self.orientation == 'horizontal' else ydata) def _format(self, val): if self.valfmt is not None: return f'({self.valfmt % val[0]}, {self.valfmt % val[1]})' else: (_, s1, s2, _) = self._fmt.format_ticks([self.valmin, *val, self.valmax]) s1 += self._fmt.get_offset() s2 += self._fmt.get_offset() return f'({s1}, {s2})' def set_min(self, min): self.set_val((min, self.val[1])) def set_max(self, max): self.set_val((self.val[0], max)) def set_val(self, val): val = np.sort(val) _api.check_shape((2,), val=val) self.val = (self.valmin, self.valmax) (vmin, vmax) = self._value_in_bounds(val) self._update_selection_poly(vmin, vmax) if self.orientation == 'vertical': self._handles[0].set_ydata([vmin]) self._handles[1].set_ydata([vmax]) else: self._handles[0].set_xdata([vmin]) self._handles[1].set_xdata([vmax]) self.valtext.set_text(self._format((vmin, vmax))) if self.drawon: self.ax.get_figure(root=True).canvas.draw_idle() self.val = (vmin, vmax) if self.eventson: self._observers.process('changed', (vmin, vmax)) def on_changed(self, func): return self._observers.connect('changed', lambda val: func(val)) def _expand_text_props(props): props = cbook.normalize_kwargs(props, mtext.Text) return cycler(**props)() if props else itertools.repeat({}) class CheckButtons(AxesWidget): def __init__(self, ax, labels, actives=None, *, useblit=True, label_props=None, frame_props=None, check_props=None): super().__init__(ax) _api.check_isinstance((dict, None), label_props=label_props, frame_props=frame_props, check_props=check_props) ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if actives is None: actives = [False] * len(labels) self._useblit = useblit and self.canvas.supports_blit self._background = None ys = np.linspace(1, 0, len(labels) + 2)[1:-1] label_props = _expand_text_props(label_props) self.labels = [ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center', **props) for (y, label, props) in zip(ys, labels, label_props)] text_size = np.array([text.get_fontsize() for text in self.labels]) / 2 frame_props = {'s': text_size ** 2, 'linewidth': 1, **cbook.normalize_kwargs(frame_props, collections.PathCollection), 'marker': 's', 'transform': ax.transAxes} frame_props.setdefault('facecolor', frame_props.get('color', 'none')) frame_props.setdefault('edgecolor', frame_props.pop('color', 'black')) self._frames = ax.scatter([0.15] * len(ys), ys, **frame_props) check_props = {'linewidth': 1, 's': text_size ** 2, **cbook.normalize_kwargs(check_props, collections.PathCollection), 'marker': 'x', 'transform': ax.transAxes, 'animated': self._useblit} check_props.setdefault('facecolor', check_props.pop('color', 'black')) self._checks = ax.scatter([0.15] * len(ys), ys, **check_props) self._init_status(actives) self.connect_event('button_press_event', self._clicked) if self._useblit: self.connect_event('draw_event', self._clear) self._observers = cbook.CallbackRegistry(signals=['clicked']) def _clear(self, event): if self.ignore(event) or self.canvas.is_saving(): return self._background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self._checks) def _clicked(self, event): if self.ignore(event) or event.button != 1 or (not self.ax.contains(event)[0]): return idxs = [*self._frames.contains(event)[1]['ind'], *[i for (i, text) in enumerate(self.labels) if text.contains(event)[0]]] if idxs: coords = self._frames.get_offset_transform().transform(self._frames.get_offsets()) self.set_active(idxs[(((event.x, event.y) - coords[idxs]) ** 2).sum(-1).argmin()]) def set_label_props(self, props): _api.check_isinstance(dict, props=props) props = _expand_text_props(props) for (text, prop) in zip(self.labels, props): text.update(prop) def set_frame_props(self, props): _api.check_isinstance(dict, props=props) if 's' in props: props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels)) self._frames.update(props) def set_check_props(self, props): _api.check_isinstance(dict, props=props) if 's' in props: props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels)) actives = self.get_status() self._checks.update(props) self._init_status(actives) def set_active(self, index, state=None): if index not in range(len(self.labels)): raise ValueError(f'Invalid CheckButton index: {index}') _api.check_isinstance((bool, None), state=state) invisible = colors.to_rgba('none') facecolors = self._checks.get_facecolor() if state is None: state = colors.same_color(facecolors[index], invisible) facecolors[index] = self._active_check_colors[index] if state else invisible self._checks.set_facecolor(facecolors) if self.drawon: if self._useblit: if self._background is not None: self.canvas.restore_region(self._background) self.ax.draw_artist(self._checks) self.canvas.blit(self.ax.bbox) else: self.canvas.draw() if self.eventson: self._observers.process('clicked', self.labels[index].get_text()) def _init_status(self, actives): self._active_check_colors = self._checks.get_facecolor() if len(self._active_check_colors) == 1: self._active_check_colors = np.repeat(self._active_check_colors, len(actives), axis=0) self._checks.set_facecolor([ec if active else 'none' for (ec, active) in zip(self._active_check_colors, actives)]) def clear(self): self._checks.set_facecolor(['none'] * len(self._active_check_colors)) if hasattr(self, '_lines'): for (l1, l2) in self._lines: l1.set_visible(False) l2.set_visible(False) if self.drawon: self.canvas.draw() if self.eventson: self._observers.process('clicked', None) def get_status(self): return [not colors.same_color(color, colors.to_rgba('none')) for color in self._checks.get_facecolors()] def get_checked_labels(self): return [l.get_text() for (l, box_checked) in zip(self.labels, self.get_status()) if box_checked] def on_clicked(self, func): return self._observers.connect('clicked', lambda text: func(text)) def disconnect(self, cid): self._observers.disconnect(cid) class TextBox(AxesWidget): def __init__(self, ax, label, initial='', *, color='.95', hovercolor='1', label_pad=0.01, textalignment='left'): super().__init__(ax) self._text_position = _api.check_getitem({'left': 0.05, 'center': 0.5, 'right': 0.95}, textalignment=textalignment) self.label = ax.text(-label_pad, 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.text_disp = self.ax.text(self._text_position, 0.5, initial, transform=self.ax.transAxes, verticalalignment='center', horizontalalignment=textalignment, parse_math=False) self._observers = cbook.CallbackRegistry(signals=['change', 'submit']) ax.set(xlim=(0, 1), ylim=(0, 1), navigate=False, facecolor=color, xticks=[], yticks=[]) self.cursor_index = 0 self.cursor = ax.vlines(0, 0, 0, visible=False, color='k', lw=1, transform=mpl.transforms.IdentityTransform()) self.connect_event('button_press_event', self._click) self.connect_event('button_release_event', self._release) self.connect_event('motion_notify_event', self._motion) self.connect_event('key_press_event', self._keypress) self.connect_event('resize_event', self._resize) self.color = color self.hovercolor = hovercolor self.capturekeystrokes = False @property def text(self): return self.text_disp.get_text() def _rendercursor(self): fig = self.ax.get_figure(root=True) if fig._get_renderer() is None: fig.canvas.draw() text = self.text_disp.get_text() widthtext = text[:self.cursor_index] bb_text = self.text_disp.get_window_extent() self.text_disp.set_text(widthtext or ',') bb_widthtext = self.text_disp.get_window_extent() if bb_text.y0 == bb_text.y1: bb_text.y0 -= bb_widthtext.height / 2 bb_text.y1 += bb_widthtext.height / 2 elif not widthtext: bb_text.x1 = bb_text.x0 else: bb_text.x1 = bb_text.x0 + bb_widthtext.width self.cursor.set(segments=[[(bb_text.x1, bb_text.y0), (bb_text.x1, bb_text.y1)]], visible=True) self.text_disp.set_text(text) fig.canvas.draw() def _release(self, event): if self.ignore(event): return if event.canvas.mouse_grabber != self.ax: return event.canvas.release_mouse(self.ax) def _keypress(self, event): if self.ignore(event): return if self.capturekeystrokes: key = event.key text = self.text if len(key) == 1: text = text[:self.cursor_index] + key + text[self.cursor_index:] self.cursor_index += 1 elif key == 'right': if self.cursor_index != len(text): self.cursor_index += 1 elif key == 'left': if self.cursor_index != 0: self.cursor_index -= 1 elif key == 'home': self.cursor_index = 0 elif key == 'end': self.cursor_index = len(text) elif key == 'backspace': if self.cursor_index != 0: text = text[:self.cursor_index - 1] + text[self.cursor_index:] self.cursor_index -= 1 elif key == 'delete': if self.cursor_index != len(self.text): text = text[:self.cursor_index] + text[self.cursor_index + 1:] self.text_disp.set_text(text) self._rendercursor() if self.eventson: self._observers.process('change', self.text) if key in ['enter', 'return']: self._observers.process('submit', self.text) def set_val(self, val): newval = str(val) if self.text == newval: return self.text_disp.set_text(newval) self._rendercursor() if self.eventson: self._observers.process('change', self.text) self._observers.process('submit', self.text) def begin_typing(self): self.capturekeystrokes = True stack = ExitStack() self._on_stop_typing = stack.close toolmanager = getattr(self.ax.get_figure(root=True).canvas.manager, 'toolmanager', None) if toolmanager is not None: toolmanager.keypresslock(self) stack.callback(toolmanager.keypresslock.release, self) else: with _api.suppress_matplotlib_deprecation_warning(): stack.enter_context(mpl.rc_context({k: [] for k in mpl.rcParams if k.startswith('keymap.')})) def stop_typing(self): if self.capturekeystrokes: self._on_stop_typing() self._on_stop_typing = None notifysubmit = True else: notifysubmit = False self.capturekeystrokes = False self.cursor.set_visible(False) self.ax.get_figure(root=True).canvas.draw() if notifysubmit and self.eventson: self._observers.process('submit', self.text) def _click(self, event): if self.ignore(event): return if not self.ax.contains(event)[0]: self.stop_typing() return if not self.eventson: return if event.canvas.mouse_grabber != self.ax: event.canvas.grab_mouse(self.ax) if not self.capturekeystrokes: self.begin_typing() self.cursor_index = self.text_disp._char_index_at(event.x) self._rendercursor() def _resize(self, event): self.stop_typing() def _motion(self, event): if self.ignore(event): return c = self.hovercolor if self.ax.contains(event)[0] else self.color if not colors.same_color(c, self.ax.get_facecolor()): self.ax.set_facecolor(c) if self.drawon: self.ax.get_figure(root=True).canvas.draw() def on_text_change(self, func): return self._observers.connect('change', lambda text: func(text)) def on_submit(self, func): return self._observers.connect('submit', lambda text: func(text)) def disconnect(self, cid): self._observers.disconnect(cid) class RadioButtons(AxesWidget): def __init__(self, ax, labels, active=0, activecolor=None, *, useblit=True, label_props=None, radio_props=None): super().__init__(ax) _api.check_isinstance((dict, None), label_props=label_props, radio_props=radio_props) radio_props = cbook.normalize_kwargs(radio_props, collections.PathCollection) if activecolor is not None: if 'facecolor' in radio_props: _api.warn_external('Both the *activecolor* parameter and the *facecolor* key in the *radio_props* parameter has been specified. *activecolor* will be ignored.') else: activecolor = 'blue' self._activecolor = activecolor self._initial_active = active self.value_selected = labels[active] self.index_selected = active ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) ys = np.linspace(1, 0, len(labels) + 2)[1:-1] self._useblit = useblit and self.canvas.supports_blit self._background = None label_props = _expand_text_props(label_props) self.labels = [ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center', **props) for (y, label, props) in zip(ys, labels, label_props)] text_size = np.array([text.get_fontsize() for text in self.labels]) / 2 radio_props = {'s': text_size ** 2, **radio_props, 'marker': 'o', 'transform': ax.transAxes, 'animated': self._useblit} radio_props.setdefault('edgecolor', radio_props.get('color', 'black')) radio_props.setdefault('facecolor', radio_props.pop('color', activecolor)) self._buttons = ax.scatter([0.15] * len(ys), ys, **radio_props) self._active_colors = self._buttons.get_facecolor() if len(self._active_colors) == 1: self._active_colors = np.repeat(self._active_colors, len(labels), axis=0) self._buttons.set_facecolor([activecolor if i == active else 'none' for (i, activecolor) in enumerate(self._active_colors)]) self.connect_event('button_press_event', self._clicked) if self._useblit: self.connect_event('draw_event', self._clear) self._observers = cbook.CallbackRegistry(signals=['clicked']) def _clear(self, event): if self.ignore(event) or self.canvas.is_saving(): return self._background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self._buttons) def _clicked(self, event): if self.ignore(event) or event.button != 1 or (not self.ax.contains(event)[0]): return idxs = [*self._buttons.contains(event)[1]['ind'], *[i for (i, text) in enumerate(self.labels) if text.contains(event)[0]]] if idxs: coords = self._buttons.get_offset_transform().transform(self._buttons.get_offsets()) self.set_active(idxs[(((event.x, event.y) - coords[idxs]) ** 2).sum(-1).argmin()]) def set_label_props(self, props): _api.check_isinstance(dict, props=props) props = _expand_text_props(props) for (text, prop) in zip(self.labels, props): text.update(prop) def set_radio_props(self, props): _api.check_isinstance(dict, props=props) if 's' in props: props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels)) self._buttons.update(props) self._active_colors = self._buttons.get_facecolor() if len(self._active_colors) == 1: self._active_colors = np.repeat(self._active_colors, len(self.labels), axis=0) self._buttons.set_facecolor([activecolor if text.get_text() == self.value_selected else 'none' for (text, activecolor) in zip(self.labels, self._active_colors)]) @property def activecolor(self): return self._activecolor @activecolor.setter def activecolor(self, activecolor): colors._check_color_like(activecolor=activecolor) self._activecolor = activecolor self.set_radio_props({'facecolor': activecolor}) def set_active(self, index): if index not in range(len(self.labels)): raise ValueError(f'Invalid RadioButton index: {index}') self.value_selected = self.labels[index].get_text() self.index_selected = index button_facecolors = self._buttons.get_facecolor() button_facecolors[:] = colors.to_rgba('none') button_facecolors[index] = colors.to_rgba(self._active_colors[index]) self._buttons.set_facecolor(button_facecolors) if self.drawon: if self._useblit: if self._background is not None: self.canvas.restore_region(self._background) self.ax.draw_artist(self._buttons) self.canvas.blit(self.ax.bbox) else: self.canvas.draw() if self.eventson: self._observers.process('clicked', self.labels[index].get_text()) def clear(self): self.set_active(self._initial_active) def on_clicked(self, func): return self._observers.connect('clicked', func) def disconnect(self, cid): self._observers.disconnect(cid) class SubplotTool(Widget): def __init__(self, targetfig, toolfig): self.figure = toolfig self.targetfig = targetfig toolfig.subplots_adjust(left=0.2, right=0.9) toolfig.suptitle('Click on slider to adjust subplot param') self._sliders = [] names = ['left', 'bottom', 'right', 'top', 'wspace', 'hspace'] for (name, ax) in zip(names, toolfig.subplots(len(names) + 1)): ax.set_navigate(False) slider = Slider(ax, name, 0, 1, valinit=getattr(targetfig.subplotpars, name)) slider.on_changed(self._on_slider_changed) self._sliders.append(slider) toolfig.axes[-1].remove() (self.sliderleft, self.sliderbottom, self.sliderright, self.slidertop, self.sliderwspace, self.sliderhspace) = self._sliders for slider in [self.sliderleft, self.sliderbottom, self.sliderwspace, self.sliderhspace]: slider.closedmax = False for slider in [self.sliderright, self.slidertop]: slider.closedmin = False self.sliderleft.slidermax = self.sliderright self.sliderright.slidermin = self.sliderleft self.sliderbottom.slidermax = self.slidertop self.slidertop.slidermin = self.sliderbottom bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075]) self.buttonreset = Button(bax, 'Reset') self.buttonreset.on_clicked(self._on_reset) def _on_slider_changed(self, _): self.targetfig.subplots_adjust(**{slider.label.get_text(): slider.val for slider in self._sliders}) if self.drawon: self.targetfig.canvas.draw() def _on_reset(self, event): with ExitStack() as stack: stack.enter_context(cbook._setattr_cm(self, drawon=False)) for slider in self._sliders: stack.enter_context(cbook._setattr_cm(slider, drawon=False, eventson=False)) for slider in self._sliders: slider.reset() if self.drawon: event.canvas.draw() self._on_slider_changed(None) class Cursor(AxesWidget): def __init__(self, ax, *, horizOn=True, vertOn=True, useblit=False, **lineprops): super().__init__(ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.clear) self.visible = True self.horizOn = horizOn self.vertOn = vertOn self.useblit = useblit and self.canvas.supports_blit if self.useblit: lineprops['animated'] = True self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops) self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops) self.background = None self.needclear = False def clear(self, event): if self.ignore(event) or self.canvas.is_saving(): return if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) def onmove(self, event): if self.ignore(event): return if not self.canvas.widgetlock.available(self): return if not self.ax.contains(event)[0]: self.linev.set_visible(False) self.lineh.set_visible(False) if self.needclear: self.canvas.draw() self.needclear = False return self.needclear = True (xdata, ydata) = self._get_data_coords(event) self.linev.set_xdata((xdata, xdata)) self.linev.set_visible(self.visible and self.vertOn) self.lineh.set_ydata((ydata, ydata)) self.lineh.set_visible(self.visible and self.horizOn) if not (self.visible and (self.vertOn or self.horizOn)): return if self.useblit: if self.background is not None: self.canvas.restore_region(self.background) self.ax.draw_artist(self.linev) self.ax.draw_artist(self.lineh) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() class MultiCursor(Widget): def __init__(self, canvas, axes, *, useblit=True, horizOn=False, vertOn=True, **lineprops): self._canvas = canvas self.axes = axes self.horizOn = horizOn self.vertOn = vertOn self._canvas_infos = {ax.get_figure(root=True).canvas: {'cids': [], 'background': None} for ax in axes} (xmin, xmax) = axes[-1].get_xlim() (ymin, ymax) = axes[-1].get_ylim() xmid = 0.5 * (xmin + xmax) ymid = 0.5 * (ymin + ymax) self.visible = True self.useblit = useblit and all((canvas.supports_blit for canvas in self._canvas_infos)) if self.useblit: lineprops['animated'] = True self.vlines = [ax.axvline(xmid, visible=False, **lineprops) for ax in axes] self.hlines = [ax.axhline(ymid, visible=False, **lineprops) for ax in axes] self.connect() def connect(self): for (canvas, info) in self._canvas_infos.items(): info['cids'] = [canvas.mpl_connect('motion_notify_event', self.onmove), canvas.mpl_connect('draw_event', self.clear)] def disconnect(self): for (canvas, info) in self._canvas_infos.items(): for cid in info['cids']: canvas.mpl_disconnect(cid) info['cids'].clear() def clear(self, event): if self.ignore(event): return if self.useblit: for (canvas, info) in self._canvas_infos.items(): if canvas is not canvas.figure.canvas: continue info['background'] = canvas.copy_from_bbox(canvas.figure.bbox) def onmove(self, event): axs = [ax for ax in self.axes if ax.contains(event)[0]] if self.ignore(event) or not axs or (not event.canvas.widgetlock.available(self)): return ax = cbook._topmost_artist(axs) (xdata, ydata) = (event.xdata, event.ydata) if event.inaxes is ax else ax.transData.inverted().transform((event.x, event.y)) for line in self.vlines: line.set_xdata((xdata, xdata)) line.set_visible(self.visible and self.vertOn) for line in self.hlines: line.set_ydata((ydata, ydata)) line.set_visible(self.visible and self.horizOn) if not (self.visible and (self.vertOn or self.horizOn)): return if self.useblit: for (canvas, info) in self._canvas_infos.items(): if info['background']: canvas.restore_region(info['background']) if self.vertOn: for (ax, line) in zip(self.axes, self.vlines): ax.draw_artist(line) if self.horizOn: for (ax, line) in zip(self.axes, self.hlines): ax.draw_artist(line) for canvas in self._canvas_infos: canvas.blit() else: for canvas in self._canvas_infos: canvas.draw_idle() class _SelectorWidget(AxesWidget): def __init__(self, ax, onselect, useblit=False, button=None, state_modifier_keys=None, use_data_coordinates=False): super().__init__(ax) self._visible = True self.onselect = onselect self.useblit = useblit and self.canvas.supports_blit self.connect_default_events() self._state_modifier_keys = dict(move=' ', clear='escape', square='shift', center='control', rotate='r') self._state_modifier_keys.update(state_modifier_keys or {}) self._use_data_coordinates = use_data_coordinates self.background = None if isinstance(button, Integral): self.validButtons = [button] else: self.validButtons = button self._selection_completed = False self._eventpress = None self._eventrelease = None self._prev_event = None self._state = set() def set_active(self, active): super().set_active(active) if active: self.update_background(None) def _get_animated_artists(self): return tuple((a for ax_ in self.ax.get_figure().get_axes() for a in ax_.get_children() if a.get_animated() and a not in self.artists)) def update_background(self, event): if not self.useblit: return artists = sorted(self.artists + self._get_animated_artists(), key=lambda a: a.get_zorder()) needs_redraw = any((artist.get_visible() for artist in artists)) with ExitStack() as stack: if needs_redraw: for artist in artists: stack.enter_context(artist._cm_set(visible=False)) self.canvas.draw() self.background = self.canvas.copy_from_bbox(self.ax.bbox) if needs_redraw: for artist in artists: self.ax.draw_artist(artist) def connect_default_events(self): self.connect_event('motion_notify_event', self.onmove) self.connect_event('button_press_event', self.press) self.connect_event('button_release_event', self.release) self.connect_event('draw_event', self.update_background) self.connect_event('key_press_event', self.on_key_press) self.connect_event('key_release_event', self.on_key_release) self.connect_event('scroll_event', self.on_scroll) def ignore(self, event): if not self.active or not self.ax.get_visible(): return True if not self.canvas.widgetlock.available(self): return True if not hasattr(event, 'button'): event.button = None if self.validButtons is not None and event.button not in self.validButtons: return True if self._eventpress is None: return not self.ax.contains(event)[0] if event.button == self._eventpress.button: return False return not self.ax.contains(event)[0] or event.button != self._eventpress.button def update(self): if not self.ax.get_visible() or self.ax.get_figure(root=True)._get_renderer() is None: return if self.useblit: if self.background is not None: self.canvas.restore_region(self.background) else: self.update_background(None) artists = sorted(self.artists + self._get_animated_artists(), key=lambda a: a.get_zorder()) for artist in artists: self.ax.draw_artist(artist) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() def _get_data(self, event): if event.xdata is None: return (None, None) (xdata, ydata) = self._get_data_coords(event) xdata = np.clip(xdata, *self.ax.get_xbound()) ydata = np.clip(ydata, *self.ax.get_ybound()) return (xdata, ydata) def _clean_event(self, event): if event.xdata is None: event = self._prev_event else: event = copy.copy(event) (event.xdata, event.ydata) = self._get_data(event) self._prev_event = event return event def press(self, event): if not self.ignore(event): event = self._clean_event(event) self._eventpress = event self._prev_event = event key = event.key or '' key = key.replace('ctrl', 'control') if key == self._state_modifier_keys['move']: self._state.add('move') self._press(event) return True return False def _press(self, event): def release(self, event): if not self.ignore(event) and self._eventpress: event = self._clean_event(event) self._eventrelease = event self._release(event) self._eventpress = None self._eventrelease = None self._state.discard('move') return True return False def _release(self, event): def onmove(self, event): if not self.ignore(event) and self._eventpress: event = self._clean_event(event) self._onmove(event) return True return False def _onmove(self, event): def on_scroll(self, event): if not self.ignore(event): self._on_scroll(event) def _on_scroll(self, event): def on_key_press(self, event): if self.active: key = event.key or '' key = key.replace('ctrl', 'control') if key == self._state_modifier_keys['clear']: self.clear() return for (state, modifier) in self._state_modifier_keys.items(): if modifier in key.split('+'): if state == 'rotate': if state in self._state: self._state.discard(state) else: self._state.add(state) else: self._state.add(state) self._on_key_press(event) def _on_key_press(self, event): def on_key_release(self, event): if self.active: key = event.key or '' for (state, modifier) in self._state_modifier_keys.items(): if modifier in key.split('+') and state != 'rotate': self._state.discard(state) self._on_key_release(event) def _on_key_release(self, event): def set_visible(self, visible): self._visible = visible for artist in self.artists: artist.set_visible(visible) def get_visible(self): return self._visible @property def visible(self): _api.warn_deprecated('3.8', alternative='get_visible') return self.get_visible() def clear(self): self._clear_without_update() self.update() def _clear_without_update(self): self._selection_completed = False self.set_visible(False) @property def artists(self): handles_artists = getattr(self, '_handles_artists', ()) return (self._selection_artist,) + handles_artists def set_props(self, **props): artist = self._selection_artist props = cbook.normalize_kwargs(props, artist) artist.set(**props) if self.useblit: self.update() def set_handle_props(self, **handle_props): if not hasattr(self, '_handles_artists'): raise NotImplementedError("This selector doesn't have handles.") artist = self._handles_artists[0] handle_props = cbook.normalize_kwargs(handle_props, artist) for handle in self._handles_artists: handle.set(**handle_props) if self.useblit: self.update() self._handle_props.update(handle_props) def _validate_state(self, state): supported_state = [key for (key, value) in self._state_modifier_keys.items() if key != 'clear' and value != 'not-applicable'] _api.check_in_list(supported_state, state=state) def add_state(self, state): self._validate_state(state) self._state.add(state) def remove_state(self, state): self._validate_state(state) self._state.remove(state) class SpanSelector(_SelectorWidget): def __init__(self, ax, onselect, direction, *, minspan=0, useblit=False, props=None, onmove_callback=None, interactive=False, button=None, handle_props=None, grab_range=10, state_modifier_keys=None, drag_from_anywhere=False, ignore_event_outside=False, snap_values=None): if state_modifier_keys is None: state_modifier_keys = dict(clear='escape', square='not-applicable', center='not-applicable', rotate='not-applicable') super().__init__(ax, onselect, useblit=useblit, button=button, state_modifier_keys=state_modifier_keys) if props is None: props = dict(facecolor='red', alpha=0.5) props['animated'] = self.useblit self.direction = direction self._extents_on_press = None self.snap_values = snap_values self.onmove_callback = onmove_callback self.minspan = minspan self.grab_range = grab_range self._interactive = interactive self._edge_handles = None self.drag_from_anywhere = drag_from_anywhere self.ignore_event_outside = ignore_event_outside self.new_axes(ax, _props=props, _init=True) self._handle_props = {'color': props.get('facecolor', 'r'), **cbook.normalize_kwargs(handle_props, Line2D)} if self._interactive: self._edge_order = ['min', 'max'] self._setup_edge_handles(self._handle_props) self._active_handle = None def new_axes(self, ax, *, _props=None, _init=False): reconnect = False if _init or self.canvas is not ax.get_figure(root=True).canvas: if self.canvas is not None: self.disconnect_events() reconnect = True self.ax = ax if reconnect: self.connect_default_events() self._selection_completed = False if self.direction == 'horizontal': trans = ax.get_xaxis_transform() (w, h) = (0, 1) else: trans = ax.get_yaxis_transform() (w, h) = (1, 0) rect_artist = Rectangle((0, 0), w, h, transform=trans, visible=False) if _props is not None: rect_artist.update(_props) elif self._selection_artist is not None: rect_artist.update_from(self._selection_artist) self.ax.add_patch(rect_artist) self._selection_artist = rect_artist def _setup_edge_handles(self, props): if self.direction == 'horizontal': positions = self.ax.get_xbound() else: positions = self.ax.get_ybound() self._edge_handles = ToolLineHandles(self.ax, positions, direction=self.direction, line_props=props, useblit=self.useblit) @property def _handles_artists(self): if self._edge_handles is not None: return self._edge_handles.artists else: return () def _set_cursor(self, enabled): if enabled: cursor = backend_tools.Cursors.RESIZE_HORIZONTAL if self.direction == 'horizontal' else backend_tools.Cursors.RESIZE_VERTICAL else: cursor = backend_tools.Cursors.POINTER self.ax.get_figure(root=True).canvas.set_cursor(cursor) def connect_default_events(self): super().connect_default_events() if getattr(self, '_interactive', False): self.connect_event('motion_notify_event', self._hover) def _press(self, event): self._set_cursor(True) if self._interactive and self._selection_artist.get_visible(): self._set_active_handle(event) else: self._active_handle = None if self._active_handle is None or not self._interactive: self.update() (xdata, ydata) = self._get_data_coords(event) v = xdata if self.direction == 'horizontal' else ydata if self._active_handle is None and (not self.ignore_event_outside): self._visible = False self._set_extents((v, v)) self._visible = True else: self.set_visible(True) return False @property def direction(self): return self._direction @direction.setter def direction(self, direction): _api.check_in_list(['horizontal', 'vertical'], direction=direction) if hasattr(self, '_direction') and direction != self._direction: self._selection_artist.remove() if self._interactive: self._edge_handles.remove() self._direction = direction self.new_axes(self.ax) if self._interactive: self._setup_edge_handles(self._handle_props) else: self._direction = direction def _release(self, event): self._set_cursor(False) if not self._interactive: self._selection_artist.set_visible(False) if self._active_handle is None and self._selection_completed and self.ignore_event_outside: return (vmin, vmax) = self.extents span = vmax - vmin if span <= self.minspan: self.set_visible(False) if self._selection_completed: self.onselect(vmin, vmax) self._selection_completed = False else: self.onselect(vmin, vmax) self._selection_completed = True self.update() self._active_handle = None return False def _hover(self, event): if self.ignore(event): return if self._active_handle is not None or not self._selection_completed: return (_, e_dist) = self._edge_handles.closest(event.x, event.y) self._set_cursor(e_dist <= self.grab_range) def _onmove(self, event): (xdata, ydata) = self._get_data_coords(event) if self.direction == 'horizontal': v = xdata vpress = self._eventpress.xdata else: v = ydata vpress = self._eventpress.ydata if self._active_handle == 'C' and self._extents_on_press is not None: (vmin, vmax) = self._extents_on_press dv = v - vpress vmin += dv vmax += dv elif self._active_handle and self._active_handle != 'C': (vmin, vmax) = self._extents_on_press if self._active_handle == 'min': vmin = v else: vmax = v else: if self.ignore_event_outside and self._selection_completed: return (vmin, vmax) = (vpress, v) if vmin > vmax: (vmin, vmax) = (vmax, vmin) self._set_extents((vmin, vmax)) if self.onmove_callback is not None: self.onmove_callback(vmin, vmax) return False def _draw_shape(self, vmin, vmax): if vmin > vmax: (vmin, vmax) = (vmax, vmin) if self.direction == 'horizontal': self._selection_artist.set_x(vmin) self._selection_artist.set_width(vmax - vmin) else: self._selection_artist.set_y(vmin) self._selection_artist.set_height(vmax - vmin) def _set_active_handle(self, event): (e_idx, e_dist) = self._edge_handles.closest(event.x, event.y) if 'move' in self._state: self._active_handle = 'C' elif e_dist > self.grab_range: self._active_handle = None if self.drag_from_anywhere and self._contains(event): self._active_handle = 'C' self._extents_on_press = self.extents else: self._active_handle = None return else: self._active_handle = self._edge_order[e_idx] self._extents_on_press = self.extents def _contains(self, event): return self._selection_artist.contains(event, radius=0)[0] @staticmethod def _snap(values, snap_values): eps = np.min(np.abs(np.diff(snap_values))) * 1e-12 return tuple((snap_values[np.abs(snap_values - v + np.sign(v) * eps).argmin()] for v in values)) @property def extents(self): if self.direction == 'horizontal': vmin = self._selection_artist.get_x() vmax = vmin + self._selection_artist.get_width() else: vmin = self._selection_artist.get_y() vmax = vmin + self._selection_artist.get_height() return (vmin, vmax) @extents.setter def extents(self, extents): self._set_extents(extents) self._selection_completed = True def _set_extents(self, extents): if self.snap_values is not None: extents = tuple(self._snap(extents, self.snap_values)) self._draw_shape(*extents) if self._interactive: self._edge_handles.set_data(self.extents) self.set_visible(self._visible) self.update() class ToolLineHandles: def __init__(self, ax, positions, direction, *, line_props=None, useblit=True): self.ax = ax _api.check_in_list(['horizontal', 'vertical'], direction=direction) self._direction = direction line_props = {**(line_props if line_props is not None else {}), 'visible': False, 'animated': useblit} line_fun = ax.axvline if self.direction == 'horizontal' else ax.axhline self._artists = [line_fun(p, **line_props) for p in positions] @property def artists(self): return tuple(self._artists) @property def positions(self): method = 'get_xdata' if self.direction == 'horizontal' else 'get_ydata' return [getattr(line, method)()[0] for line in self.artists] @property def direction(self): return self._direction def set_data(self, positions): method = 'set_xdata' if self.direction == 'horizontal' else 'set_ydata' for (line, p) in zip(self.artists, positions): getattr(line, method)([p, p]) def set_visible(self, value): for artist in self.artists: artist.set_visible(value) def set_animated(self, value): for artist in self.artists: artist.set_animated(value) def remove(self): for artist in self._artists: artist.remove() def closest(self, x, y): if self.direction == 'horizontal': p_pts = np.array([self.ax.transData.transform((p, 0))[0] for p in self.positions]) dist = abs(p_pts - x) else: p_pts = np.array([self.ax.transData.transform((0, p))[1] for p in self.positions]) dist = abs(p_pts - y) index = np.argmin(dist) return (index, dist[index]) class ToolHandles: def __init__(self, ax, x, y, *, marker='o', marker_props=None, useblit=True): self.ax = ax props = {'marker': marker, 'markersize': 7, 'markerfacecolor': 'w', 'linestyle': 'none', 'alpha': 0.5, 'visible': False, 'label': '_nolegend_', **cbook.normalize_kwargs(marker_props, Line2D._alias_map)} self._markers = Line2D(x, y, animated=useblit, **props) self.ax.add_line(self._markers) @property def x(self): return self._markers.get_xdata() @property def y(self): return self._markers.get_ydata() @property def artists(self): return (self._markers,) def set_data(self, pts, y=None): if y is not None: x = pts pts = np.array([x, y]) self._markers.set_data(pts) def set_visible(self, val): self._markers.set_visible(val) def set_animated(self, val): self._markers.set_animated(val) def closest(self, x, y): pts = np.column_stack([self.x, self.y]) pts = self.ax.transData.transform(pts) diff = pts - [x, y] dist = np.hypot(*diff.T) min_index = np.argmin(dist) return (min_index, dist[min_index]) _RECTANGLESELECTOR_PARAMETERS_DOCSTRING = '\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n The parent Axes for the widget.\n\n onselect : function\n A callback function that is called after a release event and the\n selection is created, changed or removed.\n It must have the signature::\n\n def onselect(eclick: MouseEvent, erelease: MouseEvent)\n\n where *eclick* and *erelease* are the mouse click and release\n `.MouseEvent`\\s that start and complete the selection.\n\n minspanx : float, default: 0\n Selections with an x-span less than or equal to *minspanx* are removed\n (when already existing) or cancelled.\n\n minspany : float, default: 0\n Selections with an y-span less than or equal to *minspanx* are removed\n (when already existing) or cancelled.\n\n useblit : bool, default: False\n Whether to use blitting for faster drawing (if supported by the\n backend). See the tutorial :ref:`blitting`\n for details.\n\n props : dict, optional\n Properties with which the __ARTIST_NAME__ is drawn. See\n `.Patch` for valid properties.\n Default:\n\n ``dict(facecolor=\'red\', edgecolor=\'black\', alpha=0.2, fill=True)``\n\n spancoords : {"data", "pixels"}, default: "data"\n Whether to interpret *minspanx* and *minspany* in data or in pixel\n coordinates.\n\n button : `.MouseButton`, list of `.MouseButton`, default: all buttons\n Button(s) that trigger rectangle selection.\n\n grab_range : float, default: 10\n Distance in pixels within which the interactive tool handles can be\n activated.\n\n handle_props : dict, optional\n Properties with which the interactive handles (marker artists) are\n drawn. See the marker arguments in `.Line2D` for valid\n properties. Default values are defined in ``mpl.rcParams`` except for\n the default value of ``markeredgecolor`` which will be the same as the\n ``edgecolor`` property in *props*.\n\n interactive : bool, default: False\n Whether to draw a set of handles that allow interaction with the\n widget after it is drawn.\n\n state_modifier_keys : dict, optional\n Keyboard modifiers which affect the widget\'s behavior. Values\n amend the defaults, which are:\n\n - "move": Move the existing shape, default: no modifier.\n - "clear": Clear the current shape, default: "escape".\n - "square": Make the shape square, default: "shift".\n - "center": change the shape around its center, default: "ctrl".\n - "rotate": Rotate the shape around its center between -45° and 45°,\n default: "r".\n\n "square" and "center" can be combined. The square shape can be defined\n in data or display coordinates as determined by the\n ``use_data_coordinates`` argument specified when creating the selector.\n\n drag_from_anywhere : bool, default: False\n If `True`, the widget can be moved by clicking anywhere within\n its bounds.\n\n ignore_event_outside : bool, default: False\n If `True`, the event triggered outside the span selector will be\n ignored.\n\n use_data_coordinates : bool, default: False\n If `True`, the "square" shape of the selector is defined in\n data coordinates instead of display coordinates.\n ' @_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace('__ARTIST_NAME__', 'rectangle')) class RectangleSelector(_SelectorWidget): def __init__(self, ax, onselect, *, minspanx=0, minspany=0, useblit=False, props=None, spancoords='data', button=None, grab_range=10, handle_props=None, interactive=False, state_modifier_keys=None, drag_from_anywhere=False, ignore_event_outside=False, use_data_coordinates=False): super().__init__(ax, onselect, useblit=useblit, button=button, state_modifier_keys=state_modifier_keys, use_data_coordinates=use_data_coordinates) self._interactive = interactive self.drag_from_anywhere = drag_from_anywhere self.ignore_event_outside = ignore_event_outside self._rotation = 0.0 self._aspect_ratio_correction = 1.0 self._allow_creation = True if props is None: props = dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True) props = {**props, 'animated': self.useblit} self._visible = props.pop('visible', self._visible) to_draw = self._init_shape(**props) self.ax.add_patch(to_draw) self._selection_artist = to_draw self._set_aspect_ratio_correction() self.minspanx = minspanx self.minspany = minspany _api.check_in_list(['data', 'pixels'], spancoords=spancoords) self.spancoords = spancoords self.grab_range = grab_range if self._interactive: self._handle_props = {'markeredgecolor': (props or {}).get('edgecolor', 'black'), **cbook.normalize_kwargs(handle_props, Line2D)} self._corner_order = ['SW', 'SE', 'NE', 'NW'] (xc, yc) = self.corners self._corner_handles = ToolHandles(self.ax, xc, yc, marker_props=self._handle_props, useblit=self.useblit) self._edge_order = ['W', 'S', 'E', 'N'] (xe, ye) = self.edge_centers self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s', marker_props=self._handle_props, useblit=self.useblit) (xc, yc) = self.center self._center_handle = ToolHandles(self.ax, [xc], [yc], marker='s', marker_props=self._handle_props, useblit=self.useblit) self._active_handle = None self._extents_on_press = None @property def _handles_artists(self): return (*self._center_handle.artists, *self._corner_handles.artists, *self._edge_handles.artists) def _init_shape(self, **props): return Rectangle((0, 0), 0, 1, visible=False, rotation_point='center', **props) def _press(self, event): if self._interactive and self._selection_artist.get_visible(): self._set_active_handle(event) else: self._active_handle = None if (self._active_handle is None or not self._interactive) and self._allow_creation: self.update() if self._active_handle is None and (not self.ignore_event_outside) and self._allow_creation: (x, y) = self._get_data_coords(event) self._visible = False self.extents = (x, x, y, y) self._visible = True else: self.set_visible(True) self._extents_on_press = self.extents self._rotation_on_press = self._rotation self._set_aspect_ratio_correction() return False def _release(self, event): if not self._interactive: self._selection_artist.set_visible(False) if self._active_handle is None and self._selection_completed and self.ignore_event_outside: return (x0, x1, y0, y1) = self.extents self._eventpress.xdata = x0 self._eventpress.ydata = y0 xy0 = self.ax.transData.transform([x0, y0]) (self._eventpress.x, self._eventpress.y) = xy0 self._eventrelease.xdata = x1 self._eventrelease.ydata = y1 xy1 = self.ax.transData.transform([x1, y1]) (self._eventrelease.x, self._eventrelease.y) = xy1 if self.spancoords == 'data': spanx = abs(self._eventpress.xdata - self._eventrelease.xdata) spany = abs(self._eventpress.ydata - self._eventrelease.ydata) elif self.spancoords == 'pixels': spanx = abs(self._eventpress.x - self._eventrelease.x) spany = abs(self._eventpress.y - self._eventrelease.y) else: _api.check_in_list(['data', 'pixels'], spancoords=self.spancoords) if spanx <= self.minspanx or spany <= self.minspany: if self._selection_completed: self.onselect(self._eventpress, self._eventrelease) self._clear_without_update() else: self.onselect(self._eventpress, self._eventrelease) self._selection_completed = True self.update() self._active_handle = None self._extents_on_press = None return False def _onmove(self, event): eventpress = self._eventpress state = self._state rotate = 'rotate' in state and self._active_handle in self._corner_order move = self._active_handle == 'C' resize = self._active_handle and (not move) (xdata, ydata) = self._get_data_coords(event) if resize: inv_tr = self._get_rotation_transform().inverted() (xdata, ydata) = inv_tr.transform([xdata, ydata]) (eventpress.xdata, eventpress.ydata) = inv_tr.transform((eventpress.xdata, eventpress.ydata)) dx = xdata - eventpress.xdata dy = ydata - eventpress.ydata refmax = None if self._use_data_coordinates: (refx, refy) = (dx, dy) else: refx = event.x - eventpress.x refy = event.y - eventpress.y (x0, x1, y0, y1) = self._extents_on_press if rotate: a = (eventpress.xdata, eventpress.ydata) b = self.center c = (xdata, ydata) angle = np.arctan2(c[1] - b[1], c[0] - b[0]) - np.arctan2(a[1] - b[1], a[0] - b[0]) self.rotation = np.rad2deg(self._rotation_on_press + angle) elif resize: size_on_press = [x1 - x0, y1 - y0] center = (x0 + size_on_press[0] / 2, y0 + size_on_press[1] / 2) if 'center' in state: if 'square' in state: if self._active_handle in self._corner_order: refmax = max(refx, refy, key=abs) if self._active_handle in ['E', 'W'] or refmax == refx: hw = xdata - center[0] hh = hw / self._aspect_ratio_correction else: hh = ydata - center[1] hw = hh * self._aspect_ratio_correction else: hw = size_on_press[0] / 2 hh = size_on_press[1] / 2 if self._active_handle in ['E', 'W'] + self._corner_order: hw = abs(xdata - center[0]) if self._active_handle in ['N', 'S'] + self._corner_order: hh = abs(ydata - center[1]) (x0, x1, y0, y1) = (center[0] - hw, center[0] + hw, center[1] - hh, center[1] + hh) else: if 'W' in self._active_handle: x0 = x1 if 'S' in self._active_handle: y0 = y1 if self._active_handle in ['E', 'W'] + self._corner_order: x1 = xdata if self._active_handle in ['N', 'S'] + self._corner_order: y1 = ydata if 'square' in state: if self._active_handle in self._corner_order: refmax = max(refx, refy, key=abs) if self._active_handle in ['E', 'W'] or refmax == refx: sign = np.sign(ydata - y0) y1 = y0 + sign * abs(x1 - x0) / self._aspect_ratio_correction else: sign = np.sign(xdata - x0) x1 = x0 + sign * abs(y1 - y0) * self._aspect_ratio_correction elif move: (x0, x1, y0, y1) = self._extents_on_press dx = xdata - eventpress.xdata dy = ydata - eventpress.ydata x0 += dx x1 += dx y0 += dy y1 += dy else: self._rotation = 0 if self.ignore_event_outside and self._selection_completed or not self._allow_creation: return center = [eventpress.xdata, eventpress.ydata] dx = (xdata - center[0]) / 2 dy = (ydata - center[1]) / 2 if 'square' in state: refmax = max(refx, refy, key=abs) if refmax == refx: dy = np.sign(dy) * abs(dx) / self._aspect_ratio_correction else: dx = np.sign(dx) * abs(dy) * self._aspect_ratio_correction if 'center' in state: dx *= 2 dy *= 2 else: center[0] += dx center[1] += dy (x0, x1, y0, y1) = (center[0] - dx, center[0] + dx, center[1] - dy, center[1] + dy) self.extents = (x0, x1, y0, y1) @property def _rect_bbox(self): return self._selection_artist.get_bbox().bounds def _set_aspect_ratio_correction(self): aspect_ratio = self.ax._get_aspect_ratio() self._selection_artist._aspect_ratio_correction = aspect_ratio if self._use_data_coordinates: self._aspect_ratio_correction = 1 else: self._aspect_ratio_correction = aspect_ratio def _get_rotation_transform(self): aspect_ratio = self.ax._get_aspect_ratio() return Affine2D().translate(-self.center[0], -self.center[1]).scale(1, aspect_ratio).rotate(self._rotation).scale(1, 1 / aspect_ratio).translate(*self.center) @property def corners(self): (x0, y0, width, height) = self._rect_bbox xc = (x0, x0 + width, x0 + width, x0) yc = (y0, y0, y0 + height, y0 + height) transform = self._get_rotation_transform() coords = transform.transform(np.array([xc, yc]).T).T return (coords[0], coords[1]) @property def edge_centers(self): (x0, y0, width, height) = self._rect_bbox w = width / 2.0 h = height / 2.0 xe = (x0, x0 + w, x0 + width, x0 + w) ye = (y0 + h, y0, y0 + h, y0 + height) transform = self._get_rotation_transform() coords = transform.transform(np.array([xe, ye]).T).T return (coords[0], coords[1]) @property def center(self): (x0, y0, width, height) = self._rect_bbox return (x0 + width / 2.0, y0 + height / 2.0) @property def extents(self): (x0, y0, width, height) = self._rect_bbox (xmin, xmax) = sorted([x0, x0 + width]) (ymin, ymax) = sorted([y0, y0 + height]) return (xmin, xmax, ymin, ymax) @extents.setter def extents(self, extents): self._draw_shape(extents) if self._interactive: self._corner_handles.set_data(*self.corners) self._edge_handles.set_data(*self.edge_centers) (x, y) = self.center self._center_handle.set_data([x], [y]) self.set_visible(self._visible) self.update() @property def rotation(self): return np.rad2deg(self._rotation) @rotation.setter def rotation(self, value): if -45 <= value and value <= 45: self._rotation = np.deg2rad(value) self.extents = self.extents def _draw_shape(self, extents): (x0, x1, y0, y1) = extents (xmin, xmax) = sorted([x0, x1]) (ymin, ymax) = sorted([y0, y1]) xlim = sorted(self.ax.get_xlim()) ylim = sorted(self.ax.get_ylim()) xmin = max(xlim[0], xmin) ymin = max(ylim[0], ymin) xmax = min(xmax, xlim[1]) ymax = min(ymax, ylim[1]) self._selection_artist.set_x(xmin) self._selection_artist.set_y(ymin) self._selection_artist.set_width(xmax - xmin) self._selection_artist.set_height(ymax - ymin) self._selection_artist.set_angle(self.rotation) def _set_active_handle(self, event): (c_idx, c_dist) = self._corner_handles.closest(event.x, event.y) (e_idx, e_dist) = self._edge_handles.closest(event.x, event.y) (m_idx, m_dist) = self._center_handle.closest(event.x, event.y) if 'move' in self._state: self._active_handle = 'C' elif m_dist < self.grab_range * 2: self._active_handle = 'C' elif c_dist > self.grab_range and e_dist > self.grab_range: if self.drag_from_anywhere and self._contains(event): self._active_handle = 'C' else: self._active_handle = None return elif c_dist < e_dist: self._active_handle = self._corner_order[c_idx] else: self._active_handle = self._edge_order[e_idx] def _contains(self, event): return self._selection_artist.contains(event, radius=0)[0] @property def geometry(self): if hasattr(self._selection_artist, 'get_verts'): xfm = self.ax.transData.inverted() (y, x) = xfm.transform(self._selection_artist.get_verts()).T return np.array([x, y]) else: return np.array(self._selection_artist.get_data()) @_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace('__ARTIST_NAME__', 'ellipse')) class EllipseSelector(RectangleSelector): def _init_shape(self, **props): return Ellipse((0, 0), 0, 1, visible=False, **props) def _draw_shape(self, extents): (x0, x1, y0, y1) = extents (xmin, xmax) = sorted([x0, x1]) (ymin, ymax) = sorted([y0, y1]) center = [x0 + (x1 - x0) / 2.0, y0 + (y1 - y0) / 2.0] a = (xmax - xmin) / 2.0 b = (ymax - ymin) / 2.0 self._selection_artist.center = center self._selection_artist.width = 2 * a self._selection_artist.height = 2 * b self._selection_artist.angle = self.rotation @property def _rect_bbox(self): (x, y) = self._selection_artist.center width = self._selection_artist.width height = self._selection_artist.height return (x - width / 2.0, y - height / 2.0, width, height) class LassoSelector(_SelectorWidget): def __init__(self, ax, onselect, *, useblit=True, props=None, button=None): super().__init__(ax, onselect, useblit=useblit, button=button) self.verts = None props = {**(props if props is not None else {}), 'animated': self.useblit, 'visible': False} line = Line2D([], [], **props) self.ax.add_line(line) self._selection_artist = line def _press(self, event): self.verts = [self._get_data(event)] self._selection_artist.set_visible(True) def _release(self, event): if self.verts is not None: self.verts.append(self._get_data(event)) self.onselect(self.verts) self._selection_artist.set_data([[], []]) self._selection_artist.set_visible(False) self.verts = None def _onmove(self, event): if self.verts is None: return self.verts.append(self._get_data(event)) self._selection_artist.set_data(list(zip(*self.verts))) self.update() class PolygonSelector(_SelectorWidget): def __init__(self, ax, onselect, *, useblit=False, props=None, handle_props=None, grab_range=10, draw_bounding_box=False, box_handle_props=None, box_props=None): state_modifier_keys = dict(clear='escape', move_vertex='control', move_all='shift', move='not-applicable', square='not-applicable', center='not-applicable', rotate='not-applicable') super().__init__(ax, onselect, useblit=useblit, state_modifier_keys=state_modifier_keys) self._xys = [(0, 0)] if props is None: props = dict(color='k', linestyle='-', linewidth=2, alpha=0.5) props = {**props, 'animated': self.useblit} self._selection_artist = line = Line2D([], [], **props) self.ax.add_line(line) if handle_props is None: handle_props = dict(markeredgecolor='k', markerfacecolor=props.get('color', 'k')) self._handle_props = handle_props self._polygon_handles = ToolHandles(self.ax, [], [], useblit=self.useblit, marker_props=self._handle_props) self._active_handle_idx = -1 self.grab_range = grab_range self.set_visible(True) self._draw_box = draw_bounding_box self._box = None if box_handle_props is None: box_handle_props = {} self._box_handle_props = self._handle_props.update(box_handle_props) self._box_props = box_props def _get_bbox(self): return self._selection_artist.get_bbox() def _add_box(self): self._box = RectangleSelector(self.ax, onselect=lambda *args, **kwargs: None, useblit=self.useblit, grab_range=self.grab_range, handle_props=self._box_handle_props, props=self._box_props, interactive=True) self._box._state_modifier_keys.pop('rotate') self._box.connect_event('motion_notify_event', self._scale_polygon) self._update_box() self._box._allow_creation = False self._box._selection_completed = True self._draw_polygon() def _remove_box(self): if self._box is not None: self._box.set_visible(False) self._box = None def _update_box(self): if self._box is not None: bbox = self._get_bbox() self._box.extents = [bbox.x0, bbox.x1, bbox.y0, bbox.y1] self._old_box_extents = self._box.extents def _scale_polygon(self, event): if not self._selection_completed: return if self._old_box_extents == self._box.extents: return (x1, y1, w1, h1) = self._box._rect_bbox old_bbox = self._get_bbox() t = transforms.Affine2D().translate(-old_bbox.x0, -old_bbox.y0).scale(1 / old_bbox.width, 1 / old_bbox.height).scale(w1, h1).translate(x1, y1) new_verts = [(x, y) for (x, y) in t.transform(np.array(self.verts))] self._xys = [*new_verts, new_verts[0]] self._draw_polygon() self._old_box_extents = self._box.extents @property def _handles_artists(self): return self._polygon_handles.artists def _remove_vertex(self, i): if len(self._xys) > 2 and self._selection_completed and (i in (0, len(self._xys) - 1)): self._xys.pop(0) self._xys.pop(-1) self._xys.append(self._xys[0]) else: self._xys.pop(i) if len(self._xys) <= 2: self._selection_completed = False self._remove_box() def _press(self, event): if (self._selection_completed or 'move_vertex' in self._state) and len(self._xys) > 0: (h_idx, h_dist) = self._polygon_handles.closest(event.x, event.y) if h_dist < self.grab_range: self._active_handle_idx = h_idx self._xys_at_press = self._xys.copy() def _release(self, event): if self._active_handle_idx >= 0: if event.button == 3: self._remove_vertex(self._active_handle_idx) self._draw_polygon() self._active_handle_idx = -1 elif len(self._xys) > 3 and self._xys[-1] == self._xys[0]: self._selection_completed = True if self._draw_box and self._box is None: self._add_box() elif not self._selection_completed and 'move_all' not in self._state and ('move_vertex' not in self._state): self._xys.insert(-1, self._get_data_coords(event)) if self._selection_completed: self.onselect(self.verts) def onmove(self, event): if self.ignore(event): if not self.canvas.widgetlock.available(self) and self._xys: self._xys[-1] = (np.nan, np.nan) self._draw_polygon() return False else: event = self._clean_event(event) self._onmove(event) return True def _onmove(self, event): if self._active_handle_idx >= 0: idx = self._active_handle_idx self._xys[idx] = self._get_data_coords(event) if idx == 0 and self._selection_completed: self._xys[-1] = self._get_data_coords(event) elif 'move_all' in self._state and self._eventpress: (xdata, ydata) = self._get_data_coords(event) dx = xdata - self._eventpress.xdata dy = ydata - self._eventpress.ydata for k in range(len(self._xys)): (x_at_press, y_at_press) = self._xys_at_press[k] self._xys[k] = (x_at_press + dx, y_at_press + dy) elif self._selection_completed or 'move_vertex' in self._state or 'move_all' in self._state: return else: (x0, y0) = self._selection_artist.get_transform().transform(self._xys[0]) v0_dist = np.hypot(x0 - event.x, y0 - event.y) if len(self._xys) > 3 and v0_dist < self.grab_range: self._xys[-1] = self._xys[0] else: self._xys[-1] = self._get_data_coords(event) self._draw_polygon() def _on_key_press(self, event): if not self._selection_completed and ('move_vertex' in self._state or 'move_all' in self._state): self._xys.pop() self._draw_polygon() def _on_key_release(self, event): if not self._selection_completed and (event.key == self._state_modifier_keys.get('move_vertex') or event.key == self._state_modifier_keys.get('move_all')): self._xys.append(self._get_data_coords(event)) self._draw_polygon() elif event.key == self._state_modifier_keys.get('clear'): event = self._clean_event(event) self._xys = [self._get_data_coords(event)] self._selection_completed = False self._remove_box() self.set_visible(True) def _draw_polygon_without_update(self): (xs, ys) = zip(*self._xys) if self._xys else ([], []) self._selection_artist.set_data(xs, ys) self._update_box() if self._selection_completed or (len(self._xys) > 3 and self._xys[-1] == self._xys[0]): self._polygon_handles.set_data(xs[:-1], ys[:-1]) else: self._polygon_handles.set_data(xs, ys) def _draw_polygon(self): self._draw_polygon_without_update() self.update() @property def verts(self): return self._xys[:-1] @verts.setter def verts(self, xys): self._xys = [*xys, xys[0]] self._selection_completed = True self.set_visible(True) if self._draw_box and self._box is None: self._add_box() self._draw_polygon() def _clear_without_update(self): self._selection_completed = False self._xys = [(0, 0)] self._draw_polygon_without_update() class Lasso(AxesWidget): def __init__(self, ax, xy, callback, *, useblit=True, props=None): super().__init__(ax) self.useblit = useblit and self.canvas.supports_blit if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) style = {'linestyle': '-', 'color': 'black', 'lw': 2} if props is not None: style.update(props) (x, y) = xy self.verts = [(x, y)] self.line = Line2D([x], [y], **style) self.ax.add_line(self.line) self.callback = callback self.connect_event('button_release_event', self.onrelease) self.connect_event('motion_notify_event', self.onmove) def onrelease(self, event): if self.ignore(event): return if self.verts is not None: self.verts.append(self._get_data_coords(event)) if len(self.verts) > 2: self.callback(self.verts) self.line.remove() self.verts = None self.disconnect_events() def onmove(self, event): if self.ignore(event) or self.verts is None or event.button != 1 or (not self.ax.contains(event)[0]): return self.verts.append(self._get_data_coords(event)) self.line.set_data(list(zip(*self.verts))) if self.useblit: self.canvas.restore_region(self.background) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/anchored_artists.py from matplotlib import _api, transforms from matplotlib.offsetbox import AnchoredOffsetbox, AuxTransformBox, DrawingArea, TextArea, VPacker from matplotlib.patches import Rectangle, Ellipse, ArrowStyle, FancyArrowPatch, PathPatch from matplotlib.text import TextPath __all__ = ['AnchoredDrawingArea', 'AnchoredAuxTransformBox', 'AnchoredEllipse', 'AnchoredSizeBar', 'AnchoredDirectionArrows'] class AnchoredDrawingArea(AnchoredOffsetbox): def __init__(self, width, height, xdescent, ydescent, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): self.da = DrawingArea(width, height, xdescent, ydescent) self.drawing_area = self.da super().__init__(loc, pad=pad, borderpad=borderpad, child=self.da, prop=None, frameon=frameon, **kwargs) class AnchoredAuxTransformBox(AnchoredOffsetbox): def __init__(self, transform, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): self.drawing_area = AuxTransformBox(transform) super().__init__(loc, pad=pad, borderpad=borderpad, child=self.drawing_area, prop=prop, frameon=frameon, **kwargs) @_api.deprecated('3.8') class AnchoredEllipse(AnchoredOffsetbox): def __init__(self, transform, width, height, angle, loc, pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs): self._box = AuxTransformBox(transform) self.ellipse = Ellipse((0, 0), width, height, angle=angle) self._box.add_artist(self.ellipse) super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box, prop=prop, frameon=frameon, **kwargs) class AnchoredSizeBar(AnchoredOffsetbox): def __init__(self, transform, size, label, loc, pad=0.1, borderpad=0.1, sep=2, frameon=True, size_vertical=0, color='black', label_top=False, fontproperties=None, fill_bar=None, **kwargs): if fill_bar is None: fill_bar = size_vertical > 0 self.size_bar = AuxTransformBox(transform) self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical, fill=fill_bar, facecolor=color, edgecolor=color)) if fontproperties is None and 'prop' in kwargs: fontproperties = kwargs.pop('prop') if fontproperties is None: textprops = {'color': color} else: textprops = {'color': color, 'fontproperties': fontproperties} self.txt_label = TextArea(label, textprops=textprops) if label_top: _box_children = [self.txt_label, self.size_bar] else: _box_children = [self.size_bar, self.txt_label] self._box = VPacker(children=_box_children, align='center', pad=0, sep=sep) super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box, prop=fontproperties, frameon=frameon, **kwargs) class AnchoredDirectionArrows(AnchoredOffsetbox): def __init__(self, transform, label_x, label_y, length=0.15, fontsize=0.08, loc='upper left', angle=0, aspect_ratio=1, pad=0.4, borderpad=0.4, frameon=False, color='w', alpha=1, sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15, head_width=10, head_length=15, tail_width=2, text_props=None, arrow_props=None, **kwargs): if arrow_props is None: arrow_props = {} if text_props is None: text_props = {} arrowstyle = ArrowStyle('Simple', head_width=head_width, head_length=head_length, tail_width=tail_width) if fontproperties is None and 'prop' in kwargs: fontproperties = kwargs.pop('prop') if 'color' not in arrow_props: arrow_props['color'] = color if 'alpha' not in arrow_props: arrow_props['alpha'] = alpha if 'color' not in text_props: text_props['color'] = color if 'alpha' not in text_props: text_props['alpha'] = alpha t_start = transform t_end = t_start + transforms.Affine2D().rotate_deg(angle) self.box = AuxTransformBox(t_end) length_x = length length_y = length * aspect_ratio self.arrow_x = FancyArrowPatch((0, back_length * length_y), (length_x, back_length * length_y), arrowstyle=arrowstyle, shrinkA=0.0, shrinkB=0.0, **arrow_props) self.arrow_y = FancyArrowPatch((back_length * length_x, 0), (back_length * length_x, length_y), arrowstyle=arrowstyle, shrinkA=0.0, shrinkB=0.0, **arrow_props) self.box.add_artist(self.arrow_x) self.box.add_artist(self.arrow_y) text_path_x = TextPath((length_x + sep_x, back_length * length_y + sep_y), label_x, size=fontsize, prop=fontproperties) self.p_x = PathPatch(text_path_x, transform=t_start, **text_props) self.box.add_artist(self.p_x) text_path_y = TextPath((length_x * back_length + sep_x, length_y * (1 - back_length) + sep_y), label_y, size=fontsize, prop=fontproperties) self.p_y = PathPatch(text_path_y, **text_props) self.box.add_artist(self.p_y) super().__init__(loc, pad=pad, borderpad=borderpad, child=self.box, frameon=frameon, **kwargs) # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/axes_divider.py """""" import functools import numpy as np import matplotlib as mpl from matplotlib import _api from matplotlib.gridspec import SubplotSpec import matplotlib.transforms as mtransforms from . import axes_size as Size class Divider: def __init__(self, fig, pos, horizontal, vertical, aspect=None, anchor='C'): self._fig = fig self._pos = pos self._horizontal = horizontal self._vertical = vertical self._anchor = anchor self.set_anchor(anchor) self._aspect = aspect self._xrefindex = 0 self._yrefindex = 0 self._locator = None def get_horizontal_sizes(self, renderer): return np.array([s.get_size(renderer) for s in self.get_horizontal()]) def get_vertical_sizes(self, renderer): return np.array([s.get_size(renderer) for s in self.get_vertical()]) def set_position(self, pos): self._pos = pos def get_position(self): return self._pos def set_anchor(self, anchor): if isinstance(anchor, str): _api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor) elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2: raise TypeError('anchor must be str or 2-tuple') self._anchor = anchor def get_anchor(self): return self._anchor def get_subplotspec(self): return None def set_horizontal(self, h): self._horizontal = h def get_horizontal(self): return self._horizontal def set_vertical(self, v): self._vertical = v def get_vertical(self): return self._vertical def set_aspect(self, aspect=False): self._aspect = aspect def get_aspect(self): return self._aspect def set_locator(self, _locator): self._locator = _locator def get_locator(self): return self._locator def get_position_runtime(self, ax, renderer): if self._locator is None: return self.get_position() else: return self._locator(ax, renderer).bounds @staticmethod def _calc_k(sizes, total): (rel_sum, abs_sum) = sizes.sum(0) return (total - abs_sum) / rel_sum if rel_sum else 0 @staticmethod def _calc_offsets(sizes, k): return np.cumsum([0, *sizes @ [k, 1]]) def new_locator(self, nx, ny, nx1=None, ny1=None): if nx1 is None: nx1 = nx + 1 if ny1 is None: ny1 = ny + 1 xref = self._xrefindex yref = self._yrefindex locator = functools.partial(self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref) locator.get_subplotspec = self.get_subplotspec return locator @_api.deprecated('3.8', alternative='divider.new_locator(...)(ax, renderer)') def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None): xref = self._xrefindex yref = self._yrefindex return self._locate(nx - xref, (nx + 1 if nx1 is None else nx1) - xref, ny - yref, (ny + 1 if ny1 is None else ny1) - yref, axes, renderer) def _locate(self, nx, ny, nx1, ny1, axes, renderer): nx += self._xrefindex nx1 += self._xrefindex ny += self._yrefindex ny1 += self._yrefindex (fig_w, fig_h) = self._fig.bbox.size / self._fig.dpi (x, y, w, h) = self.get_position_runtime(axes, renderer) hsizes = self.get_horizontal_sizes(renderer) vsizes = self.get_vertical_sizes(renderer) k_h = self._calc_k(hsizes, fig_w * w) k_v = self._calc_k(vsizes, fig_h * h) if self.get_aspect(): k = min(k_h, k_v) ox = self._calc_offsets(hsizes, k) oy = self._calc_offsets(vsizes, k) ww = (ox[-1] - ox[0]) / fig_w hh = (oy[-1] - oy[0]) / fig_h pb = mtransforms.Bbox.from_bounds(x, y, w, h) pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh) (x0, y0) = pb1.anchored(self.get_anchor(), pb).p0 else: ox = self._calc_offsets(hsizes, k_h) oy = self._calc_offsets(vsizes, k_v) (x0, y0) = (x, y) if nx1 is None: nx1 = -1 if ny1 is None: ny1 = -1 (x1, w1) = (x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w) (y1, h1) = (y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h) return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) def append_size(self, position, size): _api.check_in_list(['left', 'right', 'bottom', 'top'], position=position) if position == 'left': self._horizontal.insert(0, size) self._xrefindex += 1 elif position == 'right': self._horizontal.append(size) elif position == 'bottom': self._vertical.insert(0, size) self._yrefindex += 1 else: self._vertical.append(size) def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None): if adjust_dirs is None: adjust_dirs = ['left', 'right', 'bottom', 'top'] for d in adjust_dirs: self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad) @_api.deprecated('3.8') class AxesLocator: def __init__(self, axes_divider, nx, ny, nx1=None, ny1=None): self._axes_divider = axes_divider _xrefindex = axes_divider._xrefindex _yrefindex = axes_divider._yrefindex (self._nx, self._ny) = (nx - _xrefindex, ny - _yrefindex) if nx1 is None: nx1 = len(self._axes_divider) if ny1 is None: ny1 = len(self._axes_divider[0]) self._nx1 = nx1 - _xrefindex self._ny1 = ny1 - _yrefindex def __call__(self, axes, renderer): _xrefindex = self._axes_divider._xrefindex _yrefindex = self._axes_divider._yrefindex return self._axes_divider.locate(self._nx + _xrefindex, self._ny + _yrefindex, self._nx1 + _xrefindex, self._ny1 + _yrefindex, axes, renderer) def get_subplotspec(self): return self._axes_divider.get_subplotspec() class SubplotDivider(Divider): def __init__(self, fig, *args, horizontal=None, vertical=None, aspect=None, anchor='C'): self.figure = fig super().__init__(fig, [0, 0, 1, 1], horizontal=horizontal or [], vertical=vertical or [], aspect=aspect, anchor=anchor) self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args)) def get_position(self): return self.get_subplotspec().get_position(self.figure).bounds def get_subplotspec(self): return self._subplotspec def set_subplotspec(self, subplotspec): self._subplotspec = subplotspec self.set_position(subplotspec.get_position(self.figure)) class AxesDivider(Divider): def __init__(self, axes, xref=None, yref=None): self._axes = axes if xref is None: self._xref = Size.AxesX(axes) else: self._xref = xref if yref is None: self._yref = Size.AxesY(axes) else: self._yref = yref super().__init__(fig=axes.get_figure(), pos=None, horizontal=[self._xref], vertical=[self._yref], aspect=None, anchor='C') def _get_new_axes(self, *, axes_class=None, **kwargs): axes = self._axes if axes_class is None: axes_class = type(axes) return axes_class(axes.get_figure(), axes.get_position(original=True), **kwargs) def new_horizontal(self, size, pad=None, pack_start=False, **kwargs): if pad is None: pad = mpl.rcParams['figure.subplot.wspace'] * self._xref pos = 'left' if pack_start else 'right' if pad: if not isinstance(pad, Size._Base): pad = Size.from_any(pad, fraction_ref=self._xref) self.append_size(pos, pad) if not isinstance(size, Size._Base): size = Size.from_any(size, fraction_ref=self._xref) self.append_size(pos, size) locator = self.new_locator(nx=0 if pack_start else len(self._horizontal) - 1, ny=self._yrefindex) ax = self._get_new_axes(**kwargs) ax.set_axes_locator(locator) return ax def new_vertical(self, size, pad=None, pack_start=False, **kwargs): if pad is None: pad = mpl.rcParams['figure.subplot.hspace'] * self._yref pos = 'bottom' if pack_start else 'top' if pad: if not isinstance(pad, Size._Base): pad = Size.from_any(pad, fraction_ref=self._yref) self.append_size(pos, pad) if not isinstance(size, Size._Base): size = Size.from_any(size, fraction_ref=self._yref) self.append_size(pos, size) locator = self.new_locator(nx=self._xrefindex, ny=0 if pack_start else len(self._vertical) - 1) ax = self._get_new_axes(**kwargs) ax.set_axes_locator(locator) return ax def append_axes(self, position, size, pad=None, *, axes_class=None, **kwargs): (create_axes, pack_start) = _api.check_getitem({'left': (self.new_horizontal, True), 'right': (self.new_horizontal, False), 'bottom': (self.new_vertical, True), 'top': (self.new_vertical, False)}, position=position) ax = create_axes(size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs) self._fig.add_axes(ax) return ax def get_aspect(self): if self._aspect is None: aspect = self._axes.get_aspect() if aspect == 'auto': return False else: return True else: return self._aspect def get_position(self): if self._pos is None: bbox = self._axes.get_position(original=True) return bbox.bounds else: return self._pos def get_anchor(self): if self._anchor is None: return self._axes.get_anchor() else: return self._anchor def get_subplotspec(self): return self._axes.get_subplotspec() def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor): total_width = fig_w * w max_height = fig_h * h n = len(equal_heights) (eq_rels, eq_abss) = equal_heights.T (sm_rels, sm_abss) = summed_widths.T A = np.diag([*eq_rels, 0]) A[:n, -1] = -1 A[-1, :-1] = sm_rels B = [*-eq_abss, total_width - sm_abss.sum()] (*karray, height) = np.linalg.solve(A, B) if height > max_height: karray = (max_height - eq_abss) / eq_rels ox = np.cumsum([0, *sm_rels * karray + sm_abss]) ww = (ox[-1] - ox[0]) / fig_w (h0_rel, h0_abs) = equal_heights[0] hh = (karray[0] * h0_rel + h0_abs) / fig_h pb = mtransforms.Bbox.from_bounds(x, y, w, h) pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh) (x0, y0) = pb1.anchored(anchor, pb).p0 return (x0, y0, ox, hh) class HBoxDivider(SubplotDivider): def new_locator(self, nx, nx1=None): return super().new_locator(nx, 0, nx1, 0) def _locate(self, nx, ny, nx1, ny1, axes, renderer): nx += self._xrefindex nx1 += self._xrefindex (fig_w, fig_h) = self._fig.bbox.size / self._fig.dpi (x, y, w, h) = self.get_position_runtime(axes, renderer) summed_ws = self.get_horizontal_sizes(renderer) equal_hs = self.get_vertical_sizes(renderer) (x0, y0, ox, hh) = _locate(x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor()) if nx1 is None: nx1 = -1 (x1, w1) = (x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w) (y1, h1) = (y0, hh) return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) class VBoxDivider(SubplotDivider): def new_locator(self, ny, ny1=None): return super().new_locator(0, ny, 0, ny1) def _locate(self, nx, ny, nx1, ny1, axes, renderer): ny += self._yrefindex ny1 += self._yrefindex (fig_w, fig_h) = self._fig.bbox.size / self._fig.dpi (x, y, w, h) = self.get_position_runtime(axes, renderer) summed_hs = self.get_vertical_sizes(renderer) equal_ws = self.get_horizontal_sizes(renderer) (y0, x0, oy, ww) = _locate(y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor()) if ny1 is None: ny1 = -1 (x1, w1) = (x0, ww) (y1, h1) = (y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h) return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) def make_axes_locatable(axes): divider = AxesDivider(axes) locator = divider.new_locator(nx=0, ny=0) axes.set_axes_locator(locator) return divider def make_axes_area_auto_adjustable(ax, use_axes=None, pad=0.1, adjust_dirs=None): if adjust_dirs is None: adjust_dirs = ['left', 'right', 'bottom', 'top'] divider = make_axes_locatable(ax) if use_axes is None: use_axes = ax divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad, adjust_dirs=adjust_dirs) # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/axes_grid.py from numbers import Number import functools from types import MethodType import numpy as np from matplotlib import _api, cbook from matplotlib.gridspec import SubplotSpec from .axes_divider import Size, SubplotDivider, Divider from .mpl_axes import Axes, SimpleAxisArtist class CbarAxesBase: def __init__(self, *args, orientation, **kwargs): self.orientation = orientation super().__init__(*args, **kwargs) def colorbar(self, mappable, **kwargs): return self.get_figure(root=False).colorbar(mappable, cax=self, location=self.orientation, **kwargs) @_api.deprecated('3.8', alternative='ax.tick_params and colorbar.set_label') def toggle_label(self, b): axis = self.axis[self.orientation] axis.toggle(ticklabels=b, label=b) _cbaraxes_class_factory = cbook._make_class_factory(CbarAxesBase, 'Cbar{}') class Grid: _defaultAxesClass = Axes def __init__(self, fig, rect, nrows_ncols, ngrids=None, direction='row', axes_pad=0.02, *, share_all=False, share_x=True, share_y=True, label_mode='L', axes_class=None, aspect=False): (self._nrows, self._ncols) = nrows_ncols if ngrids is None: ngrids = self._nrows * self._ncols elif not 0 < ngrids <= self._nrows * self._ncols: raise ValueError('ngrids must be positive and not larger than nrows*ncols') self.ngrids = ngrids (self._horiz_pad_size, self._vert_pad_size) = map(Size.Fixed, np.broadcast_to(axes_pad, 2)) _api.check_in_list(['column', 'row'], direction=direction) self._direction = direction if axes_class is None: axes_class = self._defaultAxesClass elif isinstance(axes_class, (list, tuple)): (cls, kwargs) = axes_class axes_class = functools.partial(cls, **kwargs) kw = dict(horizontal=[], vertical=[], aspect=aspect) if isinstance(rect, (Number, SubplotSpec)): self._divider = SubplotDivider(fig, rect, **kw) elif len(rect) == 3: self._divider = SubplotDivider(fig, *rect, **kw) elif len(rect) == 4: self._divider = Divider(fig, rect, **kw) else: raise TypeError('Incorrect rect format') rect = self._divider.get_position() axes_array = np.full((self._nrows, self._ncols), None, dtype=object) for i in range(self.ngrids): (col, row) = self._get_col_row(i) if share_all: sharex = sharey = axes_array[0, 0] else: sharex = axes_array[0, col] if share_x else None sharey = axes_array[row, 0] if share_y else None axes_array[row, col] = axes_class(fig, rect, sharex=sharex, sharey=sharey) self.axes_all = axes_array.ravel(order='C' if self._direction == 'row' else 'F').tolist() self.axes_column = axes_array.T.tolist() self.axes_row = axes_array.tolist() self.axes_llc = self.axes_column[0][-1] self._init_locators() for ax in self.axes_all: fig.add_axes(ax) self.set_label_mode(label_mode) def _init_locators(self): self._divider.set_horizontal([Size.Scaled(1), self._horiz_pad_size] * (self._ncols - 1) + [Size.Scaled(1)]) self._divider.set_vertical([Size.Scaled(1), self._vert_pad_size] * (self._nrows - 1) + [Size.Scaled(1)]) for i in range(self.ngrids): (col, row) = self._get_col_row(i) self.axes_all[i].set_axes_locator(self._divider.new_locator(nx=2 * col, ny=2 * (self._nrows - 1 - row))) def _get_col_row(self, n): if self._direction == 'column': (col, row) = divmod(n, self._nrows) else: (row, col) = divmod(n, self._ncols) return (col, row) def __len__(self): return len(self.axes_all) def __getitem__(self, i): return self.axes_all[i] def get_geometry(self): return (self._nrows, self._ncols) def set_axes_pad(self, axes_pad): self._horiz_pad_size.fixed_size = axes_pad[0] self._vert_pad_size.fixed_size = axes_pad[1] def get_axes_pad(self): return (self._horiz_pad_size.fixed_size, self._vert_pad_size.fixed_size) def set_aspect(self, aspect): self._divider.set_aspect(aspect) def get_aspect(self): return self._divider.get_aspect() def set_label_mode(self, mode): _api.check_in_list(['all', 'L', '1', 'keep'], mode=mode) (is_last_row, is_first_col) = np.mgrid[:self._nrows, :self._ncols] == [[[self._nrows - 1]], [[0]]] if mode == 'all': bottom = left = np.full((self._nrows, self._ncols), True) elif mode == 'L': bottom = is_last_row left = is_first_col elif mode == '1': bottom = left = is_last_row & is_first_col else: return for i in range(self._nrows): for j in range(self._ncols): ax = self.axes_row[i][j] if isinstance(ax.axis, MethodType): bottom_axis = SimpleAxisArtist(ax.xaxis, 1, ax.spines['bottom']) left_axis = SimpleAxisArtist(ax.yaxis, 1, ax.spines['left']) else: bottom_axis = ax.axis['bottom'] left_axis = ax.axis['left'] bottom_axis.toggle(ticklabels=bottom[i, j], label=bottom[i, j]) left_axis.toggle(ticklabels=left[i, j], label=left[i, j]) def get_divider(self): return self._divider def set_axes_locator(self, locator): self._divider.set_locator(locator) def get_axes_locator(self): return self._divider.get_locator() class ImageGrid(Grid): def __init__(self, fig, rect, nrows_ncols, ngrids=None, direction='row', axes_pad=0.02, *, share_all=False, aspect=True, label_mode='L', cbar_mode=None, cbar_location='right', cbar_pad=None, cbar_size='5%', cbar_set_cax=True, axes_class=None): _api.check_in_list(['each', 'single', 'edge', None], cbar_mode=cbar_mode) _api.check_in_list(['left', 'right', 'bottom', 'top'], cbar_location=cbar_location) self._colorbar_mode = cbar_mode self._colorbar_location = cbar_location self._colorbar_pad = cbar_pad self._colorbar_size = cbar_size super().__init__(fig, rect, nrows_ncols, ngrids, direction=direction, axes_pad=axes_pad, share_all=share_all, share_x=True, share_y=True, aspect=aspect, label_mode=label_mode, axes_class=axes_class) for ax in self.cbar_axes: fig.add_axes(ax) if cbar_set_cax: if self._colorbar_mode == 'single': for ax in self.axes_all: ax.cax = self.cbar_axes[0] elif self._colorbar_mode == 'edge': for (index, ax) in enumerate(self.axes_all): (col, row) = self._get_col_row(index) if self._colorbar_location in ('left', 'right'): ax.cax = self.cbar_axes[row] else: ax.cax = self.cbar_axes[col] else: for (ax, cax) in zip(self.axes_all, self.cbar_axes): ax.cax = cax def _init_locators(self): if self._colorbar_pad is None: if self._colorbar_location in ('left', 'right'): self._colorbar_pad = self._horiz_pad_size.fixed_size else: self._colorbar_pad = self._vert_pad_size.fixed_size self.cbar_axes = [_cbaraxes_class_factory(self._defaultAxesClass)(self.axes_all[0].get_figure(root=False), self._divider.get_position(), orientation=self._colorbar_location) for _ in range(self.ngrids)] cb_mode = self._colorbar_mode cb_location = self._colorbar_location h = [] v = [] h_ax_pos = [] h_cb_pos = [] if cb_mode == 'single' and cb_location in ('left', 'bottom'): if cb_location == 'left': sz = self._nrows * Size.AxesX(self.axes_llc) h.append(Size.from_any(self._colorbar_size, sz)) h.append(Size.from_any(self._colorbar_pad, sz)) locator = self._divider.new_locator(nx=0, ny=0, ny1=-1) elif cb_location == 'bottom': sz = self._ncols * Size.AxesY(self.axes_llc) v.append(Size.from_any(self._colorbar_size, sz)) v.append(Size.from_any(self._colorbar_pad, sz)) locator = self._divider.new_locator(nx=0, nx1=-1, ny=0) for i in range(self.ngrids): self.cbar_axes[i].set_visible(False) self.cbar_axes[0].set_axes_locator(locator) self.cbar_axes[0].set_visible(True) for (col, ax) in enumerate(self.axes_row[0]): if col != 0: h.append(self._horiz_pad_size) if ax: sz = Size.AxesX(ax, aspect='axes', ref_ax=self.axes_all[0]) else: sz = Size.AxesX(self.axes_all[0], aspect='axes', ref_ax=self.axes_all[0]) if cb_location == 'left' and (cb_mode == 'each' or (cb_mode == 'edge' and col == 0)): h_cb_pos.append(len(h)) h.append(Size.from_any(self._colorbar_size, sz)) h.append(Size.from_any(self._colorbar_pad, sz)) h_ax_pos.append(len(h)) h.append(sz) if cb_location == 'right' and (cb_mode == 'each' or (cb_mode == 'edge' and col == self._ncols - 1)): h.append(Size.from_any(self._colorbar_pad, sz)) h_cb_pos.append(len(h)) h.append(Size.from_any(self._colorbar_size, sz)) v_ax_pos = [] v_cb_pos = [] for (row, ax) in enumerate(self.axes_column[0][::-1]): if row != 0: v.append(self._vert_pad_size) if ax: sz = Size.AxesY(ax, aspect='axes', ref_ax=self.axes_all[0]) else: sz = Size.AxesY(self.axes_all[0], aspect='axes', ref_ax=self.axes_all[0]) if cb_location == 'bottom' and (cb_mode == 'each' or (cb_mode == 'edge' and row == 0)): v_cb_pos.append(len(v)) v.append(Size.from_any(self._colorbar_size, sz)) v.append(Size.from_any(self._colorbar_pad, sz)) v_ax_pos.append(len(v)) v.append(sz) if cb_location == 'top' and (cb_mode == 'each' or (cb_mode == 'edge' and row == self._nrows - 1)): v.append(Size.from_any(self._colorbar_pad, sz)) v_cb_pos.append(len(v)) v.append(Size.from_any(self._colorbar_size, sz)) for i in range(self.ngrids): (col, row) = self._get_col_row(i) locator = self._divider.new_locator(nx=h_ax_pos[col], ny=v_ax_pos[self._nrows - 1 - row]) self.axes_all[i].set_axes_locator(locator) if cb_mode == 'each': if cb_location in ('right', 'left'): locator = self._divider.new_locator(nx=h_cb_pos[col], ny=v_ax_pos[self._nrows - 1 - row]) elif cb_location in ('top', 'bottom'): locator = self._divider.new_locator(nx=h_ax_pos[col], ny=v_cb_pos[self._nrows - 1 - row]) self.cbar_axes[i].set_axes_locator(locator) elif cb_mode == 'edge': if cb_location == 'left' and col == 0 or (cb_location == 'right' and col == self._ncols - 1): locator = self._divider.new_locator(nx=h_cb_pos[0], ny=v_ax_pos[self._nrows - 1 - row]) self.cbar_axes[row].set_axes_locator(locator) elif cb_location == 'bottom' and row == self._nrows - 1 or (cb_location == 'top' and row == 0): locator = self._divider.new_locator(nx=h_ax_pos[col], ny=v_cb_pos[0]) self.cbar_axes[col].set_axes_locator(locator) if cb_mode == 'single': if cb_location == 'right': sz = self._nrows * Size.AxesX(self.axes_llc) h.append(Size.from_any(self._colorbar_pad, sz)) h.append(Size.from_any(self._colorbar_size, sz)) locator = self._divider.new_locator(nx=-2, ny=0, ny1=-1) elif cb_location == 'top': sz = self._ncols * Size.AxesY(self.axes_llc) v.append(Size.from_any(self._colorbar_pad, sz)) v.append(Size.from_any(self._colorbar_size, sz)) locator = self._divider.new_locator(nx=0, nx1=-1, ny=-2) if cb_location in ('right', 'top'): for i in range(self.ngrids): self.cbar_axes[i].set_visible(False) self.cbar_axes[0].set_axes_locator(locator) self.cbar_axes[0].set_visible(True) elif cb_mode == 'each': for i in range(self.ngrids): self.cbar_axes[i].set_visible(True) elif cb_mode == 'edge': if cb_location in ('right', 'left'): count = self._nrows else: count = self._ncols for i in range(count): self.cbar_axes[i].set_visible(True) for j in range(i + 1, self.ngrids): self.cbar_axes[j].set_visible(False) else: for i in range(self.ngrids): self.cbar_axes[i].set_visible(False) self.cbar_axes[i].set_position([1.0, 1.0, 0.001, 0.001], which='active') self._divider.set_horizontal(h) self._divider.set_vertical(v) AxesGrid = ImageGrid # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/axes_rgb.py from types import MethodType import numpy as np from .axes_divider import make_axes_locatable, Size from .mpl_axes import Axes, SimpleAxisArtist def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs): divider = make_axes_locatable(ax) pad_size = pad * Size.AxesY(ax) xsize = (1 - 2 * pad) / 3 * Size.AxesX(ax) ysize = (1 - 2 * pad) / 3 * Size.AxesY(ax) divider.set_horizontal([Size.AxesX(ax), pad_size, xsize]) divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize]) ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1)) ax_rgb = [] if axes_class is None: axes_class = type(ax) for ny in [4, 2, 0]: ax1 = axes_class(ax.get_figure(), ax.get_position(original=True), sharex=ax, sharey=ax, **kwargs) locator = divider.new_locator(nx=2, ny=ny) ax1.set_axes_locator(locator) for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels(): t.set_visible(False) try: for axis in ax1.axis.values(): axis.major_ticklabels.set_visible(False) except AttributeError: pass ax_rgb.append(ax1) fig = ax.get_figure() for ax1 in ax_rgb: fig.add_axes(ax1) return ax_rgb class RGBAxes: _defaultAxesClass = Axes def __init__(self, *args, pad=0, **kwargs): axes_class = kwargs.pop('axes_class', self._defaultAxesClass) self.RGB = ax = axes_class(*args, **kwargs) ax.get_figure().add_axes(ax) (self.R, self.G, self.B) = make_rgb_axes(ax, pad=pad, axes_class=axes_class, **kwargs) for ax1 in [self.RGB, self.R, self.G, self.B]: if isinstance(ax1.axis, MethodType): ad = Axes.AxisDict(self) ad.update(bottom=SimpleAxisArtist(ax1.xaxis, 1, ax1.spines['bottom']), top=SimpleAxisArtist(ax1.xaxis, 2, ax1.spines['top']), left=SimpleAxisArtist(ax1.yaxis, 1, ax1.spines['left']), right=SimpleAxisArtist(ax1.yaxis, 2, ax1.spines['right'])) else: ad = ax1.axis ad[:].line.set_color('w') ad[:].major_ticks.set_markeredgecolor('w') def imshow_rgb(self, r, g, b, **kwargs): if not r.shape == g.shape == b.shape: raise ValueError(f'Input shapes ({r.shape}, {g.shape}, {b.shape}) do not match') RGB = np.dstack([r, g, b]) R = np.zeros_like(RGB) R[:, :, 0] = r G = np.zeros_like(RGB) G[:, :, 1] = g B = np.zeros_like(RGB) B[:, :, 2] = b im_rgb = self.RGB.imshow(RGB, **kwargs) im_r = self.R.imshow(R, **kwargs) im_g = self.G.imshow(G, **kwargs) im_b = self.B.imshow(B, **kwargs) return (im_rgb, im_r, im_g, im_b) # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/axes_size.py """""" from numbers import Real from matplotlib import _api from matplotlib.axes import Axes class _Base: def __rmul__(self, other): return self * other def __mul__(self, other): if not isinstance(other, Real): return NotImplemented return Fraction(other, self) def __div__(self, other): return 1 / other * self def __add__(self, other): if isinstance(other, _Base): return Add(self, other) else: return Add(self, Fixed(other)) def __neg__(self): return -1 * self def __radd__(self, other): return Add(self, Fixed(other)) def __sub__(self, other): return self + -other def get_size(self, renderer): raise NotImplementedError('Subclasses must implement') class Add(_Base): def __init__(self, a, b): self._a = a self._b = b def get_size(self, renderer): (a_rel_size, a_abs_size) = self._a.get_size(renderer) (b_rel_size, b_abs_size) = self._b.get_size(renderer) return (a_rel_size + b_rel_size, a_abs_size + b_abs_size) class Fixed(_Base): def __init__(self, fixed_size): _api.check_isinstance(Real, fixed_size=fixed_size) self.fixed_size = fixed_size def get_size(self, renderer): rel_size = 0.0 abs_size = self.fixed_size return (rel_size, abs_size) class Scaled(_Base): def __init__(self, scalable_size): self._scalable_size = scalable_size def get_size(self, renderer): rel_size = self._scalable_size abs_size = 0.0 return (rel_size, abs_size) Scalable = Scaled def _get_axes_aspect(ax): aspect = ax.get_aspect() if aspect == 'auto': aspect = 1.0 return aspect class AxesX(_Base): def __init__(self, axes, aspect=1.0, ref_ax=None): self._axes = axes self._aspect = aspect if aspect == 'axes' and ref_ax is None: raise ValueError("ref_ax must be set when aspect='axes'") self._ref_ax = ref_ax def get_size(self, renderer): (l1, l2) = self._axes.get_xlim() if self._aspect == 'axes': ref_aspect = _get_axes_aspect(self._ref_ax) aspect = ref_aspect / _get_axes_aspect(self._axes) else: aspect = self._aspect rel_size = abs(l2 - l1) * aspect abs_size = 0.0 return (rel_size, abs_size) class AxesY(_Base): def __init__(self, axes, aspect=1.0, ref_ax=None): self._axes = axes self._aspect = aspect if aspect == 'axes' and ref_ax is None: raise ValueError("ref_ax must be set when aspect='axes'") self._ref_ax = ref_ax def get_size(self, renderer): (l1, l2) = self._axes.get_ylim() if self._aspect == 'axes': ref_aspect = _get_axes_aspect(self._ref_ax) aspect = _get_axes_aspect(self._axes) else: aspect = self._aspect rel_size = abs(l2 - l1) * aspect abs_size = 0.0 return (rel_size, abs_size) class MaxExtent(_Base): def __init__(self, artist_list, w_or_h): self._artist_list = artist_list _api.check_in_list(['width', 'height'], w_or_h=w_or_h) self._w_or_h = w_or_h def add_artist(self, a): self._artist_list.append(a) def get_size(self, renderer): rel_size = 0.0 extent_list = [getattr(a.get_window_extent(renderer), self._w_or_h) / a.figure.dpi for a in self._artist_list] abs_size = max(extent_list, default=0) return (rel_size, abs_size) class MaxWidth(MaxExtent): def __init__(self, artist_list): super().__init__(artist_list, 'width') class MaxHeight(MaxExtent): def __init__(self, artist_list): super().__init__(artist_list, 'height') class Fraction(_Base): def __init__(self, fraction, ref_size): _api.check_isinstance(Real, fraction=fraction) self._fraction_ref = ref_size self._fraction = fraction def get_size(self, renderer): if self._fraction_ref is None: return (self._fraction, 0.0) else: (r, a) = self._fraction_ref.get_size(renderer) rel_size = r * self._fraction abs_size = a * self._fraction return (rel_size, abs_size) def from_any(size, fraction_ref=None): if isinstance(size, Real): return Fixed(size) elif isinstance(size, str): if size[-1] == '%': return Fraction(float(size[:-1]) / 100, fraction_ref) raise ValueError('Unknown format') class _AxesDecorationsSize(_Base): _get_size_map = {'left': lambda tight_bb, axes_bb: axes_bb.xmin - tight_bb.xmin, 'right': lambda tight_bb, axes_bb: tight_bb.xmax - axes_bb.xmax, 'bottom': lambda tight_bb, axes_bb: axes_bb.ymin - tight_bb.ymin, 'top': lambda tight_bb, axes_bb: tight_bb.ymax - axes_bb.ymax} def __init__(self, ax, direction): _api.check_in_list(self._get_size_map, direction=direction) self._direction = direction self._ax_list = [ax] if isinstance(ax, Axes) else ax def get_size(self, renderer): sz = max([self._get_size_map[self._direction](ax.get_tightbbox(renderer, call_axes_locator=False), ax.bbox) for ax in self._ax_list]) dpi = renderer.points_to_pixels(72) abs_size = sz / dpi rel_size = 0 return (rel_size, abs_size) # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/inset_locator.py """""" from matplotlib import _api, _docstring from matplotlib.offsetbox import AnchoredOffsetbox from matplotlib.patches import Patch, Rectangle from matplotlib.path import Path from matplotlib.transforms import Bbox, BboxTransformTo from matplotlib.transforms import IdentityTransform, TransformedBbox from . import axes_size as Size from .parasite_axes import HostAxes @_api.deprecated('3.8', alternative='Axes.inset_axes') class InsetPosition: @_docstring.dedent_interpd def __init__(self, parent, lbwh): self.parent = parent self.lbwh = lbwh def __call__(self, ax, renderer): bbox_parent = self.parent.get_position(original=False) trans = BboxTransformTo(bbox_parent) bbox_inset = Bbox.from_bounds(*self.lbwh) bb = TransformedBbox(bbox_inset, trans) return bb class AnchoredLocatorBase(AnchoredOffsetbox): def __init__(self, bbox_to_anchor, offsetbox, loc, borderpad=0.5, bbox_transform=None): super().__init__(loc, pad=0.0, child=None, borderpad=borderpad, bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform) def draw(self, renderer): raise RuntimeError('No draw method should be called') def __call__(self, ax, renderer): fig = ax.get_figure(root=False) if renderer is None: renderer = fig._get_renderer() self.axes = ax bbox = self.get_window_extent(renderer) (px, py) = self.get_offset(bbox.width, bbox.height, 0, 0, renderer) bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height) tr = fig.transSubfigure.inverted() return TransformedBbox(bbox_canvas, tr) class AnchoredSizeLocator(AnchoredLocatorBase): def __init__(self, bbox_to_anchor, x_size, y_size, loc, borderpad=0.5, bbox_transform=None): super().__init__(bbox_to_anchor, None, loc, borderpad=borderpad, bbox_transform=bbox_transform) self.x_size = Size.from_any(x_size) self.y_size = Size.from_any(y_size) def get_bbox(self, renderer): bbox = self.get_bbox_to_anchor() dpi = renderer.points_to_pixels(72.0) (r, a) = self.x_size.get_size(renderer) width = bbox.width * r + a * dpi (r, a) = self.y_size.get_size(renderer) height = bbox.height * r + a * dpi fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) pad = self.pad * fontsize return Bbox.from_bounds(0, 0, width, height).padded(pad) class AnchoredZoomLocator(AnchoredLocatorBase): def __init__(self, parent_axes, zoom, loc, borderpad=0.5, bbox_to_anchor=None, bbox_transform=None): self.parent_axes = parent_axes self.zoom = zoom if bbox_to_anchor is None: bbox_to_anchor = parent_axes.bbox super().__init__(bbox_to_anchor, None, loc, borderpad=borderpad, bbox_transform=bbox_transform) def get_bbox(self, renderer): bb = self.parent_axes.transData.transform_bbox(self.axes.viewLim) fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) pad = self.pad * fontsize return Bbox.from_bounds(0, 0, abs(bb.width * self.zoom), abs(bb.height * self.zoom)).padded(pad) class BboxPatch(Patch): @_docstring.dedent_interpd def __init__(self, bbox, **kwargs): if 'transform' in kwargs: raise ValueError('transform should not be set') kwargs['transform'] = IdentityTransform() super().__init__(**kwargs) self.bbox = bbox def get_path(self): (x0, y0, x1, y1) = self.bbox.extents return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) class BboxConnector(Patch): @staticmethod def get_bbox_edge_pos(bbox, loc): (x0, y0, x1, y1) = bbox.extents if loc == 1: return (x1, y1) elif loc == 2: return (x0, y1) elif loc == 3: return (x0, y0) elif loc == 4: return (x1, y0) @staticmethod def connect_bbox(bbox1, bbox2, loc1, loc2=None): if isinstance(bbox1, Rectangle): bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform()) if isinstance(bbox2, Rectangle): bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform()) if loc2 is None: loc2 = loc1 (x1, y1) = BboxConnector.get_bbox_edge_pos(bbox1, loc1) (x2, y2) = BboxConnector.get_bbox_edge_pos(bbox2, loc2) return Path([[x1, y1], [x2, y2]]) @_docstring.dedent_interpd def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs): if 'transform' in kwargs: raise ValueError('transform should not be set') kwargs['transform'] = IdentityTransform() kwargs.setdefault('fill', bool({'fc', 'facecolor', 'color'}.intersection(kwargs))) super().__init__(**kwargs) self.bbox1 = bbox1 self.bbox2 = bbox2 self.loc1 = loc1 self.loc2 = loc2 def get_path(self): return self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2) class BboxConnectorPatch(BboxConnector): @_docstring.dedent_interpd def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs): if 'transform' in kwargs: raise ValueError('transform should not be set') super().__init__(bbox1, bbox2, loc1a, loc2a, **kwargs) self.loc1b = loc1b self.loc2b = loc2b def get_path(self): path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2) path2 = self.connect_bbox(self.bbox2, self.bbox1, self.loc2b, self.loc1b) path_merged = [*path1.vertices, *path2.vertices, path1.vertices[0]] return Path(path_merged) def _add_inset_axes(parent_axes, axes_class, axes_kwargs, axes_locator): if axes_class is None: axes_class = HostAxes if axes_kwargs is None: axes_kwargs = {} fig = parent_axes.get_figure(root=False) inset_axes = axes_class(fig, parent_axes.get_position(), **{'navigate': False, **axes_kwargs, 'axes_locator': axes_locator}) return fig.add_axes(inset_axes) @_docstring.dedent_interpd def inset_axes(parent_axes, width, height, loc='upper right', bbox_to_anchor=None, bbox_transform=None, axes_class=None, axes_kwargs=None, borderpad=0.5): if bbox_transform in [parent_axes.transAxes, parent_axes.get_figure(root=False).transFigure] and bbox_to_anchor is None: _api.warn_external('Using the axes or figure transform requires a bounding box in the respective coordinates. Using bbox_to_anchor=(0, 0, 1, 1) now.') bbox_to_anchor = (0, 0, 1, 1) if bbox_to_anchor is None: bbox_to_anchor = parent_axes.bbox if isinstance(bbox_to_anchor, tuple) and (isinstance(width, str) or isinstance(height, str)): if len(bbox_to_anchor) != 4: raise ValueError('Using relative units for width or height requires to provide a 4-tuple or a `Bbox` instance to `bbox_to_anchor.') return _add_inset_axes(parent_axes, axes_class, axes_kwargs, AnchoredSizeLocator(bbox_to_anchor, width, height, loc=loc, bbox_transform=bbox_transform, borderpad=borderpad)) @_docstring.dedent_interpd def zoomed_inset_axes(parent_axes, zoom, loc='upper right', bbox_to_anchor=None, bbox_transform=None, axes_class=None, axes_kwargs=None, borderpad=0.5): return _add_inset_axes(parent_axes, axes_class, axes_kwargs, AnchoredZoomLocator(parent_axes, zoom=zoom, loc=loc, bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform, borderpad=borderpad)) class _TransformedBboxWithCallback(TransformedBbox): def __init__(self, *args, callback, **kwargs): super().__init__(*args, **kwargs) self._callback = callback def get_points(self): self._callback() return super().get_points() @_docstring.dedent_interpd def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs): rect = _TransformedBboxWithCallback(inset_axes.viewLim, parent_axes.transData, callback=parent_axes._unstale_viewLim) kwargs.setdefault('fill', bool({'fc', 'facecolor', 'color'}.intersection(kwargs))) pp = BboxPatch(rect, **kwargs) parent_axes.add_patch(pp) p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs) inset_axes.add_patch(p1) p1.set_clip_on(False) p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs) inset_axes.add_patch(p2) p2.set_clip_on(False) return (pp, p1, p2) # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/mpl_axes.py import matplotlib.axes as maxes from matplotlib.artist import Artist from matplotlib.axis import XAxis, YAxis class SimpleChainedObjects: def __init__(self, objects): self._objects = objects def __getattr__(self, k): _a = SimpleChainedObjects([getattr(a, k) for a in self._objects]) return _a def __call__(self, *args, **kwargs): for m in self._objects: m(*args, **kwargs) class Axes(maxes.Axes): class AxisDict(dict): def __init__(self, axes): self.axes = axes super().__init__() def __getitem__(self, k): if isinstance(k, tuple): r = SimpleChainedObjects([super(Axes.AxisDict, self).__getitem__(k1) for k1 in k]) return r elif isinstance(k, slice): if k.start is None and k.stop is None and (k.step is None): return SimpleChainedObjects(list(self.values())) else: raise ValueError('Unsupported slice') else: return dict.__getitem__(self, k) def __call__(self, *v, **kwargs): return maxes.Axes.axis(self.axes, *v, **kwargs) @property def axis(self): return self._axislines def clear(self): super().clear() self._axislines = self.AxisDict(self) self._axislines.update(bottom=SimpleAxisArtist(self.xaxis, 1, self.spines['bottom']), top=SimpleAxisArtist(self.xaxis, 2, self.spines['top']), left=SimpleAxisArtist(self.yaxis, 1, self.spines['left']), right=SimpleAxisArtist(self.yaxis, 2, self.spines['right'])) class SimpleAxisArtist(Artist): def __init__(self, axis, axisnum, spine): self._axis = axis self._axisnum = axisnum self.line = spine if isinstance(axis, XAxis): self._axis_direction = ['bottom', 'top'][axisnum - 1] elif isinstance(axis, YAxis): self._axis_direction = ['left', 'right'][axisnum - 1] else: raise ValueError(f'axis must be instance of XAxis or YAxis, but got {axis}') super().__init__() @property def major_ticks(self): tickline = 'tick%dline' % self._axisnum return SimpleChainedObjects([getattr(tick, tickline) for tick in self._axis.get_major_ticks()]) @property def major_ticklabels(self): label = 'label%d' % self._axisnum return SimpleChainedObjects([getattr(tick, label) for tick in self._axis.get_major_ticks()]) @property def label(self): return self._axis.label def set_visible(self, b): self.toggle(all=b) self.line.set_visible(b) self._axis.set_visible(True) super().set_visible(b) def set_label(self, txt): self._axis.set_label_text(txt) def toggle(self, all=None, ticks=None, ticklabels=None, label=None): if all: (_ticks, _ticklabels, _label) = (True, True, True) elif all is not None: (_ticks, _ticklabels, _label) = (False, False, False) else: (_ticks, _ticklabels, _label) = (None, None, None) if ticks is not None: _ticks = ticks if ticklabels is not None: _ticklabels = ticklabels if label is not None: _label = label if _ticks is not None: tickparam = {f'tick{self._axisnum}On': _ticks} self._axis.set_tick_params(**tickparam) if _ticklabels is not None: tickparam = {f'label{self._axisnum}On': _ticklabels} self._axis.set_tick_params(**tickparam) if _label is not None: pos = self._axis.get_label_position() if pos == self._axis_direction and (not _label): self._axis.label.set_visible(False) elif _label: self._axis.label.set_visible(True) self._axis.set_label_position(self._axis_direction) # File: matplotlib-main/lib/mpl_toolkits/axes_grid1/parasite_axes.py from matplotlib import _api, cbook import matplotlib.artist as martist import matplotlib.transforms as mtransforms from matplotlib.transforms import Bbox from .mpl_axes import Axes class ParasiteAxesBase: def __init__(self, parent_axes, aux_transform=None, *, viewlim_mode=None, **kwargs): self._parent_axes = parent_axes self.transAux = aux_transform self.set_viewlim_mode(viewlim_mode) kwargs['frameon'] = False super().__init__(parent_axes.get_figure(root=False), parent_axes._position, **kwargs) def clear(self): super().clear() martist.setp(self.get_children(), visible=False) self._get_lines = self._parent_axes._get_lines self._parent_axes.callbacks._connect_picklable('xlim_changed', self._sync_lims) self._parent_axes.callbacks._connect_picklable('ylim_changed', self._sync_lims) def pick(self, mouseevent): super().pick(mouseevent) for a in self.get_children(): if hasattr(mouseevent.inaxes, 'parasites') and self in mouseevent.inaxes.parasites: a.pick(mouseevent) def _set_lim_and_transforms(self): if self.transAux is not None: self.transAxes = self._parent_axes.transAxes self.transData = self.transAux + self._parent_axes.transData self._xaxis_transform = mtransforms.blended_transform_factory(self.transData, self.transAxes) self._yaxis_transform = mtransforms.blended_transform_factory(self.transAxes, self.transData) else: super()._set_lim_and_transforms() def set_viewlim_mode(self, mode): _api.check_in_list([None, 'equal', 'transform'], mode=mode) self._viewlim_mode = mode def get_viewlim_mode(self): return self._viewlim_mode def _sync_lims(self, parent): viewlim = parent.viewLim.frozen() mode = self.get_viewlim_mode() if mode is None: pass elif mode == 'equal': self.viewLim.set(viewlim) elif mode == 'transform': self.viewLim.set(viewlim.transformed(self.transAux.inverted())) else: _api.check_in_list([None, 'equal', 'transform'], mode=mode) parasite_axes_class_factory = cbook._make_class_factory(ParasiteAxesBase, '{}Parasite') ParasiteAxes = parasite_axes_class_factory(Axes) class HostAxesBase: def __init__(self, *args, **kwargs): self.parasites = [] super().__init__(*args, **kwargs) def get_aux_axes(self, tr=None, viewlim_mode='equal', axes_class=None, **kwargs): if axes_class is None: axes_class = self._base_axes_class parasite_axes_class = parasite_axes_class_factory(axes_class) ax2 = parasite_axes_class(self, tr, viewlim_mode=viewlim_mode, **kwargs) self.parasites.append(ax2) ax2._remove_method = self.parasites.remove return ax2 def draw(self, renderer): orig_children_len = len(self._children) locator = self.get_axes_locator() if locator: pos = locator(self, renderer) self.set_position(pos, which='active') self.apply_aspect(pos) else: self.apply_aspect() rect = self.get_position() for ax in self.parasites: ax.apply_aspect(rect) self._children.extend(ax.get_children()) super().draw(renderer) del self._children[orig_children_len:] def clear(self): super().clear() for ax in self.parasites: ax.clear() def pick(self, mouseevent): super().pick(mouseevent) for a in self.parasites: a.pick(mouseevent) def twinx(self, axes_class=None): ax = self._add_twin_axes(axes_class, sharex=self) self.axis['right'].set_visible(False) ax.axis['right'].set_visible(True) ax.axis['left', 'top', 'bottom'].set_visible(False) return ax def twiny(self, axes_class=None): ax = self._add_twin_axes(axes_class, sharey=self) self.axis['top'].set_visible(False) ax.axis['top'].set_visible(True) ax.axis['left', 'right', 'bottom'].set_visible(False) return ax def twin(self, aux_trans=None, axes_class=None): if aux_trans is None: aux_trans = mtransforms.IdentityTransform() ax = self._add_twin_axes(axes_class, aux_transform=aux_trans, viewlim_mode='transform') self.axis['top', 'right'].set_visible(False) ax.axis['top', 'right'].set_visible(True) ax.axis['left', 'bottom'].set_visible(False) return ax def _add_twin_axes(self, axes_class, **kwargs): if axes_class is None: axes_class = self._base_axes_class ax = parasite_axes_class_factory(axes_class)(self, **kwargs) self.parasites.append(ax) ax._remove_method = self._remove_any_twin return ax def _remove_any_twin(self, ax): self.parasites.remove(ax) restore = ['top', 'right'] if ax._sharex: restore.remove('top') if ax._sharey: restore.remove('right') self.axis[tuple(restore)].set_visible(True) self.axis[tuple(restore)].toggle(ticklabels=False, label=False) def get_tightbbox(self, renderer=None, *, call_axes_locator=True, bbox_extra_artists=None): bbs = [*[ax.get_tightbbox(renderer, call_axes_locator=call_axes_locator) for ax in self.parasites], super().get_tightbbox(renderer, call_axes_locator=call_axes_locator, bbox_extra_artists=bbox_extra_artists)] return Bbox.union([b for b in bbs if b.width != 0 or b.height != 0]) host_axes_class_factory = host_subplot_class_factory = cbook._make_class_factory(HostAxesBase, '{}HostAxes', '_base_axes_class') HostAxes = SubplotHost = host_axes_class_factory(Axes) def host_axes(*args, axes_class=Axes, figure=None, **kwargs): import matplotlib.pyplot as plt host_axes_class = host_axes_class_factory(axes_class) if figure is None: figure = plt.gcf() ax = host_axes_class(figure, *args, **kwargs) figure.add_axes(ax) return ax host_subplot = host_axes # File: matplotlib-main/lib/mpl_toolkits/axisartist/__init__.py from .axislines import Axes from .axislines import AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear, GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero from .axis_artist import AxisArtist, GridlinesCollection from .grid_helper_curvelinear import GridHelperCurveLinear from .floating_axes import FloatingAxes, FloatingSubplot from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory, parasite_axes_class_factory ParasiteAxes = parasite_axes_class_factory(Axes) HostAxes = host_axes_class_factory(Axes) SubplotHost = HostAxes # File: matplotlib-main/lib/mpl_toolkits/axisartist/angle_helper.py import numpy as np import math from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple def select_step_degree(dv): degree_limits_ = [1.5, 3, 7, 13, 20, 40, 70, 120, 270, 520] degree_steps_ = [1, 2, 5, 10, 15, 30, 45, 90, 180, 360] degree_factors = [1.0] * len(degree_steps_) minsec_limits_ = [1.5, 2.5, 3.5, 8, 11, 18, 25, 45] minsec_steps_ = [1, 2, 3, 5, 10, 15, 20, 30] minute_limits_ = np.array(minsec_limits_) / 60 minute_factors = [60.0] * len(minute_limits_) second_limits_ = np.array(minsec_limits_) / 3600 second_factors = [3600.0] * len(second_limits_) degree_limits = [*second_limits_, *minute_limits_, *degree_limits_] degree_steps = [*minsec_steps_, *minsec_steps_, *degree_steps_] degree_factors = [*second_factors, *minute_factors, *degree_factors] n = np.searchsorted(degree_limits, dv) step = degree_steps[n] factor = degree_factors[n] return (step, factor) def select_step_hour(dv): hour_limits_ = [1.5, 2.5, 3.5, 5, 7, 10, 15, 21, 36] hour_steps_ = [1, 2, 3, 4, 6, 8, 12, 18, 24] hour_factors = [1.0] * len(hour_steps_) minsec_limits_ = [1.5, 2.5, 3.5, 4.5, 5.5, 8, 11, 14, 18, 25, 45] minsec_steps_ = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30] minute_limits_ = np.array(minsec_limits_) / 60 minute_factors = [60.0] * len(minute_limits_) second_limits_ = np.array(minsec_limits_) / 3600 second_factors = [3600.0] * len(second_limits_) hour_limits = [*second_limits_, *minute_limits_, *hour_limits_] hour_steps = [*minsec_steps_, *minsec_steps_, *hour_steps_] hour_factors = [*second_factors, *minute_factors, *hour_factors] n = np.searchsorted(hour_limits, dv) step = hour_steps[n] factor = hour_factors[n] return (step, factor) def select_step_sub(dv): tmp = 10.0 ** (int(math.log10(dv)) - 1.0) factor = 1.0 / tmp if 1.5 * tmp >= dv: step = 1 elif 3.0 * tmp >= dv: step = 2 elif 7.0 * tmp >= dv: step = 5 else: step = 1 factor = 0.1 * factor return (step, factor) def select_step(v1, v2, nv, hour=False, include_last=True, threshold_factor=3600.0): if v1 > v2: (v1, v2) = (v2, v1) dv = (v2 - v1) / nv if hour: _select_step = select_step_hour cycle = 24.0 else: _select_step = select_step_degree cycle = 360.0 if dv > 1 / threshold_factor: (step, factor) = _select_step(dv) else: (step, factor) = select_step_sub(dv * threshold_factor) factor = factor * threshold_factor levs = np.arange(np.floor(v1 * factor / step), np.ceil(v2 * factor / step) + 0.5, dtype=int) * step n = len(levs) if factor == 1.0 and levs[-1] >= levs[0] + cycle: nv = int(cycle / step) if include_last: levs = levs[0] + np.arange(0, nv + 1, 1) * step else: levs = levs[0] + np.arange(0, nv, 1) * step n = len(levs) return (np.array(levs), n, factor) def select_step24(v1, v2, nv, include_last=True, threshold_factor=3600): (v1, v2) = (v1 / 15, v2 / 15) (levs, n, factor) = select_step(v1, v2, nv, hour=True, include_last=include_last, threshold_factor=threshold_factor) return (levs * 15, n, factor) def select_step360(v1, v2, nv, include_last=True, threshold_factor=3600): return select_step(v1, v2, nv, hour=False, include_last=include_last, threshold_factor=threshold_factor) class LocatorBase: def __init__(self, nbins, include_last=True): self.nbins = nbins self._include_last = include_last def set_params(self, nbins=None): if nbins is not None: self.nbins = int(nbins) class LocatorHMS(LocatorBase): def __call__(self, v1, v2): return select_step24(v1, v2, self.nbins, self._include_last) class LocatorHM(LocatorBase): def __call__(self, v1, v2): return select_step24(v1, v2, self.nbins, self._include_last, threshold_factor=60) class LocatorH(LocatorBase): def __call__(self, v1, v2): return select_step24(v1, v2, self.nbins, self._include_last, threshold_factor=1) class LocatorDMS(LocatorBase): def __call__(self, v1, v2): return select_step360(v1, v2, self.nbins, self._include_last) class LocatorDM(LocatorBase): def __call__(self, v1, v2): return select_step360(v1, v2, self.nbins, self._include_last, threshold_factor=60) class LocatorD(LocatorBase): def __call__(self, v1, v2): return select_step360(v1, v2, self.nbins, self._include_last, threshold_factor=1) class FormatterDMS: deg_mark = '^{\\circ}' min_mark = '^{\\prime}' sec_mark = '^{\\prime\\prime}' fmt_d = '$%d' + deg_mark + '$' fmt_ds = '$%d.%s' + deg_mark + '$' fmt_d_m = '$%s%d' + deg_mark + '\\,%02d' + min_mark + '$' fmt_d_ms = '$%s%d' + deg_mark + '\\,%02d.%s' + min_mark + '$' fmt_d_m_partial = '$%s%d' + deg_mark + '\\,%02d' + min_mark + '\\,' fmt_s_partial = '%02d' + sec_mark + '$' fmt_ss_partial = '%02d.%s' + sec_mark + '$' def _get_number_fraction(self, factor): number_fraction = None for threshold in [1, 60, 3600]: if factor <= threshold: break d = factor // threshold int_log_d = int(np.floor(np.log10(d))) if 10 ** int_log_d == d and d != 1: number_fraction = int_log_d factor = factor // 10 ** int_log_d return (factor, number_fraction) return (factor, number_fraction) def __call__(self, direction, factor, values): if len(values) == 0: return [] ss = np.sign(values) signs = ['-' if v < 0 else '' for v in values] (factor, number_fraction) = self._get_number_fraction(factor) values = np.abs(values) if number_fraction is not None: (values, frac_part) = divmod(values, 10 ** number_fraction) frac_fmt = '%%0%dd' % (number_fraction,) frac_str = [frac_fmt % (f1,) for f1 in frac_part] if factor == 1: if number_fraction is None: return [self.fmt_d % (s * int(v),) for (s, v) in zip(ss, values)] else: return [self.fmt_ds % (s * int(v), f1) for (s, v, f1) in zip(ss, values, frac_str)] elif factor == 60: (deg_part, min_part) = divmod(values, 60) if number_fraction is None: return [self.fmt_d_m % (s1, d1, m1) for (s1, d1, m1) in zip(signs, deg_part, min_part)] else: return [self.fmt_d_ms % (s, d1, m1, f1) for (s, d1, m1, f1) in zip(signs, deg_part, min_part, frac_str)] elif factor == 3600: if ss[-1] == -1: inverse_order = True values = values[::-1] signs = signs[::-1] else: inverse_order = False l_hm_old = '' r = [] (deg_part, min_part_) = divmod(values, 3600) (min_part, sec_part) = divmod(min_part_, 60) if number_fraction is None: sec_str = [self.fmt_s_partial % (s1,) for s1 in sec_part] else: sec_str = [self.fmt_ss_partial % (s1, f1) for (s1, f1) in zip(sec_part, frac_str)] for (s, d1, m1, s1) in zip(signs, deg_part, min_part, sec_str): l_hm = self.fmt_d_m_partial % (s, d1, m1) if l_hm != l_hm_old: l_hm_old = l_hm l = l_hm + s1 else: l = '$' + s + s1 r.append(l) if inverse_order: return r[::-1] else: return r else: return ['$%s^{\\circ}$' % v for v in ss * values] class FormatterHMS(FormatterDMS): deg_mark = '^\\mathrm{h}' min_mark = '^\\mathrm{m}' sec_mark = '^\\mathrm{s}' fmt_d = '$%d' + deg_mark + '$' fmt_ds = '$%d.%s' + deg_mark + '$' fmt_d_m = '$%s%d' + deg_mark + '\\,%02d' + min_mark + '$' fmt_d_ms = '$%s%d' + deg_mark + '\\,%02d.%s' + min_mark + '$' fmt_d_m_partial = '$%s%d' + deg_mark + '\\,%02d' + min_mark + '\\,' fmt_s_partial = '%02d' + sec_mark + '$' fmt_ss_partial = '%02d.%s' + sec_mark + '$' def __call__(self, direction, factor, values): return super().__call__(direction, factor, np.asarray(values) / 15) class ExtremeFinderCycle(ExtremeFinderSimple): def __init__(self, nx, ny, lon_cycle=360.0, lat_cycle=None, lon_minmax=None, lat_minmax=(-90, 90)): (self.nx, self.ny) = (nx, ny) (self.lon_cycle, self.lat_cycle) = (lon_cycle, lat_cycle) self.lon_minmax = lon_minmax self.lat_minmax = lat_minmax def __call__(self, transform_xy, x1, y1, x2, y2): (x, y) = np.meshgrid(np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)) (lon, lat) = transform_xy(np.ravel(x), np.ravel(y)) with np.errstate(invalid='ignore'): if self.lon_cycle is not None: lon0 = np.nanmin(lon) lon -= 360.0 * (lon - lon0 > 180.0) if self.lat_cycle is not None: lat0 = np.nanmin(lat) lat -= 360.0 * (lat - lat0 > 180.0) (lon_min, lon_max) = (np.nanmin(lon), np.nanmax(lon)) (lat_min, lat_max) = (np.nanmin(lat), np.nanmax(lat)) (lon_min, lon_max, lat_min, lat_max) = self._add_pad(lon_min, lon_max, lat_min, lat_max) if self.lon_cycle: lon_max = min(lon_max, lon_min + self.lon_cycle) if self.lat_cycle: lat_max = min(lat_max, lat_min + self.lat_cycle) if self.lon_minmax is not None: min0 = self.lon_minmax[0] lon_min = max(min0, lon_min) max0 = self.lon_minmax[1] lon_max = min(max0, lon_max) if self.lat_minmax is not None: min0 = self.lat_minmax[0] lat_min = max(min0, lat_min) max0 = self.lat_minmax[1] lat_max = min(max0, lat_max) return (lon_min, lon_max, lat_min, lat_max) # File: matplotlib-main/lib/mpl_toolkits/axisartist/axes_grid.py from matplotlib import _api import mpl_toolkits.axes_grid1.axes_grid as axes_grid_orig from .axislines import Axes _api.warn_deprecated('3.8', name=__name__, obj_type='module', alternative='axes_grid1.axes_grid') @_api.deprecated('3.8', alternative='axes_grid1.axes_grid.Grid(..., axes_class=axislines.Axes') class Grid(axes_grid_orig.Grid): _defaultAxesClass = Axes @_api.deprecated('3.8', alternative='axes_grid1.axes_grid.ImageGrid(..., axes_class=axislines.Axes') class ImageGrid(axes_grid_orig.ImageGrid): _defaultAxesClass = Axes AxesGrid = ImageGrid # File: matplotlib-main/lib/mpl_toolkits/axisartist/axes_rgb.py from matplotlib import _api from mpl_toolkits.axes_grid1.axes_rgb import make_rgb_axes, RGBAxes as _RGBAxes from .axislines import Axes _api.warn_deprecated('3.8', name=__name__, obj_type='module', alternative='axes_grid1.axes_rgb') @_api.deprecated('3.8', alternative='axes_grid1.axes_rgb.RGBAxes(..., axes_class=axislines.Axes') class RGBAxes(_RGBAxes): _defaultAxesClass = Axes # File: matplotlib-main/lib/mpl_toolkits/axisartist/axis_artist.py """""" from operator import methodcaller import numpy as np import matplotlib as mpl from matplotlib import _api, cbook import matplotlib.artist as martist import matplotlib.colors as mcolors import matplotlib.text as mtext from matplotlib.collections import LineCollection from matplotlib.lines import Line2D from matplotlib.patches import PathPatch from matplotlib.path import Path from matplotlib.transforms import Affine2D, Bbox, IdentityTransform, ScaledTranslation from .axisline_style import AxislineStyle class AttributeCopier: def get_ref_artist(self): raise RuntimeError('get_ref_artist must overridden') def get_attribute_from_ref_artist(self, attr_name): getter = methodcaller('get_' + attr_name) prop = getter(super()) return getter(self.get_ref_artist()) if prop == 'auto' else prop class Ticks(AttributeCopier, Line2D): def __init__(self, ticksize, tick_out=False, *, axis=None, **kwargs): self._ticksize = ticksize self.locs_angles_labels = [] self.set_tick_out(tick_out) self._axis = axis if self._axis is not None: if 'color' not in kwargs: kwargs['color'] = 'auto' if 'mew' not in kwargs and 'markeredgewidth' not in kwargs: kwargs['markeredgewidth'] = 'auto' Line2D.__init__(self, [0.0], [0.0], **kwargs) self.set_snap(True) def get_ref_artist(self): return self._axis.majorTicks[0].tick1line def set_color(self, color): if not cbook._str_equal(color, 'auto'): mcolors._check_color_like(color=color) self._color = color self.stale = True def get_color(self): return self.get_attribute_from_ref_artist('color') def get_markeredgecolor(self): return self.get_attribute_from_ref_artist('markeredgecolor') def get_markeredgewidth(self): return self.get_attribute_from_ref_artist('markeredgewidth') def set_tick_out(self, b): self._tick_out = b def get_tick_out(self): return self._tick_out def set_ticksize(self, ticksize): self._ticksize = ticksize def get_ticksize(self): return self._ticksize def set_locs_angles(self, locs_angles): self.locs_angles = locs_angles _tickvert_path = Path([[0.0, 0.0], [1.0, 0.0]]) def draw(self, renderer): if not self.get_visible(): return gc = renderer.new_gc() gc.set_foreground(self.get_markeredgecolor()) gc.set_linewidth(self.get_markeredgewidth()) gc.set_alpha(self._alpha) path_trans = self.get_transform() marker_transform = Affine2D().scale(renderer.points_to_pixels(self._ticksize)) if self.get_tick_out(): marker_transform.rotate_deg(180) for (loc, angle) in self.locs_angles: locs = path_trans.transform_non_affine(np.array([loc])) if self.axes and (not self.axes.viewLim.contains(*locs[0])): continue renderer.draw_markers(gc, self._tickvert_path, marker_transform + Affine2D().rotate_deg(angle), Path(locs), path_trans.get_affine()) gc.restore() class LabelBase(mtext.Text): def __init__(self, *args, **kwargs): self.locs_angles_labels = [] self._ref_angle = 0 self._offset_radius = 0.0 super().__init__(*args, **kwargs) self.set_rotation_mode('anchor') self._text_follow_ref_angle = True @property def _text_ref_angle(self): if self._text_follow_ref_angle: return self._ref_angle + 90 else: return 0 @property def _offset_ref_angle(self): return self._ref_angle _get_opposite_direction = {'left': 'right', 'right': 'left', 'top': 'bottom', 'bottom': 'top'}.__getitem__ def draw(self, renderer): if not self.get_visible(): return tr = self.get_transform() angle_orig = self.get_rotation() theta = np.deg2rad(self._offset_ref_angle) dd = self._offset_radius (dx, dy) = (dd * np.cos(theta), dd * np.sin(theta)) self.set_transform(tr + Affine2D().translate(dx, dy)) self.set_rotation(self._text_ref_angle + angle_orig) super().draw(renderer) self.set_transform(tr) self.set_rotation(angle_orig) def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() tr = self.get_transform() angle_orig = self.get_rotation() theta = np.deg2rad(self._offset_ref_angle) dd = self._offset_radius (dx, dy) = (dd * np.cos(theta), dd * np.sin(theta)) self.set_transform(tr + Affine2D().translate(dx, dy)) self.set_rotation(self._text_ref_angle + angle_orig) bbox = super().get_window_extent(renderer).frozen() self.set_transform(tr) self.set_rotation(angle_orig) return bbox class AxisLabel(AttributeCopier, LabelBase): def __init__(self, *args, axis_direction='bottom', axis=None, **kwargs): self._axis = axis self._pad = 5 self._external_pad = 0 LabelBase.__init__(self, *args, **kwargs) self.set_axis_direction(axis_direction) def set_pad(self, pad): self._pad = pad def get_pad(self): return self._pad def get_ref_artist(self): return self._axis.get_label() def get_text(self): t = super().get_text() if t == '__from_axes__': return self._axis.get_label().get_text() return self._text _default_alignments = dict(left=('bottom', 'center'), right=('top', 'center'), bottom=('top', 'center'), top=('bottom', 'center')) def set_default_alignment(self, d): (va, ha) = _api.check_getitem(self._default_alignments, d=d) self.set_va(va) self.set_ha(ha) _default_angles = dict(left=180, right=0, bottom=0, top=180) def set_default_angle(self, d): self.set_rotation(_api.check_getitem(self._default_angles, d=d)) def set_axis_direction(self, d): self.set_default_alignment(d) self.set_default_angle(d) def get_color(self): return self.get_attribute_from_ref_artist('color') def draw(self, renderer): if not self.get_visible(): return self._offset_radius = self._external_pad + renderer.points_to_pixels(self.get_pad()) super().draw(renderer) def get_window_extent(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() if not self.get_visible(): return r = self._external_pad + renderer.points_to_pixels(self.get_pad()) self._offset_radius = r bb = super().get_window_extent(renderer) return bb class TickLabels(AxisLabel): def __init__(self, *, axis_direction='bottom', **kwargs): super().__init__(**kwargs) self.set_axis_direction(axis_direction) self._axislabel_pad = 0 def get_ref_artist(self): return self._axis.get_ticklabels()[0] def set_axis_direction(self, label_direction): self.set_default_alignment(label_direction) self.set_default_angle(label_direction) self._axis_direction = label_direction def invert_axis_direction(self): label_direction = self._get_opposite_direction(self._axis_direction) self.set_axis_direction(label_direction) def _get_ticklabels_offsets(self, renderer, label_direction): whd_list = self.get_texts_widths_heights_descents(renderer) if not whd_list: return (0, 0) r = 0 (va, ha) = (self.get_va(), self.get_ha()) if label_direction == 'left': pad = max((w for (w, h, d) in whd_list)) if ha == 'left': r = pad elif ha == 'center': r = 0.5 * pad elif label_direction == 'right': pad = max((w for (w, h, d) in whd_list)) if ha == 'right': r = pad elif ha == 'center': r = 0.5 * pad elif label_direction == 'bottom': pad = max((h for (w, h, d) in whd_list)) if va == 'bottom': r = pad elif va == 'center': r = 0.5 * pad elif va == 'baseline': max_ascent = max((h - d for (w, h, d) in whd_list)) max_descent = max((d for (w, h, d) in whd_list)) r = max_ascent pad = max_ascent + max_descent elif label_direction == 'top': pad = max((h for (w, h, d) in whd_list)) if va == 'top': r = pad elif va == 'center': r = 0.5 * pad elif va == 'baseline': max_ascent = max((h - d for (w, h, d) in whd_list)) max_descent = max((d for (w, h, d) in whd_list)) r = max_descent pad = max_ascent + max_descent return (r, pad) _default_alignments = dict(left=('center', 'right'), right=('center', 'left'), bottom=('baseline', 'center'), top=('baseline', 'center')) _default_angles = dict(left=90, right=-90, bottom=0, top=180) def draw(self, renderer): if not self.get_visible(): self._axislabel_pad = self._external_pad return (r, total_width) = self._get_ticklabels_offsets(renderer, self._axis_direction) pad = self._external_pad + renderer.points_to_pixels(self.get_pad()) self._offset_radius = r + pad for ((x, y), a, l) in self._locs_angles_labels: if not l.strip(): continue self._ref_angle = a self.set_x(x) self.set_y(y) self.set_text(l) LabelBase.draw(self, renderer) self._axislabel_pad = total_width + pad def set_locs_angles_labels(self, locs_angles_labels): self._locs_angles_labels = locs_angles_labels def get_window_extents(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() if not self.get_visible(): self._axislabel_pad = self._external_pad return [] bboxes = [] (r, total_width) = self._get_ticklabels_offsets(renderer, self._axis_direction) pad = self._external_pad + renderer.points_to_pixels(self.get_pad()) self._offset_radius = r + pad for ((x, y), a, l) in self._locs_angles_labels: self._ref_angle = a self.set_x(x) self.set_y(y) self.set_text(l) bb = LabelBase.get_window_extent(self, renderer) bboxes.append(bb) self._axislabel_pad = total_width + pad return bboxes def get_texts_widths_heights_descents(self, renderer): whd_list = [] for (_loc, _angle, label) in self._locs_angles_labels: if not label.strip(): continue (clean_line, ismath) = self._preprocess_math(label) whd = renderer.get_text_width_height_descent(clean_line, self._fontproperties, ismath=ismath) whd_list.append(whd) return whd_list class GridlinesCollection(LineCollection): def __init__(self, *args, which='major', axis='both', **kwargs): self._which = which self._axis = axis super().__init__(*args, **kwargs) self.set_grid_helper(None) def set_which(self, which): self._which = which def set_axis(self, axis): self._axis = axis def set_grid_helper(self, grid_helper): self._grid_helper = grid_helper def draw(self, renderer): if self._grid_helper is not None: self._grid_helper.update_lim(self.axes) gl = self._grid_helper.get_gridlines(self._which, self._axis) self.set_segments([np.transpose(l) for l in gl]) super().draw(renderer) class AxisArtist(martist.Artist): zorder = 2.5 @property def LABELPAD(self): return self.label.get_pad() @LABELPAD.setter def LABELPAD(self, v): self.label.set_pad(v) def __init__(self, axes, helper, offset=None, axis_direction='bottom', **kwargs): super().__init__(**kwargs) self.axes = axes self._axis_artist_helper = helper if offset is None: offset = (0, 0) self.offset_transform = ScaledTranslation(*offset, Affine2D().scale(1 / 72) + self.axes.get_figure(root=False).dpi_scale_trans) if axis_direction in ['left', 'right']: self.axis = axes.yaxis else: self.axis = axes.xaxis self._axisline_style = None self._axis_direction = axis_direction self._init_line() self._init_ticks(**kwargs) self._init_offsetText(axis_direction) self._init_label() self._ticklabel_add_angle = 0.0 self._axislabel_add_angle = 0.0 self.set_axis_direction(axis_direction) def set_axis_direction(self, axis_direction): self.major_ticklabels.set_axis_direction(axis_direction) self.label.set_axis_direction(axis_direction) self._axis_direction = axis_direction if axis_direction in ['left', 'top']: self.set_ticklabel_direction('-') self.set_axislabel_direction('-') else: self.set_ticklabel_direction('+') self.set_axislabel_direction('+') def set_ticklabel_direction(self, tick_direction): self._ticklabel_add_angle = _api.check_getitem({'+': 0, '-': 180}, tick_direction=tick_direction) def invert_ticklabel_direction(self): self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360 self.major_ticklabels.invert_axis_direction() self.minor_ticklabels.invert_axis_direction() def set_axislabel_direction(self, label_direction): self._axislabel_add_angle = _api.check_getitem({'+': 0, '-': 180}, label_direction=label_direction) def get_transform(self): return self.axes.transAxes + self.offset_transform def get_helper(self): return self._axis_artist_helper def set_axisline_style(self, axisline_style=None, **kwargs): if axisline_style is None: return AxislineStyle.pprint_styles() if isinstance(axisline_style, AxislineStyle._Base): self._axisline_style = axisline_style else: self._axisline_style = AxislineStyle(axisline_style, **kwargs) self._init_line() def get_axisline_style(self): return self._axisline_style def _init_line(self): tran = self._axis_artist_helper.get_line_transform(self.axes) + self.offset_transform axisline_style = self.get_axisline_style() if axisline_style is None: self.line = PathPatch(self._axis_artist_helper.get_line(self.axes), color=mpl.rcParams['axes.edgecolor'], fill=False, linewidth=mpl.rcParams['axes.linewidth'], capstyle=mpl.rcParams['lines.solid_capstyle'], joinstyle=mpl.rcParams['lines.solid_joinstyle'], transform=tran) else: self.line = axisline_style(self, transform=tran) def _draw_line(self, renderer): self.line.set_path(self._axis_artist_helper.get_line(self.axes)) if self.get_axisline_style() is not None: self.line.set_line_mutation_scale(self.major_ticklabels.get_size()) self.line.draw(renderer) def _init_ticks(self, **kwargs): axis_name = self.axis.axis_name trans = self._axis_artist_helper.get_tick_transform(self.axes) + self.offset_transform self.major_ticks = Ticks(kwargs.get('major_tick_size', mpl.rcParams[f'{axis_name}tick.major.size']), axis=self.axis, transform=trans) self.minor_ticks = Ticks(kwargs.get('minor_tick_size', mpl.rcParams[f'{axis_name}tick.minor.size']), axis=self.axis, transform=trans) size = mpl.rcParams[f'{axis_name}tick.labelsize'] self.major_ticklabels = TickLabels(axis=self.axis, axis_direction=self._axis_direction, figure=self.axes.get_figure(root=False), transform=trans, fontsize=size, pad=kwargs.get('major_tick_pad', mpl.rcParams[f'{axis_name}tick.major.pad'])) self.minor_ticklabels = TickLabels(axis=self.axis, axis_direction=self._axis_direction, figure=self.axes.get_figure(root=False), transform=trans, fontsize=size, pad=kwargs.get('minor_tick_pad', mpl.rcParams[f'{axis_name}tick.minor.pad'])) def _get_tick_info(self, tick_iter): ticks_loc_angle = [] ticklabels_loc_angle_label = [] ticklabel_add_angle = self._ticklabel_add_angle for (loc, angle_normal, angle_tangent, label) in tick_iter: angle_label = angle_tangent - 90 + ticklabel_add_angle angle_tick = angle_normal if 90 <= (angle_label - angle_normal) % 360 <= 270 else angle_normal + 180 ticks_loc_angle.append([loc, angle_tick]) ticklabels_loc_angle_label.append([loc, angle_label, label]) return (ticks_loc_angle, ticklabels_loc_angle_label) def _update_ticks(self, renderer=None): if renderer is None: renderer = self.get_figure(root=True)._get_renderer() dpi_cor = renderer.points_to_pixels(1.0) if self.major_ticks.get_visible() and self.major_ticks.get_tick_out(): ticklabel_pad = self.major_ticks._ticksize * dpi_cor self.major_ticklabels._external_pad = ticklabel_pad self.minor_ticklabels._external_pad = ticklabel_pad else: self.major_ticklabels._external_pad = 0 self.minor_ticklabels._external_pad = 0 (majortick_iter, minortick_iter) = self._axis_artist_helper.get_tick_iterators(self.axes) (tick_loc_angle, ticklabel_loc_angle_label) = self._get_tick_info(majortick_iter) self.major_ticks.set_locs_angles(tick_loc_angle) self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label) (tick_loc_angle, ticklabel_loc_angle_label) = self._get_tick_info(minortick_iter) self.minor_ticks.set_locs_angles(tick_loc_angle) self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label) def _draw_ticks(self, renderer): self._update_ticks(renderer) self.major_ticks.draw(renderer) self.major_ticklabels.draw(renderer) self.minor_ticks.draw(renderer) self.minor_ticklabels.draw(renderer) if self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible(): self._draw_offsetText(renderer) _offsetText_pos = dict(left=(0, 1, 'bottom', 'right'), right=(1, 1, 'bottom', 'left'), bottom=(1, 0, 'top', 'right'), top=(1, 1, 'bottom', 'right')) def _init_offsetText(self, direction): (x, y, va, ha) = self._offsetText_pos[direction] self.offsetText = mtext.Annotation('', xy=(x, y), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', color=mpl.rcParams['xtick.color'], horizontalalignment=ha, verticalalignment=va) self.offsetText.set_transform(IdentityTransform()) self.axes._set_artist_props(self.offsetText) def _update_offsetText(self): self.offsetText.set_text(self.axis.major.formatter.get_offset()) self.offsetText.set_size(self.major_ticklabels.get_size()) offset = self.major_ticklabels.get_pad() + self.major_ticklabels.get_size() + 2 self.offsetText.xyann = (0, offset) def _draw_offsetText(self, renderer): self._update_offsetText() self.offsetText.draw(renderer) def _init_label(self, **kwargs): tr = self._axis_artist_helper.get_axislabel_transform(self.axes) + self.offset_transform self.label = AxisLabel(0, 0, '__from_axes__', color='auto', fontsize=kwargs.get('labelsize', mpl.rcParams['axes.labelsize']), fontweight=mpl.rcParams['axes.labelweight'], axis=self.axis, transform=tr, axis_direction=self._axis_direction) self.label.set_figure(self.axes.get_figure(root=False)) labelpad = kwargs.get('labelpad', 5) self.label.set_pad(labelpad) def _update_label(self, renderer): if not self.label.get_visible(): return if self._ticklabel_add_angle != self._axislabel_add_angle: if self.major_ticks.get_visible() and (not self.major_ticks.get_tick_out()) or (self.minor_ticks.get_visible() and (not self.major_ticks.get_tick_out())): axislabel_pad = self.major_ticks._ticksize else: axislabel_pad = 0 else: axislabel_pad = max(self.major_ticklabels._axislabel_pad, self.minor_ticklabels._axislabel_pad) self.label._external_pad = axislabel_pad (xy, angle_tangent) = self._axis_artist_helper.get_axislabel_pos_angle(self.axes) if xy is None: return angle_label = angle_tangent - 90 (x, y) = xy self.label._ref_angle = angle_label + self._axislabel_add_angle self.label.set(x=x, y=y) def _draw_label(self, renderer): self._update_label(renderer) self.label.draw(renderer) def set_label(self, s): self.label.set_text(s) def get_tightbbox(self, renderer=None): if not self.get_visible(): return self._axis_artist_helper.update_lim(self.axes) self._update_ticks(renderer) self._update_label(renderer) self.line.set_path(self._axis_artist_helper.get_line(self.axes)) if self.get_axisline_style() is not None: self.line.set_line_mutation_scale(self.major_ticklabels.get_size()) bb = [*self.major_ticklabels.get_window_extents(renderer), *self.minor_ticklabels.get_window_extents(renderer), self.label.get_window_extent(renderer), self.offsetText.get_window_extent(renderer), self.line.get_window_extent(renderer)] bb = [b for b in bb if b and (b.width != 0 or b.height != 0)] if bb: _bbox = Bbox.union(bb) return _bbox else: return None @martist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group(__name__, gid=self.get_gid()) self._axis_artist_helper.update_lim(self.axes) self._draw_ticks(renderer) self._draw_line(renderer) self._draw_label(renderer) renderer.close_group(__name__) def toggle(self, all=None, ticks=None, ticklabels=None, label=None): if all: (_ticks, _ticklabels, _label) = (True, True, True) elif all is not None: (_ticks, _ticklabels, _label) = (False, False, False) else: (_ticks, _ticklabels, _label) = (None, None, None) if ticks is not None: _ticks = ticks if ticklabels is not None: _ticklabels = ticklabels if label is not None: _label = label if _ticks is not None: self.major_ticks.set_visible(_ticks) self.minor_ticks.set_visible(_ticks) if _ticklabels is not None: self.major_ticklabels.set_visible(_ticklabels) self.minor_ticklabels.set_visible(_ticklabels) if _label is not None: self.label.set_visible(_label) # File: matplotlib-main/lib/mpl_toolkits/axisartist/axisline_style.py """""" import math import numpy as np import matplotlib as mpl from matplotlib.patches import _Style, FancyArrowPatch from matplotlib.path import Path from matplotlib.transforms import IdentityTransform class _FancyAxislineStyle: class SimpleArrow(FancyArrowPatch): _ARROW_STYLE = '->' def __init__(self, axis_artist, line_path, transform, line_mutation_scale): self._axis_artist = axis_artist self._line_transform = transform self._line_path = line_path self._line_mutation_scale = line_mutation_scale FancyArrowPatch.__init__(self, path=self._line_path, arrowstyle=self._ARROW_STYLE, patchA=None, patchB=None, shrinkA=0.0, shrinkB=0.0, mutation_scale=line_mutation_scale, mutation_aspect=None, transform=IdentityTransform()) def set_line_mutation_scale(self, scale): self.set_mutation_scale(scale * self._line_mutation_scale) def _extend_path(self, path, mutation_size=10): ((x0, y0), (x1, y1)) = path.vertices[-2:] theta = math.atan2(y1 - y0, x1 - x0) x2 = x1 + math.cos(theta) * mutation_size y2 = y1 + math.sin(theta) * mutation_size if path.codes is None: return Path(np.concatenate([path.vertices, [[x2, y2]]])) else: return Path(np.concatenate([path.vertices, [[x2, y2]]]), np.concatenate([path.codes, [Path.LINETO]])) def set_path(self, path): self._line_path = path def draw(self, renderer): path_in_disp = self._line_transform.transform_path(self._line_path) mutation_size = self.get_mutation_scale() extended_path = self._extend_path(path_in_disp, mutation_size=mutation_size) self._path_original = extended_path FancyArrowPatch.draw(self, renderer) def get_window_extent(self, renderer=None): path_in_disp = self._line_transform.transform_path(self._line_path) mutation_size = self.get_mutation_scale() extended_path = self._extend_path(path_in_disp, mutation_size=mutation_size) self._path_original = extended_path return FancyArrowPatch.get_window_extent(self, renderer) class FilledArrow(SimpleArrow): _ARROW_STYLE = '-|>' def __init__(self, axis_artist, line_path, transform, line_mutation_scale, facecolor): super().__init__(axis_artist, line_path, transform, line_mutation_scale) self.set_facecolor(facecolor) class AxislineStyle(_Style): _style_list = {} class _Base: def __init__(self): super().__init__() def __call__(self, axis_artist, transform): return self.new_line(axis_artist, transform) class SimpleArrow(_Base): ArrowAxisClass = _FancyAxislineStyle.SimpleArrow def __init__(self, size=1): self.size = size super().__init__() def new_line(self, axis_artist, transform): linepath = Path([(0, 0), (0, 1)]) axisline = self.ArrowAxisClass(axis_artist, linepath, transform, line_mutation_scale=self.size) return axisline _style_list['->'] = SimpleArrow class FilledArrow(SimpleArrow): ArrowAxisClass = _FancyAxislineStyle.FilledArrow def __init__(self, size=1, facecolor=None): if facecolor is None: facecolor = mpl.rcParams['axes.edgecolor'] self.size = size self._facecolor = facecolor super().__init__(size=size) def new_line(self, axis_artist, transform): linepath = Path([(0, 0), (0, 1)]) axisline = self.ArrowAxisClass(axis_artist, linepath, transform, line_mutation_scale=self.size, facecolor=self._facecolor) return axisline _style_list['-|>'] = FilledArrow # File: matplotlib-main/lib/mpl_toolkits/axisartist/axislines.py """""" import numpy as np import matplotlib as mpl from matplotlib import _api import matplotlib.axes as maxes from matplotlib.path import Path from mpl_toolkits.axes_grid1 import mpl_axes from .axisline_style import AxislineStyle from .axis_artist import AxisArtist, GridlinesCollection class _AxisArtistHelperBase: def __init__(self, nth_coord): self.nth_coord = nth_coord def update_lim(self, axes): pass def get_nth_coord(self): return self.nth_coord def _to_xy(self, values, const): if self.nth_coord == 0: return np.stack(np.broadcast_arrays(values, const), axis=-1) elif self.nth_coord == 1: return np.stack(np.broadcast_arrays(const, values), axis=-1) else: raise ValueError('Unexpected nth_coord') class _FixedAxisArtistHelperBase(_AxisArtistHelperBase): @_api.delete_parameter('3.9', 'nth_coord') def __init__(self, loc, nth_coord=None): super().__init__(_api.check_getitem({'bottom': 0, 'top': 0, 'left': 1, 'right': 1}, loc=loc)) self._loc = loc self._pos = {'bottom': 0, 'top': 1, 'left': 0, 'right': 1}[loc] self._path = Path(self._to_xy((0, 1), const=self._pos)) def get_line(self, axes): return self._path def get_line_transform(self, axes): return axes.transAxes def get_axislabel_transform(self, axes): return axes.transAxes def get_axislabel_pos_angle(self, axes): return dict(left=((0.0, 0.5), 90), right=((1.0, 0.5), 90), bottom=((0.5, 0.0), 0), top=((0.5, 1.0), 0))[self._loc] def get_tick_transform(self, axes): return [axes.get_xaxis_transform(), axes.get_yaxis_transform()][self.nth_coord] class _FloatingAxisArtistHelperBase(_AxisArtistHelperBase): def __init__(self, nth_coord, value): self._value = value super().__init__(nth_coord) def get_line(self, axes): raise RuntimeError('get_line method should be defined by the derived class') class FixedAxisArtistHelperRectilinear(_FixedAxisArtistHelperBase): @_api.delete_parameter('3.9', 'nth_coord') def __init__(self, axes, loc, nth_coord=None): super().__init__(loc) self.axis = [axes.xaxis, axes.yaxis][self.nth_coord] def get_tick_iterators(self, axes): (angle_normal, angle_tangent) = {0: (90, 0), 1: (0, 90)}[self.nth_coord] major = self.axis.major major_locs = major.locator() major_labels = major.formatter.format_ticks(major_locs) minor = self.axis.minor minor_locs = minor.locator() minor_labels = minor.formatter.format_ticks(minor_locs) tick_to_axes = self.get_tick_transform(axes) - axes.transAxes def _f(locs, labels): for (loc, label) in zip(locs, labels): c = self._to_xy(loc, const=self._pos) c2 = tick_to_axes.transform(c) if mpl.transforms._interval_contains_close((0, 1), c2[self.nth_coord]): yield (c, angle_normal, angle_tangent, label) return (_f(major_locs, major_labels), _f(minor_locs, minor_labels)) class FloatingAxisArtistHelperRectilinear(_FloatingAxisArtistHelperBase): def __init__(self, axes, nth_coord, passingthrough_point, axis_direction='bottom'): super().__init__(nth_coord, passingthrough_point) self._axis_direction = axis_direction self.axis = [axes.xaxis, axes.yaxis][self.nth_coord] def get_line(self, axes): fixed_coord = 1 - self.nth_coord data_to_axes = axes.transData - axes.transAxes p = data_to_axes.transform([self._value, self._value]) return Path(self._to_xy((0, 1), const=p[fixed_coord])) def get_line_transform(self, axes): return axes.transAxes def get_axislabel_transform(self, axes): return axes.transAxes def get_axislabel_pos_angle(self, axes): angle = [0, 90][self.nth_coord] fixed_coord = 1 - self.nth_coord data_to_axes = axes.transData - axes.transAxes p = data_to_axes.transform([self._value, self._value]) verts = self._to_xy(0.5, const=p[fixed_coord]) return (verts, angle) if 0 <= verts[fixed_coord] <= 1 else (None, None) def get_tick_transform(self, axes): return axes.transData def get_tick_iterators(self, axes): (angle_normal, angle_tangent) = {0: (90, 0), 1: (0, 90)}[self.nth_coord] major = self.axis.major major_locs = major.locator() major_labels = major.formatter.format_ticks(major_locs) minor = self.axis.minor minor_locs = minor.locator() minor_labels = minor.formatter.format_ticks(minor_locs) data_to_axes = axes.transData - axes.transAxes def _f(locs, labels): for (loc, label) in zip(locs, labels): c = self._to_xy(loc, const=self._value) (c1, c2) = data_to_axes.transform(c) if 0 <= c1 <= 1 and 0 <= c2 <= 1: yield (c, angle_normal, angle_tangent, label) return (_f(major_locs, major_labels), _f(minor_locs, minor_labels)) class AxisArtistHelper: Fixed = _FixedAxisArtistHelperBase Floating = _FloatingAxisArtistHelperBase class AxisArtistHelperRectlinear: Fixed = FixedAxisArtistHelperRectilinear Floating = FloatingAxisArtistHelperRectilinear class GridHelperBase: def __init__(self): self._old_limits = None super().__init__() def update_lim(self, axes): (x1, x2) = axes.get_xlim() (y1, y2) = axes.get_ylim() if self._old_limits != (x1, x2, y1, y2): self._update_grid(x1, y1, x2, y2) self._old_limits = (x1, x2, y1, y2) def _update_grid(self, x1, y1, x2, y2): def get_gridlines(self, which, axis): return [] class GridHelperRectlinear(GridHelperBase): def __init__(self, axes): super().__init__() self.axes = axes @_api.delete_parameter('3.9', 'nth_coord', addendum="'nth_coord' is now inferred from 'loc'.") def new_fixed_axis(self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None): if axes is None: _api.warn_external("'new_fixed_axis' explicitly requires the axes keyword.") axes = self.axes if axis_direction is None: axis_direction = loc return AxisArtist(axes, FixedAxisArtistHelperRectilinear(axes, loc), offset=offset, axis_direction=axis_direction) def new_floating_axis(self, nth_coord, value, axis_direction='bottom', axes=None): if axes is None: _api.warn_external("'new_floating_axis' explicitly requires the axes keyword.") axes = self.axes helper = FloatingAxisArtistHelperRectilinear(axes, nth_coord, value, axis_direction) axisline = AxisArtist(axes, helper, axis_direction=axis_direction) axisline.line.set_clip_on(True) axisline.line.set_clip_box(axisline.axes.bbox) return axisline def get_gridlines(self, which='major', axis='both'): _api.check_in_list(['both', 'major', 'minor'], which=which) _api.check_in_list(['both', 'x', 'y'], axis=axis) gridlines = [] if axis in ('both', 'x'): locs = [] (y1, y2) = self.axes.get_ylim() if which in ('both', 'major'): locs.extend(self.axes.xaxis.major.locator()) if which in ('both', 'minor'): locs.extend(self.axes.xaxis.minor.locator()) gridlines.extend(([[x, x], [y1, y2]] for x in locs)) if axis in ('both', 'y'): (x1, x2) = self.axes.get_xlim() locs = [] if self.axes.yaxis._major_tick_kw['gridOn']: locs.extend(self.axes.yaxis.major.locator()) if self.axes.yaxis._minor_tick_kw['gridOn']: locs.extend(self.axes.yaxis.minor.locator()) gridlines.extend(([[x1, x2], [y, y]] for y in locs)) return gridlines class Axes(maxes.Axes): @_api.deprecated('3.8', alternative='ax.axis') def __call__(self, *args, **kwargs): return maxes.Axes.axis(self.axes, *args, **kwargs) def __init__(self, *args, grid_helper=None, **kwargs): self._axisline_on = True self._grid_helper = grid_helper if grid_helper else GridHelperRectlinear(self) super().__init__(*args, **kwargs) self.toggle_axisline(True) def toggle_axisline(self, b=None): if b is None: b = not self._axisline_on if b: self._axisline_on = True self.spines[:].set_visible(False) self.xaxis.set_visible(False) self.yaxis.set_visible(False) else: self._axisline_on = False self.spines[:].set_visible(True) self.xaxis.set_visible(True) self.yaxis.set_visible(True) @property def axis(self): return self._axislines def clear(self): self.gridlines = gridlines = GridlinesCollection([], colors=mpl.rcParams['grid.color'], linestyles=mpl.rcParams['grid.linestyle'], linewidths=mpl.rcParams['grid.linewidth']) self._set_artist_props(gridlines) gridlines.set_grid_helper(self.get_grid_helper()) super().clear() gridlines.set_clip_path(self.axes.patch) self._axislines = mpl_axes.Axes.AxisDict(self) new_fixed_axis = self.get_grid_helper().new_fixed_axis self._axislines.update({loc: new_fixed_axis(loc=loc, axes=self, axis_direction=loc) for loc in ['bottom', 'top', 'left', 'right']}) for axisline in [self._axislines['top'], self._axislines['right']]: axisline.label.set_visible(False) axisline.major_ticklabels.set_visible(False) axisline.minor_ticklabels.set_visible(False) def get_grid_helper(self): return self._grid_helper def grid(self, visible=None, which='major', axis='both', **kwargs): super().grid(visible, which=which, axis=axis, **kwargs) if not self._axisline_on: return if visible is None: visible = self.axes.xaxis._minor_tick_kw['gridOn'] or self.axes.xaxis._major_tick_kw['gridOn'] or self.axes.yaxis._minor_tick_kw['gridOn'] or self.axes.yaxis._major_tick_kw['gridOn'] self.gridlines.set(which=which, axis=axis, visible=visible) self.gridlines.set(**kwargs) def get_children(self): if self._axisline_on: children = [*self._axislines.values(), self.gridlines] else: children = [] children.extend(super().get_children()) return children def new_fixed_axis(self, loc, offset=None): return self.get_grid_helper().new_fixed_axis(loc, offset=offset, axes=self) def new_floating_axis(self, nth_coord, value, axis_direction='bottom'): return self.get_grid_helper().new_floating_axis(nth_coord, value, axis_direction=axis_direction, axes=self) class AxesZero(Axes): def clear(self): super().clear() new_floating_axis = self.get_grid_helper().new_floating_axis self._axislines.update(xzero=new_floating_axis(nth_coord=0, value=0.0, axis_direction='bottom', axes=self), yzero=new_floating_axis(nth_coord=1, value=0.0, axis_direction='left', axes=self)) for k in ['xzero', 'yzero']: self._axislines[k].line.set_clip_path(self.patch) self._axislines[k].set_visible(False) Subplot = Axes SubplotZero = AxesZero # File: matplotlib-main/lib/mpl_toolkits/axisartist/floating_axes.py """""" import functools import numpy as np import matplotlib as mpl from matplotlib import _api, cbook import matplotlib.patches as mpatches from matplotlib.path import Path from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory from . import axislines, grid_helper_curvelinear from .axis_artist import AxisArtist from .grid_finder import ExtremeFinderSimple class FloatingAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper): pass class FixedAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper): def __init__(self, grid_helper, side, nth_coord_ticks=None): (lon1, lon2, lat1, lat2) = grid_helper.grid_finder.extreme_finder(*[None] * 5) (value, nth_coord) = _api.check_getitem(dict(left=(lon1, 0), right=(lon2, 0), bottom=(lat1, 1), top=(lat2, 1)), side=side) super().__init__(grid_helper, nth_coord, value, axis_direction=side) if nth_coord_ticks is None: nth_coord_ticks = nth_coord self.nth_coord_ticks = nth_coord_ticks self.value = value self.grid_helper = grid_helper self._side = side def update_lim(self, axes): self.grid_helper.update_lim(axes) self._grid_info = self.grid_helper._grid_info def get_tick_iterators(self, axes): grid_finder = self.grid_helper.grid_finder (lat_levs, lat_n, lat_factor) = self._grid_info['lat_info'] yy0 = lat_levs / lat_factor (lon_levs, lon_n, lon_factor) = self._grid_info['lon_info'] xx0 = lon_levs / lon_factor extremes = self.grid_helper.grid_finder.extreme_finder(*[None] * 5) (xmin, xmax) = sorted(extremes[:2]) (ymin, ymax) = sorted(extremes[2:]) def trf_xy(x, y): trf = grid_finder.get_transform() + axes.transData return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T if self.nth_coord == 0: mask = (ymin <= yy0) & (yy0 <= ymax) ((xx1, yy1), (dxx1, dyy1), (dxx2, dyy2)) = grid_helper_curvelinear._value_and_jacobian(trf_xy, self.value, yy0[mask], (xmin, xmax), (ymin, ymax)) labels = self._grid_info['lat_labels'] elif self.nth_coord == 1: mask = (xmin <= xx0) & (xx0 <= xmax) ((xx1, yy1), (dxx2, dyy2), (dxx1, dyy1)) = grid_helper_curvelinear._value_and_jacobian(trf_xy, xx0[mask], self.value, (xmin, xmax), (ymin, ymax)) labels = self._grid_info['lon_labels'] labels = [l for (l, m) in zip(labels, mask) if m] angle_normal = np.arctan2(dyy1, dxx1) angle_tangent = np.arctan2(dyy2, dxx2) mm = (dyy1 == 0) & (dxx1 == 0) angle_normal[mm] = angle_tangent[mm] + np.pi / 2 tick_to_axes = self.get_tick_transform(axes) - axes.transAxes in_01 = functools.partial(mpl.transforms._interval_contains_close, (0, 1)) def f1(): for (x, y, normal, tangent, lab) in zip(xx1, yy1, angle_normal, angle_tangent, labels): c2 = tick_to_axes.transform((x, y)) if in_01(c2[0]) and in_01(c2[1]): yield ([x, y], *np.rad2deg([normal, tangent]), lab) return (f1(), iter([])) def get_line(self, axes): self.update_lim(axes) (k, v) = dict(left=('lon_lines0', 0), right=('lon_lines0', 1), bottom=('lat_lines0', 0), top=('lat_lines0', 1))[self._side] (xx, yy) = self._grid_info[k][v] return Path(np.column_stack([xx, yy])) class ExtremeFinderFixed(ExtremeFinderSimple): def __init__(self, extremes): self._extremes = extremes def __call__(self, transform_xy, x1, y1, x2, y2): return self._extremes class GridHelperCurveLinear(grid_helper_curvelinear.GridHelperCurveLinear): def __init__(self, aux_trans, extremes, grid_locator1=None, grid_locator2=None, tick_formatter1=None, tick_formatter2=None): super().__init__(aux_trans, extreme_finder=ExtremeFinderFixed(extremes), grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1, tick_formatter2=tick_formatter2) @_api.deprecated('3.8') def get_data_boundary(self, side): (lon1, lon2, lat1, lat2) = self.grid_finder.extreme_finder(*[None] * 5) return dict(left=(lon1, 0), right=(lon2, 0), bottom=(lat1, 1), top=(lat2, 1))[side] def new_fixed_axis(self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None): if axes is None: axes = self.axes if axis_direction is None: axis_direction = loc helper = FixedAxisArtistHelper(self, loc, nth_coord_ticks=nth_coord) axisline = AxisArtist(axes, helper, axis_direction=axis_direction) axisline.line.set_clip_on(True) axisline.line.set_clip_box(axisline.axes.bbox) return axisline def _update_grid(self, x1, y1, x2, y2): if self._grid_info is None: self._grid_info = dict() grid_info = self._grid_info grid_finder = self.grid_finder extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy, x1, y1, x2, y2) (lon_min, lon_max) = sorted(extremes[:2]) (lat_min, lat_max) = sorted(extremes[2:]) grid_info['extremes'] = (lon_min, lon_max, lat_min, lat_max) (lon_levs, lon_n, lon_factor) = grid_finder.grid_locator1(lon_min, lon_max) lon_levs = np.asarray(lon_levs) (lat_levs, lat_n, lat_factor) = grid_finder.grid_locator2(lat_min, lat_max) lat_levs = np.asarray(lat_levs) grid_info['lon_info'] = (lon_levs, lon_n, lon_factor) grid_info['lat_info'] = (lat_levs, lat_n, lat_factor) grid_info['lon_labels'] = grid_finder._format_ticks(1, 'bottom', lon_factor, lon_levs) grid_info['lat_labels'] = grid_finder._format_ticks(2, 'bottom', lat_factor, lat_levs) lon_values = lon_levs[:lon_n] / lon_factor lat_values = lat_levs[:lat_n] / lat_factor (lon_lines, lat_lines) = grid_finder._get_raw_grid_lines(lon_values[(lon_min < lon_values) & (lon_values < lon_max)], lat_values[(lat_min < lat_values) & (lat_values < lat_max)], lon_min, lon_max, lat_min, lat_max) grid_info['lon_lines'] = lon_lines grid_info['lat_lines'] = lat_lines (lon_lines, lat_lines) = grid_finder._get_raw_grid_lines(extremes[:2], extremes[2:], *extremes) grid_info['lon_lines0'] = lon_lines grid_info['lat_lines0'] = lat_lines def get_gridlines(self, which='major', axis='both'): grid_lines = [] if axis in ['both', 'x']: grid_lines.extend(self._grid_info['lon_lines']) if axis in ['both', 'y']: grid_lines.extend(self._grid_info['lat_lines']) return grid_lines class FloatingAxesBase: def __init__(self, *args, grid_helper, **kwargs): _api.check_isinstance(GridHelperCurveLinear, grid_helper=grid_helper) super().__init__(*args, grid_helper=grid_helper, **kwargs) self.set_aspect(1.0) def _gen_axes_patch(self): (x0, x1, y0, y1) = self.get_grid_helper().grid_finder.extreme_finder(*[None] * 5) patch = mpatches.Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) patch.get_path()._interpolation_steps = 100 return patch def clear(self): super().clear() self.patch.set_transform(self.get_grid_helper().grid_finder.get_transform() + self.transData) orig_patch = super()._gen_axes_patch() orig_patch.set_figure(self.get_figure(root=False)) orig_patch.set_transform(self.transAxes) self.patch.set_clip_path(orig_patch) self.gridlines.set_clip_path(orig_patch) self.adjust_axes_lim() def adjust_axes_lim(self): bbox = self.patch.get_path().get_extents(self.patch.get_transform() - self.transData) bbox = bbox.expanded(1.02, 1.02) self.set_xlim(bbox.xmin, bbox.xmax) self.set_ylim(bbox.ymin, bbox.ymax) floatingaxes_class_factory = cbook._make_class_factory(FloatingAxesBase, 'Floating{}') FloatingAxes = floatingaxes_class_factory(host_axes_class_factory(axislines.Axes)) FloatingSubplot = FloatingAxes # File: matplotlib-main/lib/mpl_toolkits/axisartist/grid_finder.py import numpy as np from matplotlib import ticker as mticker, _api from matplotlib.transforms import Bbox, Transform def _find_line_box_crossings(xys, bbox): crossings = [] dxys = xys[1:] - xys[:-1] for sl in [slice(None), slice(None, None, -1)]: (us, vs) = xys.T[sl] (dus, dvs) = dxys.T[sl] (umin, vmin) = bbox.min[sl] (umax, vmax) = bbox.max[sl] for (u0, inside) in [(umin, us > umin), (umax, us < umax)]: cross = [] (idxs,) = (inside[:-1] ^ inside[1:]).nonzero() for idx in idxs: v = vs[idx] + (u0 - us[idx]) * dvs[idx] / dus[idx] if not vmin <= v <= vmax: continue crossing = (u0, v)[sl] theta = np.degrees(np.arctan2(*dxys[idx][::-1])) cross.append((crossing, theta)) crossings.append(cross) return crossings class ExtremeFinderSimple: def __init__(self, nx, ny): self.nx = nx self.ny = ny def __call__(self, transform_xy, x1, y1, x2, y2): (x, y) = np.meshgrid(np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)) (xt, yt) = transform_xy(np.ravel(x), np.ravel(y)) return self._add_pad(xt.min(), xt.max(), yt.min(), yt.max()) def _add_pad(self, x_min, x_max, y_min, y_max): dx = (x_max - x_min) / self.nx dy = (y_max - y_min) / self.ny return (x_min - dx, x_max + dx, y_min - dy, y_max + dy) class _User2DTransform(Transform): input_dims = output_dims = 2 def __init__(self, forward, backward): super().__init__() self._forward = forward self._backward = backward def transform_non_affine(self, values): return np.transpose(self._forward(*np.transpose(values))) def inverted(self): return type(self)(self._backward, self._forward) class GridFinder: def __init__(self, transform, extreme_finder=None, grid_locator1=None, grid_locator2=None, tick_formatter1=None, tick_formatter2=None): if extreme_finder is None: extreme_finder = ExtremeFinderSimple(20, 20) if grid_locator1 is None: grid_locator1 = MaxNLocator() if grid_locator2 is None: grid_locator2 = MaxNLocator() if tick_formatter1 is None: tick_formatter1 = FormatterPrettyPrint() if tick_formatter2 is None: tick_formatter2 = FormatterPrettyPrint() self.extreme_finder = extreme_finder self.grid_locator1 = grid_locator1 self.grid_locator2 = grid_locator2 self.tick_formatter1 = tick_formatter1 self.tick_formatter2 = tick_formatter2 self.set_transform(transform) def _format_ticks(self, idx, direction, factor, levels): fmt = _api.check_getitem({1: self.tick_formatter1, 2: self.tick_formatter2}, idx=idx) return fmt.format_ticks(levels) if isinstance(fmt, mticker.Formatter) else fmt(direction, factor, levels) def get_grid_info(self, x1, y1, x2, y2): extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2) (lon_min, lon_max, lat_min, lat_max) = extremes (lon_levs, lon_n, lon_factor) = self.grid_locator1(lon_min, lon_max) lon_levs = np.asarray(lon_levs) (lat_levs, lat_n, lat_factor) = self.grid_locator2(lat_min, lat_max) lat_levs = np.asarray(lat_levs) lon_values = lon_levs[:lon_n] / lon_factor lat_values = lat_levs[:lat_n] / lat_factor (lon_lines, lat_lines) = self._get_raw_grid_lines(lon_values, lat_values, lon_min, lon_max, lat_min, lat_max) bb = Bbox.from_extents(x1, y1, x2, y2).expanded(1 + 2e-10, 1 + 2e-10) grid_info = {'extremes': extremes} for (idx, lon_or_lat, levs, factor, values, lines) in [(1, 'lon', lon_levs, lon_factor, lon_values, lon_lines), (2, 'lat', lat_levs, lat_factor, lat_values, lat_lines)]: grid_info[lon_or_lat] = gi = {'lines': [[l] for l in lines], 'ticks': {'left': [], 'right': [], 'bottom': [], 'top': []}} for ((lx, ly), v, level) in zip(lines, values, levs): all_crossings = _find_line_box_crossings(np.column_stack([lx, ly]), bb) for (side, crossings) in zip(['left', 'right', 'bottom', 'top'], all_crossings): for crossing in crossings: gi['ticks'][side].append({'level': level, 'loc': crossing}) for side in gi['ticks']: levs = [tick['level'] for tick in gi['ticks'][side]] labels = self._format_ticks(idx, side, factor, levs) for (tick, label) in zip(gi['ticks'][side], labels): tick['label'] = label return grid_info def _get_raw_grid_lines(self, lon_values, lat_values, lon_min, lon_max, lat_min, lat_max): lons_i = np.linspace(lon_min, lon_max, 100) lats_i = np.linspace(lat_min, lat_max, 100) lon_lines = [self.transform_xy(np.full_like(lats_i, lon), lats_i) for lon in lon_values] lat_lines = [self.transform_xy(lons_i, np.full_like(lons_i, lat)) for lat in lat_values] return (lon_lines, lat_lines) def set_transform(self, aux_trans): if isinstance(aux_trans, Transform): self._aux_transform = aux_trans elif len(aux_trans) == 2 and all(map(callable, aux_trans)): self._aux_transform = _User2DTransform(*aux_trans) else: raise TypeError("'aux_trans' must be either a Transform instance or a pair of callables") def get_transform(self): return self._aux_transform update_transform = set_transform def transform_xy(self, x, y): return self._aux_transform.transform(np.column_stack([x, y])).T def inv_transform_xy(self, x, y): return self._aux_transform.inverted().transform(np.column_stack([x, y])).T def update(self, **kwargs): for (k, v) in kwargs.items(): if k in ['extreme_finder', 'grid_locator1', 'grid_locator2', 'tick_formatter1', 'tick_formatter2']: setattr(self, k, v) else: raise ValueError(f'Unknown update property {k!r}') class MaxNLocator(mticker.MaxNLocator): def __init__(self, nbins=10, steps=None, trim=True, integer=False, symmetric=False, prune=None): super().__init__(nbins, steps=steps, integer=integer, symmetric=symmetric, prune=prune) self.create_dummy_axis() def __call__(self, v1, v2): locs = super().tick_values(v1, v2) return (np.array(locs), len(locs), 1) class FixedLocator: def __init__(self, locs): self._locs = locs def __call__(self, v1, v2): (v1, v2) = sorted([v1, v2]) locs = np.array([l for l in self._locs if v1 <= l <= v2]) return (locs, len(locs), 1) class FormatterPrettyPrint: def __init__(self, useMathText=True): self._fmt = mticker.ScalarFormatter(useMathText=useMathText, useOffset=False) self._fmt.create_dummy_axis() def __call__(self, direction, factor, values): return self._fmt.format_ticks(values) class DictFormatter: def __init__(self, format_dict, formatter=None): super().__init__() self._format_dict = format_dict self._fallback_formatter = formatter def __call__(self, direction, factor, values): if self._fallback_formatter: fallback_strings = self._fallback_formatter(direction, factor, values) else: fallback_strings = [''] * len(values) return [self._format_dict.get(k, v) for (k, v) in zip(values, fallback_strings)] # File: matplotlib-main/lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py """""" import functools import numpy as np import matplotlib as mpl from matplotlib import _api from matplotlib.path import Path from matplotlib.transforms import Affine2D, IdentityTransform from .axislines import _FixedAxisArtistHelperBase, _FloatingAxisArtistHelperBase, GridHelperBase from .axis_artist import AxisArtist from .grid_finder import GridFinder def _value_and_jacobian(func, xs, ys, xlims, ylims): eps = np.finfo(float).eps ** (1 / 2) val = func(xs, ys) (xlo, xhi) = sorted(xlims) dxlo = xs - xlo dxhi = xhi - xs xeps = np.take([-1, 1], dxhi >= dxlo) * np.minimum(eps, np.maximum(dxlo, dxhi)) val_dx = func(xs + xeps, ys) (ylo, yhi) = sorted(ylims) dylo = ys - ylo dyhi = yhi - ys yeps = np.take([-1, 1], dyhi >= dylo) * np.minimum(eps, np.maximum(dylo, dyhi)) val_dy = func(xs, ys + yeps) return (val, (val_dx - val) / xeps, (val_dy - val) / yeps) class FixedAxisArtistHelper(_FixedAxisArtistHelperBase): def __init__(self, grid_helper, side, nth_coord_ticks=None): super().__init__(loc=side) self.grid_helper = grid_helper if nth_coord_ticks is None: nth_coord_ticks = self.nth_coord self.nth_coord_ticks = nth_coord_ticks self.side = side def update_lim(self, axes): self.grid_helper.update_lim(axes) def get_tick_transform(self, axes): return axes.transData def get_tick_iterators(self, axes): (v1, v2) = axes.get_ylim() if self.nth_coord == 0 else axes.get_xlim() if v1 > v2: side = {'left': 'right', 'right': 'left', 'top': 'bottom', 'bottom': 'top'}[self.side] else: side = self.side angle_tangent = dict(left=90, right=90, bottom=0, top=0)[side] def iter_major(): for (nth_coord, show_labels) in [(self.nth_coord_ticks, True), (1 - self.nth_coord_ticks, False)]: gi = self.grid_helper._grid_info[['lon', 'lat'][nth_coord]] for tick in gi['ticks'][side]: yield (*tick['loc'], angle_tangent, tick['label'] if show_labels else '') return (iter_major(), iter([])) class FloatingAxisArtistHelper(_FloatingAxisArtistHelperBase): def __init__(self, grid_helper, nth_coord, value, axis_direction=None): super().__init__(nth_coord, value) self.value = value self.grid_helper = grid_helper self._extremes = (-np.inf, np.inf) self._line_num_points = 100 def set_extremes(self, e1, e2): if e1 is None: e1 = -np.inf if e2 is None: e2 = np.inf self._extremes = (e1, e2) def update_lim(self, axes): self.grid_helper.update_lim(axes) (x1, x2) = axes.get_xlim() (y1, y2) = axes.get_ylim() grid_finder = self.grid_helper.grid_finder extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy, x1, y1, x2, y2) (lon_min, lon_max, lat_min, lat_max) = extremes (e_min, e_max) = self._extremes if self.nth_coord == 0: lat_min = max(e_min, lat_min) lat_max = min(e_max, lat_max) elif self.nth_coord == 1: lon_min = max(e_min, lon_min) lon_max = min(e_max, lon_max) (lon_levs, lon_n, lon_factor) = grid_finder.grid_locator1(lon_min, lon_max) (lat_levs, lat_n, lat_factor) = grid_finder.grid_locator2(lat_min, lat_max) if self.nth_coord == 0: xx0 = np.full(self._line_num_points, self.value) yy0 = np.linspace(lat_min, lat_max, self._line_num_points) (xx, yy) = grid_finder.transform_xy(xx0, yy0) elif self.nth_coord == 1: xx0 = np.linspace(lon_min, lon_max, self._line_num_points) yy0 = np.full(self._line_num_points, self.value) (xx, yy) = grid_finder.transform_xy(xx0, yy0) self._grid_info = {'extremes': (lon_min, lon_max, lat_min, lat_max), 'lon_info': (lon_levs, lon_n, np.asarray(lon_factor)), 'lat_info': (lat_levs, lat_n, np.asarray(lat_factor)), 'lon_labels': grid_finder._format_ticks(1, 'bottom', lon_factor, lon_levs), 'lat_labels': grid_finder._format_ticks(2, 'bottom', lat_factor, lat_levs), 'line_xy': (xx, yy)} def get_axislabel_transform(self, axes): return Affine2D() def get_axislabel_pos_angle(self, axes): def trf_xy(x, y): trf = self.grid_helper.grid_finder.get_transform() + axes.transData return trf.transform([x, y]).T (xmin, xmax, ymin, ymax) = self._grid_info['extremes'] if self.nth_coord == 0: xx0 = self.value yy0 = (ymin + ymax) / 2 elif self.nth_coord == 1: xx0 = (xmin + xmax) / 2 yy0 = self.value (xy1, dxy1_dx, dxy1_dy) = _value_and_jacobian(trf_xy, xx0, yy0, (xmin, xmax), (ymin, ymax)) p = axes.transAxes.inverted().transform(xy1) if 0 <= p[0] <= 1 and 0 <= p[1] <= 1: d = [dxy1_dy, dxy1_dx][self.nth_coord] return (xy1, np.rad2deg(np.arctan2(*d[::-1]))) else: return (None, None) def get_tick_transform(self, axes): return IdentityTransform() def get_tick_iterators(self, axes): (lat_levs, lat_n, lat_factor) = self._grid_info['lat_info'] yy0 = lat_levs / lat_factor (lon_levs, lon_n, lon_factor) = self._grid_info['lon_info'] xx0 = lon_levs / lon_factor (e0, e1) = self._extremes def trf_xy(x, y): trf = self.grid_helper.grid_finder.get_transform() + axes.transData return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T if self.nth_coord == 0: mask = (e0 <= yy0) & (yy0 <= e1) ((xx1, yy1), (dxx1, dyy1), (dxx2, dyy2)) = _value_and_jacobian(trf_xy, self.value, yy0[mask], (-np.inf, np.inf), (e0, e1)) labels = self._grid_info['lat_labels'] elif self.nth_coord == 1: mask = (e0 <= xx0) & (xx0 <= e1) ((xx1, yy1), (dxx2, dyy2), (dxx1, dyy1)) = _value_and_jacobian(trf_xy, xx0[mask], self.value, (-np.inf, np.inf), (e0, e1)) labels = self._grid_info['lon_labels'] labels = [l for (l, m) in zip(labels, mask) if m] angle_normal = np.arctan2(dyy1, dxx1) angle_tangent = np.arctan2(dyy2, dxx2) mm = (dyy1 == 0) & (dxx1 == 0) angle_normal[mm] = angle_tangent[mm] + np.pi / 2 tick_to_axes = self.get_tick_transform(axes) - axes.transAxes in_01 = functools.partial(mpl.transforms._interval_contains_close, (0, 1)) def iter_major(): for (x, y, normal, tangent, lab) in zip(xx1, yy1, angle_normal, angle_tangent, labels): c2 = tick_to_axes.transform((x, y)) if in_01(c2[0]) and in_01(c2[1]): yield ([x, y], *np.rad2deg([normal, tangent]), lab) return (iter_major(), iter([])) def get_line_transform(self, axes): return axes.transData def get_line(self, axes): self.update_lim(axes) (x, y) = self._grid_info['line_xy'] return Path(np.column_stack([x, y])) class GridHelperCurveLinear(GridHelperBase): def __init__(self, aux_trans, extreme_finder=None, grid_locator1=None, grid_locator2=None, tick_formatter1=None, tick_formatter2=None): super().__init__() self._grid_info = None self.grid_finder = GridFinder(aux_trans, extreme_finder, grid_locator1, grid_locator2, tick_formatter1, tick_formatter2) def update_grid_finder(self, aux_trans=None, **kwargs): if aux_trans is not None: self.grid_finder.update_transform(aux_trans) self.grid_finder.update(**kwargs) self._old_limits = None @_api.make_keyword_only('3.9', 'nth_coord') def new_fixed_axis(self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None): if axes is None: axes = self.axes if axis_direction is None: axis_direction = loc helper = FixedAxisArtistHelper(self, loc, nth_coord_ticks=nth_coord) axisline = AxisArtist(axes, helper, axis_direction=axis_direction) return axisline def new_floating_axis(self, nth_coord, value, axes=None, axis_direction='bottom'): if axes is None: axes = self.axes helper = FloatingAxisArtistHelper(self, nth_coord, value, axis_direction) axisline = AxisArtist(axes, helper) axisline.line.set_clip_on(True) axisline.line.set_clip_box(axisline.axes.bbox) return axisline def _update_grid(self, x1, y1, x2, y2): self._grid_info = self.grid_finder.get_grid_info(x1, y1, x2, y2) def get_gridlines(self, which='major', axis='both'): grid_lines = [] if axis in ['both', 'x']: for gl in self._grid_info['lon']['lines']: grid_lines.extend(gl) if axis in ['both', 'y']: for gl in self._grid_info['lat']['lines']: grid_lines.extend(gl) return grid_lines @_api.deprecated('3.9') def get_tick_iterator(self, nth_coord, axis_side, minor=False): angle_tangent = dict(left=90, right=90, bottom=0, top=0)[axis_side] lon_or_lat = ['lon', 'lat'][nth_coord] if not minor: for tick in self._grid_info[lon_or_lat]['ticks'][axis_side]: yield (*tick['loc'], angle_tangent, tick['label']) else: for tick in self._grid_info[lon_or_lat]['ticks'][axis_side]: yield (*tick['loc'], angle_tangent, '') # File: matplotlib-main/lib/mpl_toolkits/mplot3d/art3d.py """""" import math import numpy as np from contextlib import contextmanager from matplotlib import _api, artist, cbook, colors as mcolors, lines, text as mtext, path as mpath from matplotlib.collections import Collection, LineCollection, PolyCollection, PatchCollection, PathCollection from matplotlib.colors import Normalize from matplotlib.patches import Patch from . import proj3d def _norm_angle(a): a = (a + 360) % 360 if a > 180: a = a - 360 return a def _norm_text_angle(a): a = (a + 180) % 180 if a > 90: a = a - 180 return a def get_dir_vector(zdir): if zdir == 'x': return np.array((1, 0, 0)) elif zdir == 'y': return np.array((0, 1, 0)) elif zdir == 'z': return np.array((0, 0, 1)) elif zdir is None: return np.array((0, 0, 0)) elif np.iterable(zdir) and len(zdir) == 3: return np.array(zdir) else: raise ValueError("'x', 'y', 'z', None or vector of length 3 expected") class Text3D(mtext.Text): def __init__(self, x=0, y=0, z=0, text='', zdir='z', **kwargs): mtext.Text.__init__(self, x, y, text, **kwargs) self.set_3d_properties(z, zdir) def get_position_3d(self): return (self._x, self._y, self._z) def set_position_3d(self, xyz, zdir=None): super().set_position(xyz[:2]) self.set_z(xyz[2]) if zdir is not None: self._dir_vec = get_dir_vector(zdir) def set_z(self, z): self._z = z self.stale = True def set_3d_properties(self, z=0, zdir='z'): self._z = z self._dir_vec = get_dir_vector(zdir) self.stale = True @artist.allow_rasterization def draw(self, renderer): position3d = np.array((self._x, self._y, self._z)) proj = proj3d._proj_trans_points([position3d, position3d + self._dir_vec], self.axes.M) dx = proj[0][1] - proj[0][0] dy = proj[1][1] - proj[1][0] angle = math.degrees(math.atan2(dy, dx)) with cbook._setattr_cm(self, _x=proj[0][0], _y=proj[1][0], _rotation=_norm_text_angle(angle)): mtext.Text.draw(self, renderer) self.stale = False def get_tightbbox(self, renderer=None): return None def text_2d_to_3d(obj, z=0, zdir='z'): obj.__class__ = Text3D obj.set_3d_properties(z, zdir) class Line3D(lines.Line2D): def __init__(self, xs, ys, zs, *args, **kwargs): super().__init__([], [], *args, **kwargs) self.set_data_3d(xs, ys, zs) def set_3d_properties(self, zs=0, zdir='z'): xs = self.get_xdata() ys = self.get_ydata() zs = cbook._to_unmasked_float_array(zs).ravel() zs = np.broadcast_to(zs, len(xs)) self._verts3d = juggle_axes(xs, ys, zs, zdir) self.stale = True def set_data_3d(self, *args): if len(args) == 1: args = args[0] for (name, xyz) in zip('xyz', args): if not np.iterable(xyz): raise RuntimeError(f'{name} must be a sequence') self._verts3d = args self.stale = True def get_data_3d(self): return self._verts3d @artist.allow_rasterization def draw(self, renderer): (xs3d, ys3d, zs3d) = self._verts3d (xs, ys, zs, tis) = proj3d._proj_transform_clip(xs3d, ys3d, zs3d, self.axes.M, self.axes._focal_length) self.set_data(xs, ys) super().draw(renderer) self.stale = False def line_2d_to_3d(line, zs=0, zdir='z'): line.__class__ = Line3D line.set_3d_properties(zs, zdir) def _path_to_3d_segment(path, zs=0, zdir='z'): zs = np.broadcast_to(zs, len(path)) pathsegs = path.iter_segments(simplify=False, curves=False) seg = [(x, y, z) for (((x, y), code), z) in zip(pathsegs, zs)] seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg] return seg3d def _paths_to_3d_segments(paths, zs=0, zdir='z'): if not np.iterable(zs): zs = np.broadcast_to(zs, len(paths)) elif len(zs) != len(paths): raise ValueError('Number of z-coordinates does not match paths.') segs = [_path_to_3d_segment(path, pathz, zdir) for (path, pathz) in zip(paths, zs)] return segs def _path_to_3d_segment_with_codes(path, zs=0, zdir='z'): zs = np.broadcast_to(zs, len(path)) pathsegs = path.iter_segments(simplify=False, curves=False) seg_codes = [((x, y, z), code) for (((x, y), code), z) in zip(pathsegs, zs)] if seg_codes: (seg, codes) = zip(*seg_codes) seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg] else: seg3d = [] codes = [] return (seg3d, list(codes)) def _paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'): zs = np.broadcast_to(zs, len(paths)) segments_codes = [_path_to_3d_segment_with_codes(path, pathz, zdir) for (path, pathz) in zip(paths, zs)] if segments_codes: (segments, codes) = zip(*segments_codes) else: (segments, codes) = ([], []) return (list(segments), list(codes)) class Collection3D(Collection): def do_3d_projection(self): xyzs_list = [proj3d.proj_transform(*vs.T, self.axes.M) for (vs, _) in self._3dverts_codes] self._paths = [mpath.Path(np.column_stack([xs, ys]), cs) for ((xs, ys, _), (_, cs)) in zip(xyzs_list, self._3dverts_codes)] zs = np.concatenate([zs for (_, _, zs) in xyzs_list]) return zs.min() if len(zs) else 1000000000.0 def collection_2d_to_3d(col, zs=0, zdir='z'): zs = np.broadcast_to(zs, len(col.get_paths())) col._3dverts_codes = [(np.column_stack(juggle_axes(*np.column_stack([p.vertices, np.broadcast_to(z, len(p.vertices))]).T, zdir)), p.codes) for (p, z) in zip(col.get_paths(), zs)] col.__class__ = cbook._make_class_factory(Collection3D, '{}3D')(type(col)) class Line3DCollection(LineCollection): def set_sort_zpos(self, val): self._sort_zpos = val self.stale = True def set_segments(self, segments): self._segments3d = segments super().set_segments([]) def do_3d_projection(self): xyslist = [proj3d._proj_trans_points(points, self.axes.M) for points in self._segments3d] segments_2d = [np.column_stack([xs, ys]) for (xs, ys, zs) in xyslist] LineCollection.set_segments(self, segments_2d) minz = 1000000000.0 for (xs, ys, zs) in xyslist: minz = min(minz, min(zs)) return minz def line_collection_2d_to_3d(col, zs=0, zdir='z'): segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir) col.__class__ = Line3DCollection col.set_segments(segments3d) class Patch3D(Patch): def __init__(self, *args, zs=(), zdir='z', **kwargs): super().__init__(*args, **kwargs) self.set_3d_properties(zs, zdir) def set_3d_properties(self, verts, zs=0, zdir='z'): zs = np.broadcast_to(zs, len(verts)) self._segment3d = [juggle_axes(x, y, z, zdir) for ((x, y), z) in zip(verts, zs)] def get_path(self): if not hasattr(self, '_path2d'): self.axes.M = self.axes.get_proj() self.do_3d_projection() return self._path2d def do_3d_projection(self): s = self._segment3d (xs, ys, zs) = zip(*s) (vxs, vys, vzs, vis) = proj3d._proj_transform_clip(xs, ys, zs, self.axes.M, self.axes._focal_length) self._path2d = mpath.Path(np.column_stack([vxs, vys])) return min(vzs) class PathPatch3D(Patch3D): def __init__(self, path, *, zs=(), zdir='z', **kwargs): Patch.__init__(self, **kwargs) self.set_3d_properties(path, zs, zdir) def set_3d_properties(self, path, zs=0, zdir='z'): Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir) self._code3d = path.codes def do_3d_projection(self): s = self._segment3d (xs, ys, zs) = zip(*s) (vxs, vys, vzs, vis) = proj3d._proj_transform_clip(xs, ys, zs, self.axes.M, self.axes._focal_length) self._path2d = mpath.Path(np.column_stack([vxs, vys]), self._code3d) return min(vzs) def _get_patch_verts(patch): trans = patch.get_patch_transform() path = patch.get_path() polygons = path.to_polygons(trans) return polygons[0] if len(polygons) else np.array([]) def patch_2d_to_3d(patch, z=0, zdir='z'): verts = _get_patch_verts(patch) patch.__class__ = Patch3D patch.set_3d_properties(verts, z, zdir) def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'): path = pathpatch.get_path() trans = pathpatch.get_patch_transform() mpath = trans.transform_path(path) pathpatch.__class__ = PathPatch3D pathpatch.set_3d_properties(mpath, z, zdir) class Patch3DCollection(PatchCollection): def __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs): self._depthshade = depthshade super().__init__(*args, **kwargs) self.set_3d_properties(zs, zdir) def get_depthshade(self): return self._depthshade def set_depthshade(self, depthshade): self._depthshade = depthshade self.stale = True def set_sort_zpos(self, val): self._sort_zpos = val self.stale = True def set_3d_properties(self, zs, zdir): self.update_scalarmappable() offsets = self.get_offsets() if len(offsets) > 0: (xs, ys) = offsets.T else: xs = [] ys = [] self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir) self._z_markers_idx = slice(-1) self._vzs = None self.stale = True def do_3d_projection(self): (xs, ys, zs) = self._offsets3d (vxs, vys, vzs, vis) = proj3d._proj_transform_clip(xs, ys, zs, self.axes.M, self.axes._focal_length) self._vzs = vzs super().set_offsets(np.column_stack([vxs, vys])) if vzs.size > 0: return min(vzs) else: return np.nan def _maybe_depth_shade_and_sort_colors(self, color_array): color_array = _zalpha(color_array, self._vzs) if self._vzs is not None and self._depthshade else color_array if len(color_array) > 1: color_array = color_array[self._z_markers_idx] return mcolors.to_rgba_array(color_array, self._alpha) def get_facecolor(self): return self._maybe_depth_shade_and_sort_colors(super().get_facecolor()) def get_edgecolor(self): if cbook._str_equal(self._edgecolors, 'face'): return self.get_facecolor() return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor()) class Path3DCollection(PathCollection): def __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs): self._depthshade = depthshade self._in_draw = False super().__init__(*args, **kwargs) self.set_3d_properties(zs, zdir) self._offset_zordered = None def draw(self, renderer): with self._use_zordered_offset(): with cbook._setattr_cm(self, _in_draw=True): super().draw(renderer) def set_sort_zpos(self, val): self._sort_zpos = val self.stale = True def set_3d_properties(self, zs, zdir): self.update_scalarmappable() offsets = self.get_offsets() if len(offsets) > 0: (xs, ys) = offsets.T else: xs = [] ys = [] self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir) self._sizes3d = self._sizes self._linewidths3d = np.array(self._linewidths) (xs, ys, zs) = self._offsets3d self._z_markers_idx = slice(-1) self._vzs = None self.stale = True def set_sizes(self, sizes, dpi=72.0): super().set_sizes(sizes, dpi) if not self._in_draw: self._sizes3d = sizes def set_linewidth(self, lw): super().set_linewidth(lw) if not self._in_draw: self._linewidths3d = np.array(self._linewidths) def get_depthshade(self): return self._depthshade def set_depthshade(self, depthshade): self._depthshade = depthshade self.stale = True def do_3d_projection(self): (xs, ys, zs) = self._offsets3d (vxs, vys, vzs, vis) = proj3d._proj_transform_clip(xs, ys, zs, self.axes.M, self.axes._focal_length) z_markers_idx = self._z_markers_idx = np.argsort(vzs)[::-1] self._vzs = vzs if len(self._sizes3d) > 1: self._sizes = self._sizes3d[z_markers_idx] if len(self._linewidths3d) > 1: self._linewidths = self._linewidths3d[z_markers_idx] PathCollection.set_offsets(self, np.column_stack((vxs, vys))) vzs = vzs[z_markers_idx] vxs = vxs[z_markers_idx] vys = vys[z_markers_idx] self._offset_zordered = np.column_stack((vxs, vys)) return np.min(vzs) if vzs.size else np.nan @contextmanager def _use_zordered_offset(self): if self._offset_zordered is None: yield else: old_offset = self._offsets super().set_offsets(self._offset_zordered) try: yield finally: self._offsets = old_offset def _maybe_depth_shade_and_sort_colors(self, color_array): color_array = _zalpha(color_array, self._vzs) if self._vzs is not None and self._depthshade else color_array if len(color_array) > 1: color_array = color_array[self._z_markers_idx] return mcolors.to_rgba_array(color_array, self._alpha) def get_facecolor(self): return self._maybe_depth_shade_and_sort_colors(super().get_facecolor()) def get_edgecolor(self): if cbook._str_equal(self._edgecolors, 'face'): return self.get_facecolor() return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor()) def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True): if isinstance(col, PathCollection): col.__class__ = Path3DCollection col._offset_zordered = None elif isinstance(col, PatchCollection): col.__class__ = Patch3DCollection col._depthshade = depthshade col._in_draw = False col.set_3d_properties(zs, zdir) class Poly3DCollection(PolyCollection): def __init__(self, verts, *args, zsort='average', shade=False, lightsource=None, **kwargs): if shade: normals = _generate_normals(verts) facecolors = kwargs.get('facecolors', None) if facecolors is not None: kwargs['facecolors'] = _shade_colors(facecolors, normals, lightsource) edgecolors = kwargs.get('edgecolors', None) if edgecolors is not None: kwargs['edgecolors'] = _shade_colors(edgecolors, normals, lightsource) if facecolors is None and edgecolors is None: raise ValueError('You must provide facecolors, edgecolors, or both for shade to work.') super().__init__(verts, *args, **kwargs) if isinstance(verts, np.ndarray): if verts.ndim != 3: raise ValueError('verts must be a list of (N, 3) array-like') elif any((len(np.shape(vert)) != 2 for vert in verts)): raise ValueError('verts must be a list of (N, 3) array-like') self.set_zsort(zsort) self._codes3d = None _zsort_functions = {'average': np.average, 'min': np.min, 'max': np.max} def set_zsort(self, zsort): self._zsortfunc = self._zsort_functions[zsort] self._sort_zpos = None self.stale = True @_api.deprecated('3.10') def get_vector(self, segments3d): return self._get_vector(segments3d) def _get_vector(self, segments3d): if len(segments3d): (xs, ys, zs) = np.vstack(segments3d).T else: (xs, ys, zs) = ([], [], []) ones = np.ones(len(xs)) self._vec = np.array([xs, ys, zs, ones]) indices = [0, *np.cumsum([len(segment) for segment in segments3d])] self._segslices = [*map(slice, indices[:-1], indices[1:])] def set_verts(self, verts, closed=True): self._get_vector(verts) super().set_verts([], False) self._closed = closed def set_verts_and_codes(self, verts, codes): self.set_verts(verts, closed=False) self._codes3d = codes def set_3d_properties(self): self.update_scalarmappable() self._sort_zpos = None self.set_zsort('average') self._facecolor3d = PolyCollection.get_facecolor(self) self._edgecolor3d = PolyCollection.get_edgecolor(self) self._alpha3d = PolyCollection.get_alpha(self) self.stale = True def set_sort_zpos(self, val): self._sort_zpos = val self.stale = True def do_3d_projection(self): if self._A is not None: self.update_scalarmappable() if self._face_is_mapped: self._facecolor3d = self._facecolors if self._edge_is_mapped: self._edgecolor3d = self._edgecolors (txs, tys, tzs) = proj3d._proj_transform_vec(self._vec, self.axes.M) xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices] cface = self._facecolor3d cedge = self._edgecolor3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) if xyzlist: z_segments_2d = sorted(((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx) for (idx, ((xs, ys, zs), fc, ec)) in enumerate(zip(xyzlist, cface, cedge))), key=lambda x: x[0], reverse=True) (_, segments_2d, self._facecolors2d, self._edgecolors2d, idxs) = zip(*z_segments_2d) else: segments_2d = [] self._facecolors2d = np.empty((0, 4)) self._edgecolors2d = np.empty((0, 4)) idxs = [] if self._codes3d is not None: codes = [self._codes3d[idx] for idx in idxs] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d, self._closed) if len(self._edgecolor3d) != len(cface): self._edgecolors2d = self._edgecolor3d if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d._proj_transform_vec(zvec, self.axes.M) return ztrans[2][0] elif tzs.size > 0: return np.min(tzs) else: return np.nan def set_facecolor(self, colors): super().set_facecolor(colors) self._facecolor3d = PolyCollection.get_facecolor(self) def set_edgecolor(self, colors): super().set_edgecolor(colors) self._edgecolor3d = PolyCollection.get_edgecolor(self) def set_alpha(self, alpha): artist.Artist.set_alpha(self, alpha) try: self._facecolor3d = mcolors.to_rgba_array(self._facecolor3d, self._alpha) except (AttributeError, TypeError, IndexError): pass try: self._edgecolors = mcolors.to_rgba_array(self._edgecolor3d, self._alpha) except (AttributeError, TypeError, IndexError): pass self.stale = True def get_facecolor(self): if not hasattr(self, '_facecolors2d'): self.axes.M = self.axes.get_proj() self.do_3d_projection() return np.asarray(self._facecolors2d) def get_edgecolor(self): if not hasattr(self, '_edgecolors2d'): self.axes.M = self.axes.get_proj() self.do_3d_projection() return np.asarray(self._edgecolors2d) def poly_collection_2d_to_3d(col, zs=0, zdir='z'): (segments_3d, codes) = _paths_to_3d_segments_with_codes(col.get_paths(), zs, zdir) col.__class__ = Poly3DCollection col.set_verts_and_codes(segments_3d, codes) col.set_3d_properties() def juggle_axes(xs, ys, zs, zdir): if zdir == 'x': return (zs, xs, ys) elif zdir == 'y': return (xs, zs, ys) elif zdir[0] == '-': return rotate_axes(xs, ys, zs, zdir) else: return (xs, ys, zs) def rotate_axes(xs, ys, zs, zdir): if zdir in ('x', '-y'): return (ys, zs, xs) elif zdir in ('-x', 'y'): return (zs, xs, ys) else: return (xs, ys, zs) def _zalpha(colors, zs): if len(colors) == 0 or len(zs) == 0: return np.zeros((0, 4)) norm = Normalize(min(zs), max(zs)) sats = 1 - norm(zs) * 0.7 rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4)) return np.column_stack([rgba[:, :3], rgba[:, 3] * sats]) def _all_points_on_plane(xs, ys, zs, atol=1e-08): (xs, ys, zs) = (np.asarray(xs), np.asarray(ys), np.asarray(zs)) points = np.column_stack([xs, ys, zs]) points = points[~np.isnan(points).any(axis=1)] points = np.unique(points, axis=0) if len(points) <= 3: return True vs = (points - points[0])[1:] vs = vs / np.linalg.norm(vs, axis=1)[:, np.newaxis] vs = np.unique(vs, axis=0) if len(vs) <= 2: return True cross_norms = np.linalg.norm(np.cross(vs[0], vs[1:]), axis=1) zero_cross_norms = np.where(np.isclose(cross_norms, 0, atol=atol))[0] + 1 vs = np.delete(vs, zero_cross_norms, axis=0) if len(vs) <= 2: return True n = np.cross(vs[0], vs[1]) n = n / np.linalg.norm(n) dots = np.dot(n, vs.transpose()) return np.allclose(dots, 0, atol=atol) def _generate_normals(polygons): if isinstance(polygons, np.ndarray): n = polygons.shape[-2] (i1, i2, i3) = (0, n // 3, 2 * n // 3) v1 = polygons[..., i1, :] - polygons[..., i2, :] v2 = polygons[..., i2, :] - polygons[..., i3, :] else: v1 = np.empty((len(polygons), 3)) v2 = np.empty((len(polygons), 3)) for (poly_i, ps) in enumerate(polygons): n = len(ps) (i1, i2, i3) = (0, n // 3, 2 * n // 3) v1[poly_i, :] = ps[i1, :] - ps[i2, :] v2[poly_i, :] = ps[i2, :] - ps[i3, :] return np.cross(v1, v2) def _shade_colors(color, normals, lightsource=None): if lightsource is None: lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712) with np.errstate(invalid='ignore'): shade = normals / np.linalg.norm(normals, axis=1, keepdims=True) @ lightsource.direction mask = ~np.isnan(shade) if mask.any(): in_norm = mcolors.Normalize(-1, 1) out_norm = mcolors.Normalize(0.3, 1).inverse def norm(x): return out_norm(in_norm(x)) shade[~mask] = 0 color = mcolors.to_rgba_array(color) alpha = color[:, 3] colors = norm(shade)[:, np.newaxis] * color colors[:, 3] = alpha else: colors = np.asanyarray(color).copy() return colors # File: matplotlib-main/lib/mpl_toolkits/mplot3d/axes3d.py """""" from collections import defaultdict import itertools import math import textwrap import warnings import numpy as np import matplotlib as mpl from matplotlib import _api, cbook, _docstring, _preprocess_data import matplotlib.artist as martist import matplotlib.collections as mcoll import matplotlib.colors as mcolors import matplotlib.image as mimage import matplotlib.lines as mlines import matplotlib.patches as mpatches import matplotlib.container as mcontainer import matplotlib.transforms as mtransforms from matplotlib.axes import Axes from matplotlib.axes._base import _axis_method_wrapper, _process_plot_format from matplotlib.transforms import Bbox from matplotlib.tri._triangulation import Triangulation from . import art3d from . import proj3d from . import axis3d @_docstring.interpd @_api.define_aliases({'xlim': ['xlim3d'], 'ylim': ['ylim3d'], 'zlim': ['zlim3d']}) class Axes3D(Axes): name = '3d' _axis_names = ('x', 'y', 'z') Axes._shared_axes['z'] = cbook.Grouper() Axes._shared_axes['view'] = cbook.Grouper() def __init__(self, fig, rect=None, *args, elev=30, azim=-60, roll=0, shareview=None, sharez=None, proj_type='persp', focal_length=None, box_aspect=None, computed_zorder=True, **kwargs): if rect is None: rect = [0.0, 0.0, 1.0, 1.0] self.initial_azim = azim self.initial_elev = elev self.initial_roll = roll self.set_proj_type(proj_type, focal_length) self.computed_zorder = computed_zorder self.xy_viewLim = Bbox.unit() self.zz_viewLim = Bbox.unit() xymargin = 0.05 * 10 / 11 self.xy_dataLim = Bbox([[xymargin, xymargin], [1 - xymargin, 1 - xymargin]]) self.zz_dataLim = Bbox.unit() self.view_init(self.initial_elev, self.initial_azim, self.initial_roll) self._sharez = sharez if sharez is not None: self._shared_axes['z'].join(self, sharez) self._adjustable = 'datalim' self._shareview = shareview if shareview is not None: self._shared_axes['view'].join(self, shareview) if kwargs.pop('auto_add_to_figure', False): raise AttributeError('auto_add_to_figure is no longer supported for Axes3D. Use fig.add_axes(ax) instead.') super().__init__(fig, rect, *args, frameon=True, box_aspect=box_aspect, **kwargs) super().set_axis_off() self.set_axis_on() self.M = None self.invM = None self._view_margin = 1 / 48 self.autoscale_view() self.fmt_zdata = None self.mouse_init() fig = self.get_figure(root=True) fig.canvas.callbacks._connect_picklable('motion_notify_event', self._on_move) fig.canvas.callbacks._connect_picklable('button_press_event', self._button_press) fig.canvas.callbacks._connect_picklable('button_release_event', self._button_release) self.set_top_view() self.patch.set_linewidth(0) pseudo_bbox = self.transLimits.inverted().transform([(0, 0), (1, 1)]) (self._pseudo_w, self._pseudo_h) = pseudo_bbox[1] - pseudo_bbox[0] self.spines[:].set_visible(False) def set_axis_off(self): self._axis3don = False self.stale = True def set_axis_on(self): self._axis3don = True self.stale = True def convert_zunits(self, z): return self.zaxis.convert_units(z) def set_top_view(self): xdwl = 0.95 / self._dist xdw = 0.9 / self._dist ydwl = 0.95 / self._dist ydw = 0.9 / self._dist self.viewLim.intervalx = (-xdwl, xdw) self.viewLim.intervaly = (-ydwl, ydw) self.stale = True def _init_axis(self): self.xaxis = axis3d.XAxis(self) self.yaxis = axis3d.YAxis(self) self.zaxis = axis3d.ZAxis(self) def get_zaxis(self): return self.zaxis get_zgridlines = _axis_method_wrapper('zaxis', 'get_gridlines') get_zticklines = _axis_method_wrapper('zaxis', 'get_ticklines') def _transformed_cube(self, vals): (minx, maxx, miny, maxy, minz, maxz) = vals xyzs = [(minx, miny, minz), (maxx, miny, minz), (maxx, maxy, minz), (minx, maxy, minz), (minx, miny, maxz), (maxx, miny, maxz), (maxx, maxy, maxz), (minx, maxy, maxz)] return proj3d._proj_points(xyzs, self.M) def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): _api.check_in_list(('auto', 'equal', 'equalxy', 'equalyz', 'equalxz'), aspect=aspect) super().set_aspect(aspect='auto', adjustable=adjustable, anchor=anchor, share=share) self._aspect = aspect if aspect in ('equal', 'equalxy', 'equalxz', 'equalyz'): ax_indices = self._equal_aspect_axis_indices(aspect) view_intervals = np.array([self.xaxis.get_view_interval(), self.yaxis.get_view_interval(), self.zaxis.get_view_interval()]) ptp = np.ptp(view_intervals, axis=1) if self._adjustable == 'datalim': mean = np.mean(view_intervals, axis=1) scale = max(ptp[ax_indices] / self._box_aspect[ax_indices]) deltas = scale * self._box_aspect for (i, set_lim) in enumerate((self.set_xlim3d, self.set_ylim3d, self.set_zlim3d)): if i in ax_indices: set_lim(mean[i] - deltas[i] / 2.0, mean[i] + deltas[i] / 2.0, auto=True, view_margin=None) else: box_aspect = np.array(self._box_aspect) box_aspect[ax_indices] = ptp[ax_indices] remaining_ax_indices = {0, 1, 2}.difference(ax_indices) if remaining_ax_indices: remaining = remaining_ax_indices.pop() old_diag = np.linalg.norm(self._box_aspect[ax_indices]) new_diag = np.linalg.norm(box_aspect[ax_indices]) box_aspect[remaining] *= new_diag / old_diag self.set_box_aspect(box_aspect) def _equal_aspect_axis_indices(self, aspect): ax_indices = [] if aspect == 'equal': ax_indices = [0, 1, 2] elif aspect == 'equalxy': ax_indices = [0, 1] elif aspect == 'equalxz': ax_indices = [0, 2] elif aspect == 'equalyz': ax_indices = [1, 2] return ax_indices def set_box_aspect(self, aspect, *, zoom=1): if zoom <= 0: raise ValueError(f'Argument zoom = {zoom} must be > 0') if aspect is None: aspect = np.asarray((4, 4, 3), dtype=float) else: aspect = np.asarray(aspect, dtype=float) _api.check_shape((3,), aspect=aspect) aspect *= 1.8294640721620434 * 25 / 24 * zoom / np.linalg.norm(aspect) self._box_aspect = self._roll_to_vertical(aspect, reverse=True) self.stale = True def apply_aspect(self, position=None): if position is None: position = self.get_position(original=True) trans = self.get_figure().transSubfigure bb = mtransforms.Bbox.unit().transformed(trans) fig_aspect = bb.height / bb.width box_aspect = 1 pb = position.frozen() pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect) self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') @martist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return self._unstale_viewLim() self.patch.draw(renderer) self._frameon = False locator = self.get_axes_locator() self.apply_aspect(locator(self, renderer) if locator else None) self.M = self.get_proj() self.invM = np.linalg.inv(self.M) collections_and_patches = (artist for artist in self._children if isinstance(artist, (mcoll.Collection, mpatches.Patch)) and artist.get_visible()) if self.computed_zorder: zorder_offset = max((axis.get_zorder() for axis in self._axis_map.values())) + 1 collection_zorder = patch_zorder = zorder_offset for artist in sorted(collections_and_patches, key=lambda artist: artist.do_3d_projection(), reverse=True): if isinstance(artist, mcoll.Collection): artist.zorder = collection_zorder collection_zorder += 1 elif isinstance(artist, mpatches.Patch): artist.zorder = patch_zorder patch_zorder += 1 else: for artist in collections_and_patches: artist.do_3d_projection() if self._axis3don: for axis in self._axis_map.values(): axis.draw_pane(renderer) for axis in self._axis_map.values(): axis.draw_grid(renderer) for axis in self._axis_map.values(): axis.draw(renderer) super().draw(renderer) def get_axis_position(self): tc = self._transformed_cube(self.get_w_lims()) xhigh = tc[1][2] > tc[2][2] yhigh = tc[3][2] > tc[2][2] zhigh = tc[0][2] > tc[2][2] return (xhigh, yhigh, zhigh) def update_datalim(self, xys, **kwargs): pass get_autoscalez_on = _axis_method_wrapper('zaxis', '_get_autoscale_on') set_autoscalez_on = _axis_method_wrapper('zaxis', '_set_autoscale_on') def get_zmargin(self): return self._zmargin def set_zmargin(self, m): if m <= -0.5: raise ValueError('margin must be greater than -0.5') self._zmargin = m self._request_autoscale_view('z') self.stale = True def margins(self, *margins, x=None, y=None, z=None, tight=True): if margins and (x is not None or y is not None or z is not None): raise TypeError('Cannot pass both positional and keyword arguments for x, y, and/or z.') elif len(margins) == 1: x = y = z = margins[0] elif len(margins) == 3: (x, y, z) = margins elif margins: raise TypeError('Must pass a single positional argument for all margins, or one for each margin (x, y, z).') if x is None and y is None and (z is None): if tight is not True: _api.warn_external(f'ignoring tight={tight!r} in get mode') return (self._xmargin, self._ymargin, self._zmargin) if x is not None: self.set_xmargin(x) if y is not None: self.set_ymargin(y) if z is not None: self.set_zmargin(z) self.autoscale_view(tight=tight, scalex=x is not None, scaley=y is not None, scalez=z is not None) def autoscale(self, enable=True, axis='both', tight=None): if enable is None: scalex = True scaley = True scalez = True else: if axis in ['x', 'both']: self.set_autoscalex_on(enable) scalex = self.get_autoscalex_on() else: scalex = False if axis in ['y', 'both']: self.set_autoscaley_on(enable) scaley = self.get_autoscaley_on() else: scaley = False if axis in ['z', 'both']: self.set_autoscalez_on(enable) scalez = self.get_autoscalez_on() else: scalez = False if scalex: self._request_autoscale_view('x', tight=tight) if scaley: self._request_autoscale_view('y', tight=tight) if scalez: self._request_autoscale_view('z', tight=tight) def auto_scale_xyz(self, X, Y, Z=None, had_data=None): if np.shape(X) == np.shape(Y): self.xy_dataLim.update_from_data_xy(np.column_stack([np.ravel(X), np.ravel(Y)]), not had_data) else: self.xy_dataLim.update_from_data_x(X, not had_data) self.xy_dataLim.update_from_data_y(Y, not had_data) if Z is not None: self.zz_dataLim.update_from_data_x(Z, not had_data) self.autoscale_view() def autoscale_view(self, tight=None, scalex=True, scaley=True, scalez=True): if tight is None: _tight = self._tight if not _tight: for artist in self._children: if isinstance(artist, mimage.AxesImage): _tight = True elif isinstance(artist, (mlines.Line2D, mpatches.Patch)): _tight = False break else: _tight = self._tight = bool(tight) if scalex and self.get_autoscalex_on(): (x0, x1) = self.xy_dataLim.intervalx xlocator = self.xaxis.get_major_locator() (x0, x1) = xlocator.nonsingular(x0, x1) if self._xmargin > 0: delta = (x1 - x0) * self._xmargin x0 -= delta x1 += delta if not _tight: (x0, x1) = xlocator.view_limits(x0, x1) self.set_xbound(x0, x1, self._view_margin) if scaley and self.get_autoscaley_on(): (y0, y1) = self.xy_dataLim.intervaly ylocator = self.yaxis.get_major_locator() (y0, y1) = ylocator.nonsingular(y0, y1) if self._ymargin > 0: delta = (y1 - y0) * self._ymargin y0 -= delta y1 += delta if not _tight: (y0, y1) = ylocator.view_limits(y0, y1) self.set_ybound(y0, y1, self._view_margin) if scalez and self.get_autoscalez_on(): (z0, z1) = self.zz_dataLim.intervalx zlocator = self.zaxis.get_major_locator() (z0, z1) = zlocator.nonsingular(z0, z1) if self._zmargin > 0: delta = (z1 - z0) * self._zmargin z0 -= delta z1 += delta if not _tight: (z0, z1) = zlocator.view_limits(z0, z1) self.set_zbound(z0, z1, self._view_margin) def get_w_lims(self): (minx, maxx) = self.get_xlim3d() (miny, maxy) = self.get_ylim3d() (minz, maxz) = self.get_zlim3d() return (minx, maxx, miny, maxy, minz, maxz) def _set_bound3d(self, get_bound, set_lim, axis_inverted, lower=None, upper=None, view_margin=None): if upper is None and np.iterable(lower): (lower, upper) = lower (old_lower, old_upper) = get_bound() if lower is None: lower = old_lower if upper is None: upper = old_upper set_lim(sorted((lower, upper), reverse=bool(axis_inverted())), auto=None, view_margin=view_margin) def set_xbound(self, lower=None, upper=None, view_margin=None): self._set_bound3d(self.get_xbound, self.set_xlim, self.xaxis_inverted, lower, upper, view_margin) def set_ybound(self, lower=None, upper=None, view_margin=None): self._set_bound3d(self.get_ybound, self.set_ylim, self.yaxis_inverted, lower, upper, view_margin) def set_zbound(self, lower=None, upper=None, view_margin=None): self._set_bound3d(self.get_zbound, self.set_zlim, self.zaxis_inverted, lower, upper, view_margin) def _set_lim3d(self, axis, lower=None, upper=None, *, emit=True, auto=False, view_margin=None, axmin=None, axmax=None): if upper is None: if np.iterable(lower): (lower, upper) = lower elif axmax is None: upper = axis.get_view_interval()[1] if lower is None and axmin is None: lower = axis.get_view_interval()[0] if axmin is not None: if lower is not None: raise TypeError("Cannot pass both 'lower' and 'min'") lower = axmin if axmax is not None: if upper is not None: raise TypeError("Cannot pass both 'upper' and 'max'") upper = axmax if np.isinf(lower) or np.isinf(upper): raise ValueError(f'Axis limits {lower}, {upper} cannot be infinite') if view_margin is None: if mpl.rcParams['axes3d.automargin']: view_margin = self._view_margin else: view_margin = 0 delta = (upper - lower) * view_margin lower -= delta upper += delta return axis._set_lim(lower, upper, emit=emit, auto=auto) def set_xlim(self, left=None, right=None, *, emit=True, auto=False, view_margin=None, xmin=None, xmax=None): return self._set_lim3d(self.xaxis, left, right, emit=emit, auto=auto, view_margin=view_margin, axmin=xmin, axmax=xmax) def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False, view_margin=None, ymin=None, ymax=None): return self._set_lim3d(self.yaxis, bottom, top, emit=emit, auto=auto, view_margin=view_margin, axmin=ymin, axmax=ymax) def set_zlim(self, bottom=None, top=None, *, emit=True, auto=False, view_margin=None, zmin=None, zmax=None): return self._set_lim3d(self.zaxis, bottom, top, emit=emit, auto=auto, view_margin=view_margin, axmin=zmin, axmax=zmax) set_xlim3d = set_xlim set_ylim3d = set_ylim set_zlim3d = set_zlim def get_xlim(self): return tuple(self.xy_viewLim.intervalx) def get_ylim(self): return tuple(self.xy_viewLim.intervaly) def get_zlim(self): return tuple(self.zz_viewLim.intervalx) get_zscale = _axis_method_wrapper('zaxis', 'get_scale') set_xscale = _axis_method_wrapper('xaxis', '_set_axes_scale') set_yscale = _axis_method_wrapper('yaxis', '_set_axes_scale') set_zscale = _axis_method_wrapper('zaxis', '_set_axes_scale') (set_xscale.__doc__, set_yscale.__doc__, set_zscale.__doc__) = map('\n Set the {}-axis scale.\n\n Parameters\n ----------\n value : {{"linear"}}\n The axis scale type to apply. 3D Axes currently only support\n linear scales; other scales yield nonsensical results.\n\n **kwargs\n Keyword arguments are nominally forwarded to the scale class, but\n none of them is applicable for linear scales.\n '.format, ['x', 'y', 'z']) get_zticks = _axis_method_wrapper('zaxis', 'get_ticklocs') set_zticks = _axis_method_wrapper('zaxis', 'set_ticks') get_zmajorticklabels = _axis_method_wrapper('zaxis', 'get_majorticklabels') get_zminorticklabels = _axis_method_wrapper('zaxis', 'get_minorticklabels') get_zticklabels = _axis_method_wrapper('zaxis', 'get_ticklabels') set_zticklabels = _axis_method_wrapper('zaxis', 'set_ticklabels', doc_sub={'Axis.set_ticks': 'Axes3D.set_zticks'}) zaxis_date = _axis_method_wrapper('zaxis', 'axis_date') if zaxis_date.__doc__: zaxis_date.__doc__ += textwrap.dedent('\n\n Notes\n -----\n This function is merely provided for completeness, but 3D Axes do not\n support dates for ticks, and so this may not work as expected.\n ') def clabel(self, *args, **kwargs): return None def view_init(self, elev=None, azim=None, roll=None, vertical_axis='z', share=False): self._dist = 10 if elev is None: elev = self.initial_elev if azim is None: azim = self.initial_azim if roll is None: roll = self.initial_roll vertical_axis = _api.check_getitem({name: idx for (idx, name) in enumerate(self._axis_names)}, vertical_axis=vertical_axis) if share: axes = {sibling for sibling in self._shared_axes['view'].get_siblings(self)} else: axes = [self] for ax in axes: ax.elev = elev ax.azim = azim ax.roll = roll ax._vertical_axis = vertical_axis def set_proj_type(self, proj_type, focal_length=None): _api.check_in_list(['persp', 'ortho'], proj_type=proj_type) if proj_type == 'persp': if focal_length is None: focal_length = 1 elif focal_length <= 0: raise ValueError(f'focal_length = {focal_length} must be greater than 0') self._focal_length = focal_length else: if focal_length not in (None, np.inf): raise ValueError(f'focal_length = {focal_length} must be None for proj_type = {proj_type}') self._focal_length = np.inf def _roll_to_vertical(self, arr: 'np.typing.ArrayLike', reverse: bool=False) -> np.ndarray: if reverse: return np.roll(arr, (self._vertical_axis - 2) * -1) else: return np.roll(arr, self._vertical_axis - 2) def get_proj(self): box_aspect = self._roll_to_vertical(self._box_aspect) worldM = proj3d.world_transformation(*self.get_xlim3d(), *self.get_ylim3d(), *self.get_zlim3d(), pb_aspect=box_aspect) R = 0.5 * box_aspect elev_rad = np.deg2rad(self.elev) azim_rad = np.deg2rad(self.azim) p0 = np.cos(elev_rad) * np.cos(azim_rad) p1 = np.cos(elev_rad) * np.sin(azim_rad) p2 = np.sin(elev_rad) ps = self._roll_to_vertical([p0, p1, p2]) eye = R + self._dist * ps (u, v, w) = self._calc_view_axes(eye) self._view_u = u self._view_v = v self._view_w = w if self._focal_length == np.inf: viewM = proj3d._view_transformation_uvw(u, v, w, eye) projM = proj3d._ortho_transformation(-self._dist, self._dist) else: eye_focal = R + self._dist * ps * self._focal_length viewM = proj3d._view_transformation_uvw(u, v, w, eye_focal) projM = proj3d._persp_transformation(-self._dist, self._dist, self._focal_length) M0 = np.dot(viewM, worldM) M = np.dot(projM, M0) return M def mouse_init(self, rotate_btn=1, pan_btn=2, zoom_btn=3): self.button_pressed = None self._rotate_btn = np.atleast_1d(rotate_btn).tolist() self._pan_btn = np.atleast_1d(pan_btn).tolist() self._zoom_btn = np.atleast_1d(zoom_btn).tolist() def disable_mouse_rotation(self): self.mouse_init(rotate_btn=[], pan_btn=[], zoom_btn=[]) def can_zoom(self): return True def can_pan(self): return True def sharez(self, other): _api.check_isinstance(Axes3D, other=other) if self._sharez is not None and other is not self._sharez: raise ValueError('z-axis is already shared') self._shared_axes['z'].join(self, other) self._sharez = other self.zaxis.major = other.zaxis.major self.zaxis.minor = other.zaxis.minor (z0, z1) = other.get_zlim() self.set_zlim(z0, z1, emit=False, auto=other.get_autoscalez_on()) self.zaxis._scale = other.zaxis._scale def shareview(self, other): _api.check_isinstance(Axes3D, other=other) if self._shareview is not None and other is not self._shareview: raise ValueError('view angles are already shared') self._shared_axes['view'].join(self, other) self._shareview = other vertical_axis = self._axis_names[other._vertical_axis] self.view_init(elev=other.elev, azim=other.azim, roll=other.roll, vertical_axis=vertical_axis, share=True) def clear(self): super().clear() if self._focal_length == np.inf: self._zmargin = mpl.rcParams['axes.zmargin'] else: self._zmargin = 0.0 xymargin = 0.05 * 10 / 11 self.xy_dataLim = Bbox([[xymargin, xymargin], [1 - xymargin, 1 - xymargin]]) self.zz_dataLim = Bbox.unit() self._view_margin = 1 / 48 self.autoscale_view() self.grid(mpl.rcParams['axes3d.grid']) def _button_press(self, event): if event.inaxes == self: self.button_pressed = event.button (self._sx, self._sy) = (event.xdata, event.ydata) toolbar = self.get_figure(root=True).canvas.toolbar if toolbar and toolbar._nav_stack() is None: toolbar.push_current() if toolbar: toolbar.set_message(toolbar._mouse_event_to_message(event)) def _button_release(self, event): self.button_pressed = None toolbar = self.get_figure(root=True).canvas.toolbar if toolbar and self.get_navigate_mode() is None: toolbar.push_current() if toolbar: toolbar.set_message(toolbar._mouse_event_to_message(event)) def _get_view(self): return ({'xlim': self.get_xlim(), 'autoscalex_on': self.get_autoscalex_on(), 'ylim': self.get_ylim(), 'autoscaley_on': self.get_autoscaley_on(), 'zlim': self.get_zlim(), 'autoscalez_on': self.get_autoscalez_on()}, (self.elev, self.azim, self.roll)) def _set_view(self, view): (props, (elev, azim, roll)) = view self.set(**props) self.elev = elev self.azim = azim self.roll = roll def format_zdata(self, z): try: return self.fmt_zdata(z) except (AttributeError, TypeError): func = self.zaxis.get_major_formatter().format_data_short val = func(z) return val def format_coord(self, xv, yv, renderer=None): coords = '' if self.button_pressed in self._rotate_btn: coords = self._rotation_coords() elif self.M is not None: coords = self._location_coords(xv, yv, renderer) return coords def _rotation_coords(self): norm_elev = art3d._norm_angle(self.elev) norm_azim = art3d._norm_angle(self.azim) norm_roll = art3d._norm_angle(self.roll) coords = f'elevation={norm_elev:.0f}°, azimuth={norm_azim:.0f}°, roll={norm_roll:.0f}°'.replace('-', '−') return coords def _location_coords(self, xv, yv, renderer): (p1, pane_idx) = self._calc_coord(xv, yv, renderer) xs = self.format_xdata(p1[0]) ys = self.format_ydata(p1[1]) zs = self.format_zdata(p1[2]) if pane_idx == 0: coords = f'x pane={xs}, y={ys}, z={zs}' elif pane_idx == 1: coords = f'x={xs}, y pane={ys}, z={zs}' elif pane_idx == 2: coords = f'x={xs}, y={ys}, z pane={zs}' return coords def _get_camera_loc(self): (cx, cy, cz, dx, dy, dz) = self._get_w_centers_ranges() c = np.array([cx, cy, cz]) r = np.array([dx, dy, dz]) if self._focal_length == np.inf: focal_length = 1000000000.0 else: focal_length = self._focal_length eye = c + self._view_w * self._dist * r / self._box_aspect * focal_length return eye def _calc_coord(self, xv, yv, renderer=None): if self._focal_length == np.inf: zv = 1 else: zv = -1 / self._focal_length p1 = np.array(proj3d.inv_transform(xv, yv, zv, self.invM)).ravel() vec = self._get_camera_loc() - p1 pane_locs = [] for axis in self._axis_map.values(): (xys, loc) = axis.active_pane() pane_locs.append(loc) scales = np.zeros(3) for i in range(3): if vec[i] == 0: scales[i] = np.inf else: scales[i] = (p1[i] - pane_locs[i]) / vec[i] pane_idx = np.argmin(abs(scales)) scale = scales[pane_idx] p2 = p1 - scale * vec return (p2, pane_idx) def _arcball(self, x: float, y: float) -> np.ndarray: x *= 2 y *= 2 r2 = x * x + y * y if r2 > 1: p = np.array([0, x / math.sqrt(r2), y / math.sqrt(r2)]) else: p = np.array([math.sqrt(1 - r2), x, y]) return p def _on_move(self, event): if not self.button_pressed: return if self.get_navigate_mode() is not None: return if self.M is None: return (x, y) = (event.xdata, event.ydata) if x is None or event.inaxes != self: return (dx, dy) = (x - self._sx, y - self._sy) w = self._pseudo_w h = self._pseudo_h if self.button_pressed in self._rotate_btn: if dx == 0 and dy == 0: return elev = np.deg2rad(self.elev) azim = np.deg2rad(self.azim) roll = np.deg2rad(self.roll) q = _Quaternion.from_cardan_angles(elev, azim, roll) current_vec = self._arcball(self._sx / w, self._sy / h) new_vec = self._arcball(x / w, y / h) dq = _Quaternion.rotate_from_to(current_vec, new_vec) q = dq * q (elev, azim, roll) = q.as_cardan_angles() azim = np.rad2deg(azim) elev = np.rad2deg(elev) roll = np.rad2deg(roll) vertical_axis = self._axis_names[self._vertical_axis] self.view_init(elev=elev, azim=azim, roll=roll, vertical_axis=vertical_axis, share=True) self.stale = True elif self.button_pressed in self._pan_btn: (px, py) = self.transData.transform([self._sx, self._sy]) self.start_pan(px, py, 2) self.drag_pan(2, None, event.x, event.y) self.end_pan() elif self.button_pressed in self._zoom_btn: scale = h / (h - dy) self._scale_axis_limits(scale, scale, scale) (self._sx, self._sy) = (x, y) self.get_figure(root=True).canvas.draw_idle() def drag_pan(self, button, key, x, y): p = self._pan_start ((xdata, ydata), (xdata_start, ydata_start)) = p.trans_inverse.transform([(x, y), (p.x, p.y)]) (self._sx, self._sy) = (xdata, ydata) self.start_pan(x, y, button) (du, dv) = (xdata - xdata_start, ydata - ydata_start) dw = 0 if key == 'x': dv = 0 elif key == 'y': du = 0 if du == 0 and dv == 0: return R = np.array([self._view_u, self._view_v, self._view_w]) R = -R / self._box_aspect * self._dist duvw_projected = R.T @ np.array([du, dv, dw]) (minx, maxx, miny, maxy, minz, maxz) = self.get_w_lims() dx = (maxx - minx) * duvw_projected[0] dy = (maxy - miny) * duvw_projected[1] dz = (maxz - minz) * duvw_projected[2] self.set_xlim3d(minx + dx, maxx + dx, auto=None) self.set_ylim3d(miny + dy, maxy + dy, auto=None) self.set_zlim3d(minz + dz, maxz + dz, auto=None) def _calc_view_axes(self, eye): elev_rad = np.deg2rad(art3d._norm_angle(self.elev)) roll_rad = np.deg2rad(art3d._norm_angle(self.roll)) R = 0.5 * self._roll_to_vertical(self._box_aspect) V = np.zeros(3) V[self._vertical_axis] = -1 if abs(elev_rad) > np.pi / 2 else 1 (u, v, w) = proj3d._view_axes(eye, R, V, roll_rad) return (u, v, w) def _set_view_from_bbox(self, bbox, direction='in', mode=None, twinx=False, twiny=False): (start_x, start_y, stop_x, stop_y) = bbox if mode == 'x': start_y = self.bbox.min[1] stop_y = self.bbox.max[1] elif mode == 'y': start_x = self.bbox.min[0] stop_x = self.bbox.max[0] (start_x, stop_x) = np.clip(sorted([start_x, stop_x]), self.bbox.min[0], self.bbox.max[0]) (start_y, stop_y) = np.clip(sorted([start_y, stop_y]), self.bbox.min[1], self.bbox.max[1]) zoom_center_x = (start_x + stop_x) / 2 zoom_center_y = (start_y + stop_y) / 2 ax_center_x = (self.bbox.max[0] + self.bbox.min[0]) / 2 ax_center_y = (self.bbox.max[1] + self.bbox.min[1]) / 2 self.start_pan(zoom_center_x, zoom_center_y, 2) self.drag_pan(2, None, ax_center_x, ax_center_y) self.end_pan() dx = abs(start_x - stop_x) dy = abs(start_y - stop_y) scale_u = dx / (self.bbox.max[0] - self.bbox.min[0]) scale_v = dy / (self.bbox.max[1] - self.bbox.min[1]) scale = max(scale_u, scale_v) if direction == 'out': scale = 1 / scale self._zoom_data_limits(scale, scale, scale) def _zoom_data_limits(self, scale_u, scale_v, scale_w): scale = np.array([scale_u, scale_v, scale_w]) if not np.allclose(scale, scale_u): R = np.array([self._view_u, self._view_v, self._view_w]) S = scale * np.eye(3) scale = np.linalg.norm(R.T @ S, axis=1) if self._aspect in ('equal', 'equalxy', 'equalxz', 'equalyz'): ax_idxs = self._equal_aspect_axis_indices(self._aspect) min_ax_idxs = np.argmin(np.abs(scale[ax_idxs] - 1)) scale[ax_idxs] = scale[ax_idxs][min_ax_idxs] self._scale_axis_limits(scale[0], scale[1], scale[2]) def _scale_axis_limits(self, scale_x, scale_y, scale_z): (cx, cy, cz, dx, dy, dz) = self._get_w_centers_ranges() self.set_xlim3d(cx - dx * scale_x / 2, cx + dx * scale_x / 2, auto=None) self.set_ylim3d(cy - dy * scale_y / 2, cy + dy * scale_y / 2, auto=None) self.set_zlim3d(cz - dz * scale_z / 2, cz + dz * scale_z / 2, auto=None) def _get_w_centers_ranges(self): (minx, maxx, miny, maxy, minz, maxz) = self.get_w_lims() cx = (maxx + minx) / 2 cy = (maxy + miny) / 2 cz = (maxz + minz) / 2 dx = maxx - minx dy = maxy - miny dz = maxz - minz return (cx, cy, cz, dx, dy, dz) def set_zlabel(self, zlabel, fontdict=None, labelpad=None, **kwargs): if labelpad is not None: self.zaxis.labelpad = labelpad return self.zaxis.set_label_text(zlabel, fontdict, **kwargs) def get_zlabel(self): label = self.zaxis.get_label() return label.get_text() get_frame_on = None set_frame_on = None def grid(self, visible=True, **kwargs): if len(kwargs): visible = True self._draw_grid = visible self.stale = True def tick_params(self, axis='both', **kwargs): _api.check_in_list(['x', 'y', 'z', 'both'], axis=axis) if axis in ['x', 'y', 'both']: super().tick_params(axis, **kwargs) if axis in ['z', 'both']: zkw = dict(kwargs) zkw.pop('top', None) zkw.pop('bottom', None) zkw.pop('labeltop', None) zkw.pop('labelbottom', None) self.zaxis.set_tick_params(**zkw) def invert_zaxis(self): (bottom, top) = self.get_zlim() self.set_zlim(top, bottom, auto=None) zaxis_inverted = _axis_method_wrapper('zaxis', 'get_inverted') def get_zbound(self): (lower, upper) = self.get_zlim() if lower < upper: return (lower, upper) else: return (upper, lower) def text(self, x, y, z, s, zdir=None, **kwargs): text = super().text(x, y, s, **kwargs) art3d.text_2d_to_3d(text, z, zdir) return text text3D = text text2D = Axes.text def plot(self, xs, ys, *args, zdir='z', **kwargs): had_data = self.has_data() if args and (not isinstance(args[0], str)): (zs, *args) = args if 'zs' in kwargs: raise TypeError("plot() for multiple values for argument 'zs'") else: zs = kwargs.pop('zs', 0) (xs, ys, zs) = cbook._broadcast_with_masks(xs, ys, zs) lines = super().plot(xs, ys, *args, **kwargs) for line in lines: art3d.line_2d_to_3d(line, zs=zs, zdir=zdir) (xs, ys, zs) = art3d.juggle_axes(xs, ys, zs, zdir) self.auto_scale_xyz(xs, ys, zs, had_data) return lines plot3D = plot def fill_between(self, x1, y1, z1, x2, y2, z2, *, where=None, mode='auto', facecolors=None, shade=None, **kwargs): _api.check_in_list(['auto', 'quad', 'polygon'], mode=mode) had_data = self.has_data() (x1, y1, z1, x2, y2, z2) = cbook._broadcast_with_masks(x1, y1, z1, x2, y2, z2) if facecolors is None: facecolors = [self._get_patches_for_fill.get_next_color()] facecolors = list(mcolors.to_rgba_array(facecolors)) if where is None: where = True else: where = np.asarray(where, dtype=bool) if where.size != x1.size: raise ValueError(f'where size ({where.size}) does not match size ({x1.size})') where = where & ~np.isnan(x1) if mode == 'auto': if art3d._all_points_on_plane(np.concatenate((x1[where], x2[where])), np.concatenate((y1[where], y2[where])), np.concatenate((z1[where], z2[where])), atol=1e-12): mode = 'polygon' else: mode = 'quad' if shade is None: if mode == 'quad': shade = True else: shade = False polys = [] for (idx0, idx1) in cbook.contiguous_regions(where): x1i = x1[idx0:idx1] y1i = y1[idx0:idx1] z1i = z1[idx0:idx1] x2i = x2[idx0:idx1] y2i = y2[idx0:idx1] z2i = z2[idx0:idx1] if not len(x1i): continue if mode == 'quad': n_polys_i = len(x1i) - 1 polys_i = np.empty((n_polys_i, 4, 3)) polys_i[:, 0, :] = np.column_stack((x1i[:-1], y1i[:-1], z1i[:-1])) polys_i[:, 1, :] = np.column_stack((x1i[1:], y1i[1:], z1i[1:])) polys_i[:, 2, :] = np.column_stack((x2i[1:], y2i[1:], z2i[1:])) polys_i[:, 3, :] = np.column_stack((x2i[:-1], y2i[:-1], z2i[:-1])) polys = polys + [*polys_i] elif mode == 'polygon': line1 = np.column_stack((x1i, y1i, z1i)) line2 = np.column_stack((x2i[::-1], y2i[::-1], z2i[::-1])) poly = np.concatenate((line1, line2), axis=0) polys.append(poly) polyc = art3d.Poly3DCollection(polys, facecolors=facecolors, shade=shade, **kwargs) self.add_collection(polyc) self.auto_scale_xyz([x1, x2], [y1, y2], [z1, z2], had_data) return polyc def plot_surface(self, X, Y, Z, *, norm=None, vmin=None, vmax=None, lightsource=None, **kwargs): had_data = self.has_data() if Z.ndim != 2: raise ValueError('Argument Z must be 2-dimensional.') Z = cbook._to_unmasked_float_array(Z) (X, Y, Z) = np.broadcast_arrays(X, Y, Z) (rows, cols) = Z.shape has_stride = 'rstride' in kwargs or 'cstride' in kwargs has_count = 'rcount' in kwargs or 'ccount' in kwargs if has_stride and has_count: raise ValueError('Cannot specify both stride and count arguments') rstride = kwargs.pop('rstride', 10) cstride = kwargs.pop('cstride', 10) rcount = kwargs.pop('rcount', 50) ccount = kwargs.pop('ccount', 50) if mpl.rcParams['_internal.classic_mode']: compute_strides = has_count else: compute_strides = not has_stride if compute_strides: rstride = int(max(np.ceil(rows / rcount), 1)) cstride = int(max(np.ceil(cols / ccount), 1)) fcolors = kwargs.pop('facecolors', None) cmap = kwargs.get('cmap', None) shade = kwargs.pop('shade', cmap is None) if shade is None: raise ValueError('shade cannot be None.') colset = [] if (rows - 1) % rstride == 0 and (cols - 1) % cstride == 0 and (fcolors is None): polys = np.stack([cbook._array_patch_perimeters(a, rstride, cstride) for a in (X, Y, Z)], axis=-1) else: row_inds = list(range(0, rows - 1, rstride)) + [rows - 1] col_inds = list(range(0, cols - 1, cstride)) + [cols - 1] polys = [] for (rs, rs_next) in itertools.pairwise(row_inds): for (cs, cs_next) in itertools.pairwise(col_inds): ps = [cbook._array_perimeter(a[rs:rs_next + 1, cs:cs_next + 1]) for a in (X, Y, Z)] ps = np.array(ps).T polys.append(ps) if fcolors is not None: colset.append(fcolors[rs][cs]) if not isinstance(polys, np.ndarray) or not np.isfinite(polys).all(): new_polys = [] new_colset = [] for (p, col) in itertools.zip_longest(polys, colset): new_poly = np.array(p)[np.isfinite(p).all(axis=1)] if len(new_poly): new_polys.append(new_poly) new_colset.append(col) polys = new_polys if fcolors is not None: colset = new_colset if fcolors is not None: polyc = art3d.Poly3DCollection(polys, edgecolors=colset, facecolors=colset, shade=shade, lightsource=lightsource, **kwargs) elif cmap: polyc = art3d.Poly3DCollection(polys, **kwargs) if isinstance(polys, np.ndarray): avg_z = polys[..., 2].mean(axis=-1) else: avg_z = np.array([ps[:, 2].mean() for ps in polys]) polyc.set_array(avg_z) if vmin is not None or vmax is not None: polyc.set_clim(vmin, vmax) if norm is not None: polyc.set_norm(norm) else: color = kwargs.pop('color', None) if color is None: color = self._get_lines.get_next_color() color = np.array(mcolors.to_rgba(color)) polyc = art3d.Poly3DCollection(polys, facecolors=color, shade=shade, lightsource=lightsource, **kwargs) self.add_collection(polyc) self.auto_scale_xyz(X, Y, Z, had_data) return polyc def plot_wireframe(self, X, Y, Z, **kwargs): had_data = self.has_data() if Z.ndim != 2: raise ValueError('Argument Z must be 2-dimensional.') (X, Y, Z) = np.broadcast_arrays(X, Y, Z) (rows, cols) = Z.shape has_stride = 'rstride' in kwargs or 'cstride' in kwargs has_count = 'rcount' in kwargs or 'ccount' in kwargs if has_stride and has_count: raise ValueError('Cannot specify both stride and count arguments') rstride = kwargs.pop('rstride', 1) cstride = kwargs.pop('cstride', 1) rcount = kwargs.pop('rcount', 50) ccount = kwargs.pop('ccount', 50) if mpl.rcParams['_internal.classic_mode']: if has_count: rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0 cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0 elif not has_stride: rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0 cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0 (tX, tY, tZ) = (np.transpose(X), np.transpose(Y), np.transpose(Z)) if rstride: rii = list(range(0, rows, rstride)) if rows > 0 and rii[-1] != rows - 1: rii += [rows - 1] else: rii = [] if cstride: cii = list(range(0, cols, cstride)) if cols > 0 and cii[-1] != cols - 1: cii += [cols - 1] else: cii = [] if rstride == 0 and cstride == 0: raise ValueError('Either rstride or cstride must be non zero') if Z.size == 0: rii = [] cii = [] xlines = [X[i] for i in rii] ylines = [Y[i] for i in rii] zlines = [Z[i] for i in rii] txlines = [tX[i] for i in cii] tylines = [tY[i] for i in cii] tzlines = [tZ[i] for i in cii] lines = [list(zip(xl, yl, zl)) for (xl, yl, zl) in zip(xlines, ylines, zlines)] + [list(zip(xl, yl, zl)) for (xl, yl, zl) in zip(txlines, tylines, tzlines)] linec = art3d.Line3DCollection(lines, **kwargs) self.add_collection(linec) self.auto_scale_xyz(X, Y, Z, had_data) return linec def plot_trisurf(self, *args, color=None, norm=None, vmin=None, vmax=None, lightsource=None, **kwargs): had_data = self.has_data() if color is None: color = self._get_lines.get_next_color() color = np.array(mcolors.to_rgba(color)) cmap = kwargs.get('cmap', None) shade = kwargs.pop('shade', cmap is None) (tri, args, kwargs) = Triangulation.get_from_args_and_kwargs(*args, **kwargs) try: z = kwargs.pop('Z') except KeyError: (z, *args) = args z = np.asarray(z) triangles = tri.get_masked_triangles() xt = tri.x[triangles] yt = tri.y[triangles] zt = z[triangles] verts = np.stack((xt, yt, zt), axis=-1) if cmap: polyc = art3d.Poly3DCollection(verts, *args, **kwargs) avg_z = verts[:, :, 2].mean(axis=1) polyc.set_array(avg_z) if vmin is not None or vmax is not None: polyc.set_clim(vmin, vmax) if norm is not None: polyc.set_norm(norm) else: polyc = art3d.Poly3DCollection(verts, *args, shade=shade, lightsource=lightsource, facecolors=color, **kwargs) self.add_collection(polyc) self.auto_scale_xyz(tri.x, tri.y, z, had_data) return polyc def _3d_extend_contour(self, cset, stride=5): dz = (cset.levels[1] - cset.levels[0]) / 2 polyverts = [] colors = [] for (idx, level) in enumerate(cset.levels): path = cset.get_paths()[idx] subpaths = [*path._iter_connected_components()] color = cset.get_edgecolor()[idx] top = art3d._paths_to_3d_segments(subpaths, level - dz) bot = art3d._paths_to_3d_segments(subpaths, level + dz) if not len(top[0]): continue nsteps = max(round(len(top[0]) / stride), 2) stepsize = (len(top[0]) - 1) / (nsteps - 1) polyverts.extend([(top[0][round(i * stepsize)], top[0][round((i + 1) * stepsize)], bot[0][round((i + 1) * stepsize)], bot[0][round(i * stepsize)]) for i in range(round(nsteps) - 1)]) colors.extend([color] * (round(nsteps) - 1)) self.add_collection3d(art3d.Poly3DCollection(np.array(polyverts), facecolors=colors, edgecolors=colors, shade=True)) cset.remove() def add_contour_set(self, cset, extend3d=False, stride=5, zdir='z', offset=None): zdir = '-' + zdir if extend3d: self._3d_extend_contour(cset, stride) else: art3d.collection_2d_to_3d(cset, zs=offset if offset is not None else cset.levels, zdir=zdir) def add_contourf_set(self, cset, zdir='z', offset=None): self._add_contourf_set(cset, zdir=zdir, offset=offset) def _add_contourf_set(self, cset, zdir='z', offset=None): zdir = '-' + zdir midpoints = cset.levels[:-1] + np.diff(cset.levels) / 2 if cset._extend_min: min_level = cset.levels[0] - np.diff(cset.levels[:2]) / 2 midpoints = np.insert(midpoints, 0, min_level) if cset._extend_max: max_level = cset.levels[-1] + np.diff(cset.levels[-2:]) / 2 midpoints = np.append(midpoints, max_level) art3d.collection_2d_to_3d(cset, zs=offset if offset is not None else midpoints, zdir=zdir) return midpoints @_preprocess_data() def contour(self, X, Y, Z, *args, extend3d=False, stride=5, zdir='z', offset=None, **kwargs): had_data = self.has_data() (jX, jY, jZ) = art3d.rotate_axes(X, Y, Z, zdir) cset = super().contour(jX, jY, jZ, *args, **kwargs) self.add_contour_set(cset, extend3d, stride, zdir, offset) self.auto_scale_xyz(X, Y, Z, had_data) return cset contour3D = contour @_preprocess_data() def tricontour(self, *args, extend3d=False, stride=5, zdir='z', offset=None, **kwargs): had_data = self.has_data() (tri, args, kwargs) = Triangulation.get_from_args_and_kwargs(*args, **kwargs) X = tri.x Y = tri.y if 'Z' in kwargs: Z = kwargs.pop('Z') else: (Z, *args) = args (jX, jY, jZ) = art3d.rotate_axes(X, Y, Z, zdir) tri = Triangulation(jX, jY, tri.triangles, tri.mask) cset = super().tricontour(tri, jZ, *args, **kwargs) self.add_contour_set(cset, extend3d, stride, zdir, offset) self.auto_scale_xyz(X, Y, Z, had_data) return cset def _auto_scale_contourf(self, X, Y, Z, zdir, levels, had_data): dim_vals = {'x': X, 'y': Y, 'z': Z, zdir: levels} limits = [(np.nanmin(dim_vals[dim]), np.nanmax(dim_vals[dim])) for dim in ['x', 'y', 'z']] self.auto_scale_xyz(*limits, had_data) @_preprocess_data() def contourf(self, X, Y, Z, *args, zdir='z', offset=None, **kwargs): had_data = self.has_data() (jX, jY, jZ) = art3d.rotate_axes(X, Y, Z, zdir) cset = super().contourf(jX, jY, jZ, *args, **kwargs) levels = self._add_contourf_set(cset, zdir, offset) self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data) return cset contourf3D = contourf @_preprocess_data() def tricontourf(self, *args, zdir='z', offset=None, **kwargs): had_data = self.has_data() (tri, args, kwargs) = Triangulation.get_from_args_and_kwargs(*args, **kwargs) X = tri.x Y = tri.y if 'Z' in kwargs: Z = kwargs.pop('Z') else: (Z, *args) = args (jX, jY, jZ) = art3d.rotate_axes(X, Y, Z, zdir) tri = Triangulation(jX, jY, tri.triangles, tri.mask) cset = super().tricontourf(tri, jZ, *args, **kwargs) levels = self._add_contourf_set(cset, zdir, offset) self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data) return cset def add_collection3d(self, col, zs=0, zdir='z', autolim=True): had_data = self.has_data() zvals = np.atleast_1d(zs) zsortval = np.min(zvals) if zvals.size else 0 if type(col) is mcoll.PolyCollection: art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) elif type(col) is mcoll.LineCollection: art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) elif type(col) is mcoll.PatchCollection: art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir) col.set_sort_zpos(zsortval) if autolim: if isinstance(col, art3d.Line3DCollection): self.auto_scale_xyz(*np.array(col._segments3d).transpose(), had_data=had_data) elif isinstance(col, art3d.Poly3DCollection): self.auto_scale_xyz(*col._vec[:-1], had_data=had_data) elif isinstance(col, art3d.Patch3DCollection): pass collection = super().add_collection(col) return collection @_preprocess_data(replace_names=['xs', 'ys', 'zs', 's', 'edgecolors', 'c', 'facecolor', 'facecolors', 'color']) def scatter(self, xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True, *args, **kwargs): had_data = self.has_data() zs_orig = zs (xs, ys, zs) = cbook._broadcast_with_masks(xs, ys, zs) s = np.ma.ravel(s) (xs, ys, zs, s, c, color) = cbook.delete_masked_points(xs, ys, zs, s, c, kwargs.get('color', None)) if kwargs.get('color') is not None: kwargs['color'] = color if np.may_share_memory(zs_orig, zs): zs = zs.copy() patches = super().scatter(xs, ys, *args, s=s, c=c, **kwargs) art3d.patch_collection_2d_to_3d(patches, zs=zs, zdir=zdir, depthshade=depthshade) if self._zmargin < 0.05 and xs.size > 0: self.set_zmargin(0.05) self.auto_scale_xyz(xs, ys, zs, had_data) return patches scatter3D = scatter @_preprocess_data() def bar(self, left, height, zs=0, zdir='z', *args, **kwargs): had_data = self.has_data() patches = super().bar(left, height, *args, **kwargs) zs = np.broadcast_to(zs, len(left), subok=True) verts = [] verts_zs = [] for (p, z) in zip(patches, zs): vs = art3d._get_patch_verts(p) verts += vs.tolist() verts_zs += [z] * len(vs) art3d.patch_2d_to_3d(p, z, zdir) if 'alpha' in kwargs: p.set_alpha(kwargs['alpha']) if len(verts) > 0: (xs, ys) = zip(*verts) else: (xs, ys) = ([], []) (xs, ys, verts_zs) = art3d.juggle_axes(xs, ys, verts_zs, zdir) self.auto_scale_xyz(xs, ys, verts_zs, had_data) return patches @_preprocess_data() def bar3d(self, x, y, z, dx, dy, dz, color=None, zsort='average', shade=True, lightsource=None, *args, **kwargs): had_data = self.has_data() (x, y, z, dx, dy, dz) = np.broadcast_arrays(np.atleast_1d(x), y, z, dx, dy, dz) minx = np.min(x) maxx = np.max(x + dx) miny = np.min(y) maxy = np.max(y + dy) minz = np.min(z) maxz = np.max(z + dz) cuboid = np.array([((0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0)), ((0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)), ((0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1)), ((0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0)), ((0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)), ((1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1))]) polys = np.empty(x.shape + cuboid.shape) for (i, p, dp) in [(0, x, dx), (1, y, dy), (2, z, dz)]: p = p[..., np.newaxis, np.newaxis] dp = dp[..., np.newaxis, np.newaxis] polys[..., i] = p + dp * cuboid[..., i] polys = polys.reshape((-1,) + polys.shape[2:]) facecolors = [] if color is None: color = [self._get_patches_for_fill.get_next_color()] color = list(mcolors.to_rgba_array(color)) if len(color) == len(x): for c in color: facecolors.extend([c] * 6) else: facecolors = color if len(facecolors) < len(x): facecolors *= 6 * len(x) col = art3d.Poly3DCollection(polys, *args, zsort=zsort, facecolors=facecolors, shade=shade, lightsource=lightsource, **kwargs) self.add_collection(col) self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data) return col def set_title(self, label, fontdict=None, loc='center', **kwargs): ret = super().set_title(label, fontdict=fontdict, loc=loc, **kwargs) (x, y) = self.title.get_position() self.title.set_y(0.92 * y) return ret @_preprocess_data() def quiver(self, X, Y, Z, U, V, W, *, length=1, arrow_length_ratio=0.3, pivot='tail', normalize=False, **kwargs): def calc_arrows(UVW): x = UVW[:, 0] y = UVW[:, 1] norm = np.linalg.norm(UVW[:, :2], axis=1) x_p = np.divide(y, norm, where=norm != 0, out=np.zeros_like(x)) y_p = np.divide(-x, norm, where=norm != 0, out=np.ones_like(x)) rangle = math.radians(15) c = math.cos(rangle) s = math.sin(rangle) r13 = y_p * s r32 = x_p * s r12 = x_p * y_p * (1 - c) Rpos = np.array([[c + x_p ** 2 * (1 - c), r12, r13], [r12, c + y_p ** 2 * (1 - c), -r32], [-r13, r32, np.full_like(x_p, c)]]) Rneg = Rpos.copy() Rneg[[0, 1, 2, 2], [2, 2, 0, 1]] *= -1 Rpos_vecs = np.einsum('ij...,...j->...i', Rpos, UVW) Rneg_vecs = np.einsum('ij...,...j->...i', Rneg, UVW) return np.stack([Rpos_vecs, Rneg_vecs], axis=1) had_data = self.has_data() input_args = cbook._broadcast_with_masks(X, Y, Z, U, V, W, compress=True) if any((len(v) == 0 for v in input_args)): linec = art3d.Line3DCollection([], **kwargs) self.add_collection(linec) return linec shaft_dt = np.array([0.0, length], dtype=float) arrow_dt = shaft_dt * arrow_length_ratio _api.check_in_list(['tail', 'middle', 'tip'], pivot=pivot) if pivot == 'tail': shaft_dt -= length elif pivot == 'middle': shaft_dt -= length / 2 XYZ = np.column_stack(input_args[:3]) UVW = np.column_stack(input_args[3:]).astype(float) if normalize: norm = np.linalg.norm(UVW, axis=1) norm[norm == 0] = 1 UVW = UVW / norm.reshape((-1, 1)) if len(XYZ) > 0: shafts = (XYZ - np.multiply.outer(shaft_dt, UVW)).swapaxes(0, 1) head_dirs = calc_arrows(UVW) heads = shafts[:, :1] - np.multiply.outer(arrow_dt, head_dirs) heads = heads.reshape((len(arrow_dt), -1, 3)) heads = heads.swapaxes(0, 1) lines = [*shafts, *heads[::2], *heads[1::2]] else: lines = [] linec = art3d.Line3DCollection(lines, **kwargs) self.add_collection(linec) self.auto_scale_xyz(XYZ[:, 0], XYZ[:, 1], XYZ[:, 2], had_data) return linec quiver3D = quiver def voxels(self, *args, facecolors=None, edgecolors=None, shade=True, lightsource=None, **kwargs): if len(args) >= 3: def voxels(__x, __y, __z, filled, **kwargs): return ((__x, __y, __z), filled, kwargs) else: def voxels(filled, **kwargs): return (None, filled, kwargs) (xyz, filled, kwargs) = voxels(*args, **kwargs) if filled.ndim != 3: raise ValueError('Argument filled must be 3-dimensional') size = np.array(filled.shape, dtype=np.intp) coord_shape = tuple(size + 1) if xyz is None: (x, y, z) = np.indices(coord_shape) else: (x, y, z) = (np.broadcast_to(c, coord_shape) for c in xyz) def _broadcast_color_arg(color, name): if np.ndim(color) in (0, 1): return np.broadcast_to(color, filled.shape + np.shape(color)) elif np.ndim(color) in (3, 4): if np.shape(color)[:3] != filled.shape: raise ValueError(f'When multidimensional, {name} must match the shape of filled') return color else: raise ValueError(f'Invalid {name} argument') if facecolors is None: facecolors = self._get_patches_for_fill.get_next_color() facecolors = _broadcast_color_arg(facecolors, 'facecolors') edgecolors = _broadcast_color_arg(edgecolors, 'edgecolors') self.auto_scale_xyz(x, y, z) square = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], dtype=np.intp) voxel_faces = defaultdict(list) def permutation_matrices(n): mat = np.eye(n, dtype=np.intp) for i in range(n): yield mat mat = np.roll(mat, 1, axis=0) for permute in permutation_matrices(3): (pc, qc, rc) = permute.T.dot(size) pinds = np.arange(pc) qinds = np.arange(qc) rinds = np.arange(rc) square_rot_pos = square.dot(permute.T) square_rot_neg = square_rot_pos[::-1] for p in pinds: for q in qinds: p0 = permute.dot([p, q, 0]) i0 = tuple(p0) if filled[i0]: voxel_faces[i0].append(p0 + square_rot_neg) for (r1, r2) in itertools.pairwise(rinds): p1 = permute.dot([p, q, r1]) p2 = permute.dot([p, q, r2]) i1 = tuple(p1) i2 = tuple(p2) if filled[i1] and (not filled[i2]): voxel_faces[i1].append(p2 + square_rot_pos) elif not filled[i1] and filled[i2]: voxel_faces[i2].append(p2 + square_rot_neg) pk = permute.dot([p, q, rc - 1]) pk2 = permute.dot([p, q, rc]) ik = tuple(pk) if filled[ik]: voxel_faces[ik].append(pk2 + square_rot_pos) polygons = {} for (coord, faces_inds) in voxel_faces.items(): if xyz is None: faces = faces_inds else: faces = [] for face_inds in faces_inds: ind = (face_inds[:, 0], face_inds[:, 1], face_inds[:, 2]) face = np.empty(face_inds.shape) face[:, 0] = x[ind] face[:, 1] = y[ind] face[:, 2] = z[ind] faces.append(face) facecolor = facecolors[coord] edgecolor = edgecolors[coord] poly = art3d.Poly3DCollection(faces, facecolors=facecolor, edgecolors=edgecolor, shade=shade, lightsource=lightsource, **kwargs) self.add_collection3d(poly) polygons[coord] = poly return polygons @_preprocess_data(replace_names=['x', 'y', 'z', 'xerr', 'yerr', 'zerr']) def errorbar(self, x, y, z, zerr=None, yerr=None, xerr=None, fmt='', barsabove=False, errorevery=1, ecolor=None, elinewidth=None, capsize=None, capthick=None, xlolims=False, xuplims=False, ylolims=False, yuplims=False, zlolims=False, zuplims=False, **kwargs): had_data = self.has_data() kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) kwargs = {k: v for (k, v) in kwargs.items() if v is not None} kwargs.setdefault('zorder', 2) self._process_unit_info([('x', x), ('y', y), ('z', z)], kwargs, convert=False) x = x if np.iterable(x) else [x] y = y if np.iterable(y) else [y] z = z if np.iterable(z) else [z] if not len(x) == len(y) == len(z): raise ValueError("'x', 'y', and 'z' must have the same size") everymask = self._errorevery_to_mask(x, errorevery) label = kwargs.pop('label', None) kwargs['label'] = '_nolegend_' ((data_line, base_style),) = self._get_lines._plot_args(self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True) art3d.line_2d_to_3d(data_line, zs=z) if barsabove: data_line.set_zorder(kwargs['zorder'] - 0.1) else: data_line.set_zorder(kwargs['zorder'] + 0.1) if fmt.lower() != 'none': self.add_line(data_line) else: data_line = None base_style.pop('color') if 'color' not in base_style: base_style['color'] = 'C0' if ecolor is None: ecolor = base_style['color'] for key in ['marker', 'markersize', 'markerfacecolor', 'markeredgewidth', 'markeredgecolor', 'markevery', 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle', 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle']: base_style.pop(key, None) eb_lines_style = {**base_style, 'color': ecolor} if elinewidth: eb_lines_style['linewidth'] = elinewidth elif 'linewidth' in kwargs: eb_lines_style['linewidth'] = kwargs['linewidth'] for key in ('transform', 'alpha', 'zorder', 'rasterized'): if key in kwargs: eb_lines_style[key] = kwargs[key] eb_cap_style = {**base_style, 'linestyle': 'None'} if capsize is None: capsize = mpl.rcParams['errorbar.capsize'] if capsize > 0: eb_cap_style['markersize'] = 2.0 * capsize if capthick is not None: eb_cap_style['markeredgewidth'] = capthick eb_cap_style['color'] = ecolor def _apply_mask(arrays, mask): return [[*itertools.compress(array, mask)] for array in arrays] def _extract_errs(err, data, lomask, himask): if len(err.shape) == 2: (low_err, high_err) = err else: (low_err, high_err) = (err, err) lows = np.where(lomask | ~everymask, data, data - low_err) highs = np.where(himask | ~everymask, data, data + high_err) return (lows, highs) (errlines, caplines, limmarks) = ([], [], []) coorderrs = [] capmarker = {0: '|', 1: '|', 2: '_'} i_xyz = {'x': 0, 'y': 1, 'z': 2} quiversize = eb_cap_style.get('markersize', mpl.rcParams['lines.markersize']) ** 2 quiversize *= self.get_figure(root=True).dpi / 72 quiversize = self.transAxes.inverted().transform([(0, 0), (quiversize, quiversize)]) quiversize = np.mean(np.diff(quiversize, axis=0)) with cbook._setattr_cm(self, elev=0, azim=0, roll=0): invM = np.linalg.inv(self.get_proj()) quiversize = np.dot(invM, [quiversize, 0, 0, 0])[1] quiversize *= 1.8660254037844388 eb_quiver_style = {**eb_cap_style, 'length': quiversize, 'arrow_length_ratio': 1} eb_quiver_style.pop('markersize', None) for (zdir, data, err, lolims, uplims) in zip(['x', 'y', 'z'], [x, y, z], [xerr, yerr, zerr], [xlolims, ylolims, zlolims], [xuplims, yuplims, zuplims]): dir_vector = art3d.get_dir_vector(zdir) i_zdir = i_xyz[zdir] if err is None: continue if not np.iterable(err): err = [err] * len(data) err = np.atleast_1d(err) lolims = np.broadcast_to(lolims, len(data)).astype(bool) uplims = np.broadcast_to(uplims, len(data)).astype(bool) coorderr = [_extract_errs(err * dir_vector[i], coord, lolims, uplims) for (i, coord) in enumerate([x, y, z])] ((xl, xh), (yl, yh), (zl, zh)) = coorderr nolims = ~(lolims | uplims) if nolims.any() and capsize > 0: lo_caps_xyz = _apply_mask([xl, yl, zl], nolims & everymask) hi_caps_xyz = _apply_mask([xh, yh, zh], nolims & everymask) cap_lo = art3d.Line3D(*lo_caps_xyz, ls='', marker=capmarker[i_zdir], **eb_cap_style) cap_hi = art3d.Line3D(*hi_caps_xyz, ls='', marker=capmarker[i_zdir], **eb_cap_style) self.add_line(cap_lo) self.add_line(cap_hi) caplines.append(cap_lo) caplines.append(cap_hi) if lolims.any(): (xh0, yh0, zh0) = _apply_mask([xh, yh, zh], lolims & everymask) self.quiver(xh0, yh0, zh0, *dir_vector, **eb_quiver_style) if uplims.any(): (xl0, yl0, zl0) = _apply_mask([xl, yl, zl], uplims & everymask) self.quiver(xl0, yl0, zl0, *-dir_vector, **eb_quiver_style) errline = art3d.Line3DCollection(np.array(coorderr).T, **eb_lines_style) self.add_collection(errline) errlines.append(errline) coorderrs.append(coorderr) coorderrs = np.array(coorderrs) def _digout_minmax(err_arr, coord_label): return (np.nanmin(err_arr[:, i_xyz[coord_label], :, :]), np.nanmax(err_arr[:, i_xyz[coord_label], :, :])) (minx, maxx) = _digout_minmax(coorderrs, 'x') (miny, maxy) = _digout_minmax(coorderrs, 'y') (minz, maxz) = _digout_minmax(coorderrs, 'z') self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data) errorbar_container = mcontainer.ErrorbarContainer((data_line, tuple(caplines), tuple(errlines)), has_xerr=xerr is not None or yerr is not None, has_yerr=zerr is not None, label=label) self.containers.append(errorbar_container) return (errlines, caplines, limmarks) def get_tightbbox(self, renderer=None, *, call_axes_locator=True, bbox_extra_artists=None, for_layout_only=False): ret = super().get_tightbbox(renderer, call_axes_locator=call_axes_locator, bbox_extra_artists=bbox_extra_artists, for_layout_only=for_layout_only) batch = [ret] if self._axis3don: for axis in self._axis_map.values(): if axis.get_visible(): axis_bb = martist._get_tightbbox_for_layout_only(axis, renderer) if axis_bb: batch.append(axis_bb) return mtransforms.Bbox.union(batch) @_preprocess_data() def stem(self, x, y, z, *, linefmt='C0-', markerfmt='C0o', basefmt='C3-', bottom=0, label=None, orientation='z'): from matplotlib.container import StemContainer had_data = self.has_data() _api.check_in_list(['x', 'y', 'z'], orientation=orientation) xlim = (np.min(x), np.max(x)) ylim = (np.min(y), np.max(y)) zlim = (np.min(z), np.max(z)) if orientation == 'x': (basex, basexlim) = (y, ylim) (basey, baseylim) = (z, zlim) lines = [[(bottom, thisy, thisz), (thisx, thisy, thisz)] for (thisx, thisy, thisz) in zip(x, y, z)] elif orientation == 'y': (basex, basexlim) = (x, xlim) (basey, baseylim) = (z, zlim) lines = [[(thisx, bottom, thisz), (thisx, thisy, thisz)] for (thisx, thisy, thisz) in zip(x, y, z)] else: (basex, basexlim) = (x, xlim) (basey, baseylim) = (y, ylim) lines = [[(thisx, thisy, bottom), (thisx, thisy, thisz)] for (thisx, thisy, thisz) in zip(x, y, z)] (linestyle, linemarker, linecolor) = _process_plot_format(linefmt) if linestyle is None: linestyle = mpl.rcParams['lines.linestyle'] (baseline,) = self.plot(basex, basey, basefmt, zs=bottom, zdir=orientation, label='_nolegend_') stemlines = art3d.Line3DCollection(lines, linestyles=linestyle, colors=linecolor, label='_nolegend_') self.add_collection(stemlines) (markerline,) = self.plot(x, y, z, markerfmt, label='_nolegend_') stem_container = StemContainer((markerline, stemlines, baseline), label=label) self.add_container(stem_container) (jx, jy, jz) = art3d.juggle_axes(basexlim, baseylim, [bottom, bottom], orientation) self.auto_scale_xyz([*jx, *xlim], [*jy, *ylim], [*jz, *zlim], had_data) return stem_container stem3D = stem def get_test_data(delta=0.05): x = y = np.arange(-3.0, 3.0, delta) (X, Y) = np.meshgrid(x, y) Z1 = np.exp(-(X ** 2 + Y ** 2) / 2) / (2 * np.pi) Z2 = np.exp(-(((X - 1) / 1.5) ** 2 + ((Y - 1) / 0.5) ** 2) / 2) / (2 * np.pi * 0.5 * 1.5) Z = Z2 - Z1 X = X * 10 Y = Y * 10 Z = Z * 500 return (X, Y, Z) class _Quaternion: def __init__(self, scalar, vector): self.scalar = scalar self.vector = np.array(vector) def __neg__(self): return self.__class__(-self.scalar, -self.vector) def __mul__(self, other): return self.__class__(self.scalar * other.scalar - np.dot(self.vector, other.vector), self.scalar * other.vector + self.vector * other.scalar + np.cross(self.vector, other.vector)) def conjugate(self): return self.__class__(self.scalar, -self.vector) @property def norm(self): return self.scalar * self.scalar + np.dot(self.vector, self.vector) def normalize(self): n = np.sqrt(self.norm) return self.__class__(self.scalar / n, self.vector / n) def reciprocal(self): n = self.norm return self.__class__(self.scalar / n, -self.vector / n) def __div__(self, other): return self * other.reciprocal() __truediv__ = __div__ def rotate(self, v): v = self.__class__(0, v) v = self * v / self return v.vector def __eq__(self, other): return self.scalar == other.scalar and (self.vector == other.vector).all def __repr__(self): return '_Quaternion({}, {})'.format(repr(self.scalar), repr(self.vector)) @classmethod def rotate_from_to(cls, r1, r2): k = np.cross(r1, r2) nk = np.linalg.norm(k) th = np.arctan2(nk, np.dot(r1, r2)) th = th / 2 if nk == 0: if np.dot(r1, r2) < 0: warnings.warn('Rotation defined by anti-parallel vectors is ambiguous') k = np.zeros(3) k[np.argmin(r1 * r1)] = 1 k = np.cross(r1, k) k = k / np.linalg.norm(k) q = cls(0, k) else: q = cls(1, [0, 0, 0]) else: q = cls(math.cos(th), k * math.sin(th) / nk) return q @classmethod def from_cardan_angles(cls, elev, azim, roll): (ca, sa) = (np.cos(azim / 2), np.sin(azim / 2)) (ce, se) = (np.cos(elev / 2), np.sin(elev / 2)) (cr, sr) = (np.cos(roll / 2), np.sin(roll / 2)) qw = ca * ce * cr + sa * se * sr qx = ca * ce * sr - sa * se * cr qy = ca * se * cr + sa * ce * sr qz = ca * se * sr - sa * ce * cr return cls(qw, [qx, qy, qz]) def as_cardan_angles(self): qw = self.scalar (qx, qy, qz) = self.vector[..., :] azim = np.arctan2(2 * (-qw * qz + qx * qy), qw * qw + qx * qx - qy * qy - qz * qz) elev = np.arcsin(2 * (qw * qy + qz * qx) / (qw * qw + qx * qx + qy * qy + qz * qz)) roll = np.arctan2(2 * (qw * qx - qy * qz), qw * qw - qx * qx - qy * qy + qz * qz) return (elev, azim, roll) # File: matplotlib-main/lib/mpl_toolkits/mplot3d/axis3d.py import inspect import numpy as np import matplotlib as mpl from matplotlib import _api, artist, lines as mlines, axis as maxis, patches as mpatches, transforms as mtransforms, colors as mcolors from . import art3d, proj3d def _move_from_center(coord, centers, deltas, axmask=(True, True, True)): coord = np.asarray(coord) return coord + axmask * np.copysign(1, coord - centers) * deltas def _tick_update_position(tick, tickxs, tickys, labelpos): tick.label1.set_position(labelpos) tick.label2.set_position(labelpos) tick.tick1line.set_visible(True) tick.tick2line.set_visible(False) tick.tick1line.set_linestyle('-') tick.tick1line.set_marker('') tick.tick1line.set_data(tickxs, tickys) tick.gridline.set_data([0], [0]) class Axis(maxis.XAxis): _PLANES = ((0, 3, 7, 4), (1, 2, 6, 5), (0, 1, 5, 4), (3, 2, 6, 7), (0, 1, 2, 3), (4, 5, 6, 7)) _AXINFO = {'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2)}, 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2)}, 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1)}} def _old_init(self, adir, v_intervalx, d_intervalx, axes, *args, rotate_label=None, **kwargs): return locals() def _new_init(self, axes, *, rotate_label=None, **kwargs): return locals() def __init__(self, *args, **kwargs): params = _api.select_matching_signature([self._old_init, self._new_init], *args, **kwargs) if 'adir' in params: _api.warn_deprecated('3.6', message=f'The signature of 3D Axis constructors has changed in %(since)s; the new signature is {inspect.signature(type(self).__init__)}', pending=True) if params['adir'] != self.axis_name: raise ValueError(f"Cannot instantiate {type(self).__name__} with adir={params['adir']!r}") axes = params['axes'] rotate_label = params['rotate_label'] args = params.get('args', ()) kwargs = params['kwargs'] name = self.axis_name self._label_position = 'default' self._tick_position = 'default' self._axinfo = self._AXINFO[name].copy() self._axinfo.update({'label': {'va': 'center', 'ha': 'center', 'rotation_mode': 'anchor'}, 'color': mpl.rcParams[f'axes3d.{name}axis.panecolor'], 'tick': {'inward_factor': 0.2, 'outward_factor': 0.1}}) if mpl.rcParams['_internal.classic_mode']: self._axinfo.update({'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)}, 'grid': {'color': (0.9, 0.9, 0.9, 1), 'linewidth': 1.0, 'linestyle': '-'}}) self._axinfo['tick'].update({'linewidth': {True: mpl.rcParams['lines.linewidth'], False: mpl.rcParams['lines.linewidth']}}) else: self._axinfo.update({'axisline': {'linewidth': mpl.rcParams['axes.linewidth'], 'color': mpl.rcParams['axes.edgecolor']}, 'grid': {'color': mpl.rcParams['grid.color'], 'linewidth': mpl.rcParams['grid.linewidth'], 'linestyle': mpl.rcParams['grid.linestyle']}}) self._axinfo['tick'].update({'linewidth': {True: mpl.rcParams['xtick.major.width'] if name in 'xz' else mpl.rcParams['ytick.major.width'], False: mpl.rcParams['xtick.minor.width'] if name in 'xz' else mpl.rcParams['ytick.minor.width']}}) super().__init__(axes, *args, **kwargs) if 'd_intervalx' in params: self.set_data_interval(*params['d_intervalx']) if 'v_intervalx' in params: self.set_view_interval(*params['v_intervalx']) self.set_rotate_label(rotate_label) self._init3d() __init__.__signature__ = inspect.signature(_new_init) adir = _api.deprecated('3.6', pending=True)(property(lambda self: self.axis_name)) def _init3d(self): self.line = mlines.Line2D(xdata=(0, 0), ydata=(0, 0), linewidth=self._axinfo['axisline']['linewidth'], color=self._axinfo['axisline']['color'], antialiased=True) self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False) self.set_pane_color(self._axinfo['color']) self.axes._set_artist_props(self.line) self.axes._set_artist_props(self.pane) self.gridlines = art3d.Line3DCollection([]) self.axes._set_artist_props(self.gridlines) self.axes._set_artist_props(self.label) self.axes._set_artist_props(self.offsetText) self.label._transform = self.axes.transData self.offsetText._transform = self.axes.transData @_api.deprecated('3.6', pending=True) def init3d(self): self._init3d() def get_major_ticks(self, numticks=None): ticks = super().get_major_ticks(numticks) for t in ticks: for obj in [t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]: obj.set_transform(self.axes.transData) return ticks def get_minor_ticks(self, numticks=None): ticks = super().get_minor_ticks(numticks) for t in ticks: for obj in [t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]: obj.set_transform(self.axes.transData) return ticks def set_ticks_position(self, position): if position in ['top', 'bottom']: _api.warn_deprecated('3.8', name=f'position={position!r}', obj_type='argument value', alternative="'upper' or 'lower'") return _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'], position=position) self._tick_position = position def get_ticks_position(self): return self._tick_position def set_label_position(self, position): if position in ['top', 'bottom']: _api.warn_deprecated('3.8', name=f'position={position!r}', obj_type='argument value', alternative="'upper' or 'lower'") return _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'], position=position) self._label_position = position def get_label_position(self): return self._label_position def set_pane_color(self, color, alpha=None): color = mcolors.to_rgba(color, alpha) self._axinfo['color'] = color self.pane.set_edgecolor(color) self.pane.set_facecolor(color) self.pane.set_alpha(color[-1]) self.stale = True def set_rotate_label(self, val): self._rotate_label = val self.stale = True def get_rotate_label(self, text): if self._rotate_label is not None: return self._rotate_label else: return len(text) > 4 def _get_coord_info(self): (mins, maxs) = np.array([self.axes.get_xbound(), self.axes.get_ybound(), self.axes.get_zbound()]).T bounds = (mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2]) bounds_proj = self.axes._transformed_cube(bounds) means_z0 = np.zeros(3) means_z1 = np.zeros(3) for i in range(3): means_z0[i] = np.mean(bounds_proj[self._PLANES[2 * i], 2]) means_z1[i] = np.mean(bounds_proj[self._PLANES[2 * i + 1], 2]) highs = means_z0 < means_z1 equals = np.abs(means_z0 - means_z1) <= np.finfo(float).eps if np.sum(equals) == 2: vertical = np.where(~equals)[0][0] if vertical == 2: highs = np.array([True, True, highs[2]]) elif vertical == 1: highs = np.array([True, highs[1], False]) elif vertical == 0: highs = np.array([highs[0], False, False]) return (mins, maxs, bounds_proj, highs) def _calc_centers_deltas(self, maxs, mins): centers = 0.5 * (maxs + mins) scale = 0.08 deltas = (maxs - mins) * scale return (centers, deltas) def _get_axis_line_edge_points(self, minmax, maxmin, position=None): mb = [minmax, maxmin] mb_rev = mb[::-1] mm = [[mb, mb_rev, mb_rev], [mb_rev, mb_rev, mb], [mb, mb, mb]] mm = mm[self.axes._vertical_axis][self._axinfo['i']] juggled = self._axinfo['juggled'] edge_point_0 = mm[0].copy() if position == 'lower' and mm[1][juggled[-1]] < mm[0][juggled[-1]] or (position == 'upper' and mm[1][juggled[-1]] > mm[0][juggled[-1]]): edge_point_0[juggled[-1]] = mm[1][juggled[-1]] else: edge_point_0[juggled[0]] = mm[1][juggled[0]] edge_point_1 = edge_point_0.copy() edge_point_1[juggled[1]] = mm[1][juggled[1]] return (edge_point_0, edge_point_1) def _get_all_axis_line_edge_points(self, minmax, maxmin, axis_position=None): edgep1s = [] edgep2s = [] position = [] if axis_position in (None, 'default'): (edgep1, edgep2) = self._get_axis_line_edge_points(minmax, maxmin) edgep1s = [edgep1] edgep2s = [edgep2] position = ['default'] else: (edgep1_l, edgep2_l) = self._get_axis_line_edge_points(minmax, maxmin, position='lower') (edgep1_u, edgep2_u) = self._get_axis_line_edge_points(minmax, maxmin, position='upper') if axis_position in ('lower', 'both'): edgep1s.append(edgep1_l) edgep2s.append(edgep2_l) position.append('lower') if axis_position in ('upper', 'both'): edgep1s.append(edgep1_u) edgep2s.append(edgep2_u) position.append('upper') return (edgep1s, edgep2s, position) def _get_tickdir(self, position): _api.check_in_list(('upper', 'lower', 'default'), position=position) tickdirs_base = [v['tickdir'] for v in self._AXINFO.values()] elev_mod = np.mod(self.axes.elev + 180, 360) - 180 azim_mod = np.mod(self.axes.azim, 360) if position == 'upper': if elev_mod >= 0: tickdirs_base = [2, 2, 0] else: tickdirs_base = [1, 0, 0] if 0 <= azim_mod < 180: tickdirs_base[2] = 1 elif position == 'lower': if elev_mod >= 0: tickdirs_base = [1, 0, 1] else: tickdirs_base = [2, 2, 1] if 0 <= azim_mod < 180: tickdirs_base[2] = 0 info_i = [v['i'] for v in self._AXINFO.values()] i = self._axinfo['i'] vert_ax = self.axes._vertical_axis j = vert_ax - 2 tickdir = np.roll(info_i, -j)[np.roll(tickdirs_base, j)][i] return tickdir def active_pane(self): (mins, maxs, tc, highs) = self._get_coord_info() info = self._axinfo index = info['i'] if not highs[index]: loc = mins[index] plane = self._PLANES[2 * index] else: loc = maxs[index] plane = self._PLANES[2 * index + 1] xys = np.array([tc[p] for p in plane]) return (xys, loc) def draw_pane(self, renderer): renderer.open_group('pane3d', gid=self.get_gid()) (xys, loc) = self.active_pane() self.pane.xy = xys[:, :2] self.pane.draw(renderer) renderer.close_group('pane3d') def _axmask(self): axmask = [True, True, True] axmask[self._axinfo['i']] = False return axmask def _draw_ticks(self, renderer, edgep1, centers, deltas, highs, deltas_per_point, pos): ticks = self._update_ticks() info = self._axinfo index = info['i'] juggled = info['juggled'] (mins, maxs, tc, highs) = self._get_coord_info() (centers, deltas) = self._calc_centers_deltas(maxs, mins) tickdir = self._get_tickdir(pos) tickdelta = deltas[tickdir] if highs[tickdir] else -deltas[tickdir] tick_info = info['tick'] tick_out = tick_info['outward_factor'] * tickdelta tick_in = tick_info['inward_factor'] * tickdelta tick_lw = tick_info['linewidth'] edgep1_tickdir = edgep1[tickdir] out_tickdir = edgep1_tickdir + tick_out in_tickdir = edgep1_tickdir - tick_in default_label_offset = 8.0 points = deltas_per_point * deltas for tick in ticks: pos = edgep1.copy() pos[index] = tick.get_loc() pos[tickdir] = out_tickdir (x1, y1, z1) = proj3d.proj_transform(*pos, self.axes.M) pos[tickdir] = in_tickdir (x2, y2, z2) = proj3d.proj_transform(*pos, self.axes.M) labeldeltas = (tick.get_pad() + default_label_offset) * points pos[tickdir] = edgep1_tickdir pos = _move_from_center(pos, centers, labeldeltas, self._axmask()) (lx, ly, lz) = proj3d.proj_transform(*pos, self.axes.M) _tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly)) tick.tick1line.set_linewidth(tick_lw[tick._major]) tick.draw(renderer) def _draw_offset_text(self, renderer, edgep1, edgep2, labeldeltas, centers, highs, pep, dx, dy): info = self._axinfo index = info['i'] juggled = info['juggled'] tickdir = info['tickdir'] if juggled[2] == 2: outeredgep = edgep1 outerindex = 0 else: outeredgep = edgep2 outerindex = 1 pos = _move_from_center(outeredgep, centers, labeldeltas, self._axmask()) (olx, oly, olz) = proj3d.proj_transform(*pos, self.axes.M) self.offsetText.set_text(self.major.formatter.get_offset()) self.offsetText.set_position((olx, oly)) angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx))) self.offsetText.set_rotation(angle) self.offsetText.set_rotation_mode('anchor') centpt = proj3d.proj_transform(*centers, self.axes.M) if centpt[tickdir] > pep[tickdir, outerindex]: if centpt[index] <= pep[index, outerindex] and np.count_nonzero(highs) % 2 == 0: if highs.tolist() == [False, True, True] and index in (1, 2): align = 'left' else: align = 'right' else: align = 'left' elif centpt[index] > pep[index, outerindex] and np.count_nonzero(highs) % 2 == 0: align = 'right' if index == 2 else 'left' else: align = 'right' self.offsetText.set_va('center') self.offsetText.set_ha(align) self.offsetText.draw(renderer) def _draw_labels(self, renderer, edgep1, edgep2, labeldeltas, centers, dx, dy): label = self._axinfo['label'] lxyz = 0.5 * (edgep1 + edgep2) lxyz = _move_from_center(lxyz, centers, labeldeltas, self._axmask()) (tlx, tly, tlz) = proj3d.proj_transform(*lxyz, self.axes.M) self.label.set_position((tlx, tly)) if self.get_rotate_label(self.label.get_text()): angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx))) self.label.set_rotation(angle) self.label.set_va(label['va']) self.label.set_ha(label['ha']) self.label.set_rotation_mode(label['rotation_mode']) self.label.draw(renderer) @artist.allow_rasterization def draw(self, renderer): self.label._transform = self.axes.transData self.offsetText._transform = self.axes.transData renderer.open_group('axis3d', gid=self.get_gid()) (mins, maxs, tc, highs) = self._get_coord_info() (centers, deltas) = self._calc_centers_deltas(maxs, mins) reltoinches = self.get_figure(root=False).dpi_scale_trans.inverted() ax_inches = reltoinches.transform(self.axes.bbox.size) ax_points_estimate = sum(72.0 * ax_inches) deltas_per_point = 48 / ax_points_estimate default_offset = 21.0 labeldeltas = (self.labelpad + default_offset) * deltas_per_point * deltas minmax = np.where(highs, maxs, mins) maxmin = np.where(~highs, maxs, mins) for (edgep1, edgep2, pos) in zip(*self._get_all_axis_line_edge_points(minmax, maxmin, self._tick_position)): pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M) pep = np.asarray(pep) (dx, dy) = (self.axes.transAxes.transform([pep[0:2, 1]]) - self.axes.transAxes.transform([pep[0:2, 0]]))[0] self.line.set_data(pep[0], pep[1]) self.line.draw(renderer) self._draw_ticks(renderer, edgep1, centers, deltas, highs, deltas_per_point, pos) self._draw_offset_text(renderer, edgep1, edgep2, labeldeltas, centers, highs, pep, dx, dy) for (edgep1, edgep2, pos) in zip(*self._get_all_axis_line_edge_points(minmax, maxmin, self._label_position)): pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M) pep = np.asarray(pep) (dx, dy) = (self.axes.transAxes.transform([pep[0:2, 1]]) - self.axes.transAxes.transform([pep[0:2, 0]]))[0] self._draw_labels(renderer, edgep1, edgep2, labeldeltas, centers, dx, dy) renderer.close_group('axis3d') self.stale = False @artist.allow_rasterization def draw_grid(self, renderer): if not self.axes._draw_grid: return renderer.open_group('grid3d', gid=self.get_gid()) ticks = self._update_ticks() if len(ticks): info = self._axinfo index = info['i'] (mins, maxs, tc, highs) = self._get_coord_info() minmax = np.where(highs, maxs, mins) maxmin = np.where(~highs, maxs, mins) xyz0 = np.tile(minmax, (len(ticks), 1)) xyz0[:, index] = [tick.get_loc() for tick in ticks] lines = np.stack([xyz0, xyz0, xyz0], axis=1) lines[:, 0, index - 2] = maxmin[index - 2] lines[:, 2, index - 1] = maxmin[index - 1] self.gridlines.set_segments(lines) gridinfo = info['grid'] self.gridlines.set_color(gridinfo['color']) self.gridlines.set_linewidth(gridinfo['linewidth']) self.gridlines.set_linestyle(gridinfo['linestyle']) self.gridlines.do_3d_projection() self.gridlines.draw(renderer) renderer.close_group('grid3d') def get_tightbbox(self, renderer=None, *, for_layout_only=False): if not self.get_visible(): return major_locs = self.get_majorticklocs() minor_locs = self.get_minorticklocs() ticks = [*self.get_minor_ticks(len(minor_locs)), *self.get_major_ticks(len(major_locs))] (view_low, view_high) = self.get_view_interval() if view_low > view_high: (view_low, view_high) = (view_high, view_low) interval_t = self.get_transform().transform([view_low, view_high]) ticks_to_draw = [] for tick in ticks: try: loc_t = self.get_transform().transform(tick.get_loc()) except AssertionError: pass else: if mtransforms._interval_contains_close(interval_t, loc_t): ticks_to_draw.append(tick) ticks = ticks_to_draw (bb_1, bb_2) = self._get_ticklabel_bboxes(ticks, renderer) other = [] if self.line.get_visible(): other.append(self.line.get_window_extent(renderer)) if self.label.get_visible() and (not for_layout_only) and self.label.get_text(): other.append(self.label.get_window_extent(renderer)) return mtransforms.Bbox.union([*bb_1, *bb_2, *other]) d_interval = _api.deprecated('3.6', alternative='get_data_interval', pending=True)(property(lambda self: self.get_data_interval(), lambda self, minmax: self.set_data_interval(*minmax))) v_interval = _api.deprecated('3.6', alternative='get_view_interval', pending=True)(property(lambda self: self.get_view_interval(), lambda self, minmax: self.set_view_interval(*minmax))) class XAxis(Axis): axis_name = 'x' (get_view_interval, set_view_interval) = maxis._make_getset_interval('view', 'xy_viewLim', 'intervalx') (get_data_interval, set_data_interval) = maxis._make_getset_interval('data', 'xy_dataLim', 'intervalx') class YAxis(Axis): axis_name = 'y' (get_view_interval, set_view_interval) = maxis._make_getset_interval('view', 'xy_viewLim', 'intervaly') (get_data_interval, set_data_interval) = maxis._make_getset_interval('data', 'xy_dataLim', 'intervaly') class ZAxis(Axis): axis_name = 'z' (get_view_interval, set_view_interval) = maxis._make_getset_interval('view', 'zz_viewLim', 'intervalx') (get_data_interval, set_data_interval) = maxis._make_getset_interval('data', 'zz_dataLim', 'intervalx') # File: matplotlib-main/lib/mpl_toolkits/mplot3d/proj3d.py """""" import numpy as np from matplotlib import _api def world_transformation(xmin, xmax, ymin, ymax, zmin, zmax, pb_aspect=None): dx = xmax - xmin dy = ymax - ymin dz = zmax - zmin if pb_aspect is not None: (ax, ay, az) = pb_aspect dx /= ax dy /= ay dz /= az return np.array([[1 / dx, 0, 0, -xmin / dx], [0, 1 / dy, 0, -ymin / dy], [0, 0, 1 / dz, -zmin / dz], [0, 0, 0, 1]]) def _rotation_about_vector(v, angle): (vx, vy, vz) = v / np.linalg.norm(v) s = np.sin(angle) c = np.cos(angle) t = 2 * np.sin(angle / 2) ** 2 R = np.array([[t * vx * vx + c, t * vx * vy - vz * s, t * vx * vz + vy * s], [t * vy * vx + vz * s, t * vy * vy + c, t * vy * vz - vx * s], [t * vz * vx - vy * s, t * vz * vy + vx * s, t * vz * vz + c]]) return R def _view_axes(E, R, V, roll): w = E - R w = w / np.linalg.norm(w) u = np.cross(V, w) u = u / np.linalg.norm(u) v = np.cross(w, u) if roll != 0: Rroll = _rotation_about_vector(w, -roll) u = np.dot(Rroll, u) v = np.dot(Rroll, v) return (u, v, w) def _view_transformation_uvw(u, v, w, E): Mr = np.eye(4) Mt = np.eye(4) Mr[:3, :3] = [u, v, w] Mt[:3, -1] = -E M = np.dot(Mr, Mt) return M def _persp_transformation(zfront, zback, focal_length): e = focal_length a = 1 b = (zfront + zback) / (zfront - zback) c = -2 * (zfront * zback) / (zfront - zback) proj_matrix = np.array([[e, 0, 0, 0], [0, e / a, 0, 0], [0, 0, b, c], [0, 0, -1, 0]]) return proj_matrix def _ortho_transformation(zfront, zback): a = -(zfront + zback) b = -(zfront - zback) proj_matrix = np.array([[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, -2, 0], [0, 0, a, b]]) return proj_matrix def _proj_transform_vec(vec, M): vecw = np.dot(M, vec) w = vecw[3] (txs, tys, tzs) = (vecw[0] / w, vecw[1] / w, vecw[2] / w) return (txs, tys, tzs) def _proj_transform_vec_clip(vec, M, focal_length): vecw = np.dot(M, vec) w = vecw[3] (txs, tys, tzs) = (vecw[0] / w, vecw[1] / w, vecw[2] / w) if np.isinf(focal_length): tis = np.ones(txs.shape, dtype=bool) else: tis = (-1 <= txs) & (txs <= 1) & (-1 <= tys) & (tys <= 1) & (tzs <= 0) txs = np.ma.masked_array(txs, ~tis) tys = np.ma.masked_array(tys, ~tis) tzs = np.ma.masked_array(tzs, ~tis) return (txs, tys, tzs, tis) def inv_transform(xs, ys, zs, invM): vec = _vec_pad_ones(xs, ys, zs) vecr = np.dot(invM, vec) if vecr.shape == (4,): vecr = vecr.reshape((4, 1)) for i in range(vecr.shape[1]): if vecr[3][i] != 0: vecr[:, i] = vecr[:, i] / vecr[3][i] return (vecr[0], vecr[1], vecr[2]) def _vec_pad_ones(xs, ys, zs): return np.array([xs, ys, zs, np.ones_like(xs)]) def proj_transform(xs, ys, zs, M): vec = _vec_pad_ones(xs, ys, zs) return _proj_transform_vec(vec, M) @_api.deprecated('3.10') def proj_transform_clip(xs, ys, zs, M): return _proj_transform_clip(xs, ys, zs, M, focal_length=np.inf) def _proj_transform_clip(xs, ys, zs, M, focal_length): vec = _vec_pad_ones(xs, ys, zs) return _proj_transform_vec_clip(vec, M, focal_length) def _proj_points(points, M): return np.column_stack(_proj_trans_points(points, M)) def _proj_trans_points(points, M): (xs, ys, zs) = zip(*points) return proj_transform(xs, ys, zs, M) # File: matplotlib-main/tools/boilerplate.py """""" import ast from enum import Enum import functools import inspect from inspect import Parameter from pathlib import Path import sys import subprocess import numpy as np from matplotlib import _api, mlab from matplotlib.axes import Axes from matplotlib.figure import Figure PYPLOT_MAGIC_HEADER = '################# REMAINING CONTENT GENERATED BY boilerplate.py ##############\n' AUTOGEN_MSG = '\n\n# Autogenerated by boilerplate.py. Do not edit as changes will be lost.' AXES_CMAPPABLE_METHOD_TEMPLATE = AUTOGEN_MSG + '\n@_copy_docstring_and_deprecators(Axes.{called_name})\ndef {name}{signature}:\n __ret = gca().{called_name}{call}\n {sci_command}\n return __ret\n' AXES_METHOD_TEMPLATE = AUTOGEN_MSG + '\n@_copy_docstring_and_deprecators(Axes.{called_name})\ndef {name}{signature}:\n {return_statement}gca().{called_name}{call}\n' FIGURE_METHOD_TEMPLATE = AUTOGEN_MSG + '\n@_copy_docstring_and_deprecators(Figure.{called_name})\ndef {name}{signature}:\n {return_statement}gcf().{called_name}{call}\n' CMAP_TEMPLATE = '\ndef {name}() -> None:\n """\n Set the colormap to {name!r}.\n\n This changes the default colormap as well as the colormap of the current\n image if there is one. See ``help(colormaps)`` for more information.\n """\n set_cmap({name!r})\n' class value_formatter: def __init__(self, value): if value is mlab.detrend_none: self._repr = 'mlab.detrend_none' elif value is mlab.window_hanning: self._repr = 'mlab.window_hanning' elif value is np.mean: self._repr = 'np.mean' elif value is _api.deprecation._deprecated_parameter: self._repr = '_api.deprecation._deprecated_parameter' elif isinstance(value, Enum): self._repr = f'{type(value).__name__}.{value.name}' else: self._repr = repr(value) def __repr__(self): return self._repr class direct_repr: def __init__(self, value): self._repr = value def __repr__(self): return self._repr def generate_function(name, called_fullname, template, **kwargs): (class_name, called_name) = called_fullname.split('.') class_ = {'Axes': Axes, 'Figure': Figure}[class_name] meth = getattr(class_, called_name) decorator = _api.deprecation.DECORATORS.get(meth) if decorator and decorator.func is _api.make_keyword_only: meth = meth.__wrapped__ annotated_trees = get_ast_mro_trees(class_) signature = get_matching_signature(meth, annotated_trees) params = list(signature.parameters.values())[1:] has_return_value = str(signature.return_annotation) != 'None' signature = str(signature.replace(parameters=[param.replace(default=value_formatter(param.default)) if param.default is not param.empty else param for param in params])) call = '(' + ', '.join((('{0}' if param.kind in [Parameter.POSITIONAL_OR_KEYWORD] and param.default is Parameter.empty else '**({{"data": data}} if data is not None else {{}})' if param.name == 'data' else '{0}={0}' if param.kind in [Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY] else '{0}' if param.kind is Parameter.POSITIONAL_ONLY else '*{0}' if param.kind is Parameter.VAR_POSITIONAL else '**{0}' if param.kind is Parameter.VAR_KEYWORD else None).format(param.name) for param in params)) + ')' return_statement = 'return ' if has_return_value else '' for reserved in ('gca', 'gci', 'gcf', '__ret'): if reserved in params: raise ValueError(f'Method {called_fullname} has kwarg named {reserved}') return template.format(name=name, called_name=called_name, signature=signature, call=call, return_statement=return_statement, **kwargs) def boilerplate_gen(): _figure_commands = ('figimage', 'figtext:text', 'gca', 'gci:_gci', 'ginput', 'subplots_adjust', 'suptitle', 'tight_layout', 'waitforbuttonpress') _axes_commands = ('acorr', 'angle_spectrum', 'annotate', 'arrow', 'autoscale', 'axhline', 'axhspan', 'axis', 'axline', 'axvline', 'axvspan', 'bar', 'barbs', 'barh', 'bar_label', 'boxplot', 'broken_barh', 'clabel', 'cohere', 'contour', 'contourf', 'csd', 'ecdf', 'errorbar', 'eventplot', 'fill', 'fill_between', 'fill_betweenx', 'grid', 'hexbin', 'hist', 'stairs', 'hist2d', 'hlines', 'imshow', 'legend', 'locator_params', 'loglog', 'magnitude_spectrum', 'margins', 'minorticks_off', 'minorticks_on', 'pcolor', 'pcolormesh', 'phase_spectrum', 'pie', 'plot', 'plot_date', 'psd', 'quiver', 'quiverkey', 'scatter', 'semilogx', 'semilogy', 'specgram', 'spy', 'stackplot', 'stem', 'step', 'streamplot', 'table', 'text', 'tick_params', 'ticklabel_format', 'tricontour', 'tricontourf', 'tripcolor', 'triplot', 'violinplot', 'vlines', 'xcorr', 'sci:_sci', 'title:set_title', 'xlabel:set_xlabel', 'ylabel:set_ylabel', 'xscale:set_xscale', 'yscale:set_yscale') cmappable = {'contour': 'if __ret._A is not None: # type: ignore[attr-defined]\n sci(__ret)', 'contourf': 'if __ret._A is not None: # type: ignore[attr-defined]\n sci(__ret)', 'hexbin': 'sci(__ret)', 'scatter': 'sci(__ret)', 'pcolor': 'sci(__ret)', 'pcolormesh': 'sci(__ret)', 'hist2d': 'sci(__ret[-1])', 'imshow': 'sci(__ret)', 'spy': 'if isinstance(__ret, cm.ScalarMappable):\n sci(__ret)', 'quiver': 'sci(__ret)', 'specgram': 'sci(__ret[-1])', 'streamplot': 'sci(__ret.lines)', 'tricontour': 'if __ret._A is not None: # type: ignore[attr-defined]\n sci(__ret)', 'tricontourf': 'if __ret._A is not None: # type: ignore[attr-defined]\n sci(__ret)', 'tripcolor': 'sci(__ret)'} for spec in _figure_commands: if ':' in spec: (name, called_name) = spec.split(':') else: name = called_name = spec yield generate_function(name, f'Figure.{called_name}', FIGURE_METHOD_TEMPLATE) for spec in _axes_commands: if ':' in spec: (name, called_name) = spec.split(':') else: name = called_name = spec template = AXES_CMAPPABLE_METHOD_TEMPLATE if name in cmappable else AXES_METHOD_TEMPLATE yield generate_function(name, f'Axes.{called_name}', template, sci_command=cmappable.get(name)) cmaps = ('autumn', 'bone', 'cool', 'copper', 'flag', 'gray', 'hot', 'hsv', 'jet', 'pink', 'prism', 'spring', 'summer', 'winter', 'magma', 'inferno', 'plasma', 'viridis', 'nipy_spectral') for name in cmaps: yield AUTOGEN_MSG yield CMAP_TEMPLATE.format(name=name) def build_pyplot(pyplot_path): pyplot_orig = pyplot_path.read_text().splitlines(keepends=True) try: pyplot_orig = pyplot_orig[:pyplot_orig.index(PYPLOT_MAGIC_HEADER) + 1] except IndexError as err: raise ValueError('The pyplot.py file *must* have the exact line: %s' % PYPLOT_MAGIC_HEADER) from err with pyplot_path.open('w') as pyplot: pyplot.writelines(pyplot_orig) pyplot.writelines(boilerplate_gen()) subprocess.run([sys.executable, '-m', 'black', '--line-length=88', pyplot_path], check=True) def get_ast_tree(cls): path = Path(inspect.getfile(cls)) stubpath = path.with_suffix('.pyi') path = stubpath if stubpath.exists() else path tree = ast.parse(path.read_text()) for item in tree.body: if isinstance(item, ast.ClassDef) and item.name == cls.__name__: return item raise ValueError(f'Cannot find {cls.__name__} in ast') @functools.lru_cache def get_ast_mro_trees(cls): return [get_ast_tree(c) for c in cls.__mro__ if c.__module__ != 'builtins'] def get_matching_signature(method, trees): sig = inspect.signature(method) for tree in trees: for item in tree.body: if not isinstance(item, ast.FunctionDef): continue if item.name == method.__name__: return update_sig_from_node(item, sig) return sig def update_sig_from_node(node, sig): params = dict(sig.parameters) args = node.args allargs = (*args.posonlyargs, *args.args, args.vararg, *args.kwonlyargs, args.kwarg) for param in allargs: if param is None: continue if param.annotation is None: continue annotation = direct_repr(ast.unparse(param.annotation)) params[param.arg] = params[param.arg].replace(annotation=annotation) if node.returns is not None: return inspect.Signature(params.values(), return_annotation=direct_repr(ast.unparse(node.returns))) else: return inspect.Signature(params.values()) if __name__ == '__main__': if len(sys.argv) > 1: pyplot_path = Path(sys.argv[1]) else: pyplot_path = Path(__file__).parent / '../lib/matplotlib/pyplot.py' build_pyplot(pyplot_path) # File: matplotlib-main/tools/cache_zenodo_svg.py import urllib.request from io import BytesIO import os from pathlib import Path def download_or_cache(url, version): cache_dir = _get_xdg_cache_dir() if cache_dir is not None: try: data = (cache_dir / version).read_bytes() except OSError: pass else: return BytesIO(data) with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': ''})) as req: data = req.read() if cache_dir is not None: try: cache_dir.mkdir(parents=True, exist_ok=True) with open(cache_dir / version, 'xb') as fout: fout.write(data) except OSError: pass return BytesIO(data) def _get_xdg_cache_dir(): cache_dir = os.environ.get('XDG_CACHE_HOME') if not cache_dir: cache_dir = os.path.expanduser('~/.cache') if cache_dir.startswith('~/'): return None return Path(cache_dir, 'matplotlib') if __name__ == '__main__': data = {'v3.9.2': '13308876', 'v3.9.1': '12652732', 'v3.9.0': '11201097', 'v3.8.4': '10916799', 'v3.8.3': '10661079', 'v3.8.2': '10150955', 'v3.8.1': '10059757', 'v3.8.0': '8347255', 'v3.7.3': '8336761', 'v3.7.2': '8118151', 'v3.7.1': '7697899', 'v3.7.0': '7637593', 'v3.6.3': '7527665', 'v3.6.2': '7275322', 'v3.6.1': '7162185', 'v3.6.0': '7084615', 'v3.5.3': '6982547', 'v3.5.2': '6513224', 'v3.5.1': '5773480', 'v3.5.0': '5706396', 'v3.4.3': '5194481', 'v3.4.2': '4743323', 'v3.4.1': '4649959', 'v3.4.0': '4638398', 'v3.3.4': '4475376', 'v3.3.3': '4268928', 'v3.3.2': '4030140', 'v3.3.1': '3984190', 'v3.3.0': '3948793', 'v3.2.2': '3898017', 'v3.2.1': '3714460', 'v3.2.0': '3695547', 'v3.1.3': '3633844', 'v3.1.2': '3563226', 'v3.1.1': '3264781', 'v3.1.0': '2893252', 'v3.0.3': '2577644', 'v3.0.2': '1482099', 'v3.0.1': '1482098', 'v2.2.5': '3633833', 'v3.0.0': '1420605', 'v2.2.4': '2669103', 'v2.2.3': '1343133', 'v2.2.2': '1202077', 'v2.2.1': '1202050', 'v2.2.0': '1189358', 'v2.1.2': '1154287', 'v2.1.1': '1098480', 'v2.1.0': '1004650', 'v2.0.2': '573577', 'v2.0.1': '570311', 'v2.0.0': '248351', 'v1.5.3': '61948', 'v1.5.2': '56926', 'v1.5.1': '44579', 'v1.5.0': '32914', 'v1.4.3': '15423', 'v1.4.2': '12400', 'v1.4.1': '12287', 'v1.4.0': '11451'} doc_dir = Path(__file__).parent.parent.absolute() / 'doc' target_dir = doc_dir / '_static/zenodo_cache' citing = doc_dir / 'project/citing.rst' target_dir.mkdir(exist_ok=True, parents=True) header = [] footer = [] with open(citing) as fin: target = header for ln in fin: if target is not None: target.append(ln.rstrip()) if ln.strip() == '.. START OF AUTOGENERATED': target.extend(['', '']) target = None if ln.strip() == '.. END OF AUTOGENERATED': target = footer target.append(ln.rstrip()) with open(citing, 'w') as fout: fout.write('\n'.join(header)) for (version, doi) in data.items(): svg_path = target_dir / f'{doi}.svg' if not svg_path.exists(): url = f'https://zenodo.org/badge/doi/10.5281/zenodo.{doi}.svg' payload = download_or_cache(url, f'{doi}.svg') with open(svg_path, 'xb') as svgout: svgout.write(payload.read()) fout.write(f'\n{version}\n .. image:: ../_static/zenodo_cache/{doi}.svg\n :target: https://doi.org/10.5281/zenodo.{doi}') fout.write('\n\n') fout.write('\n'.join(footer)) fout.write('\n') # File: matplotlib-main/tools/check_typehints.py """""" import ast import pathlib import sys MISSING_STUB = 1 MISSING_IMPL = 2 POS_ARGS = 4 ARGS = 8 VARARG = 16 KWARGS = 32 VARKWARG = 64 def check_file(path, ignore=0): stubpath = path.with_suffix('.pyi') ret = 0 if not stubpath.exists(): return (0, 0) tree = ast.parse(path.read_text()) stubtree = ast.parse(stubpath.read_text()) return check_namespace(tree, stubtree, path, ignore) def check_namespace(tree, stubtree, path, ignore=0): ret = 0 count = 0 tree_items = set((i.name for i in tree.body if hasattr(i, 'name') and (not i.name.startswith('_') or i.name.endswith('__')))) stubtree_items = set((i.name for i in stubtree.body if hasattr(i, 'name') and (not i.name.startswith('_') or i.name.endswith('__')))) for item in tree.body: if isinstance(item, ast.Assign): tree_items |= set((i.id for i in item.targets if hasattr(i, 'id') and (not i.id.startswith('_') or i.id.endswith('__')))) for target in item.targets: if isinstance(target, ast.Tuple): tree_items |= set((i.id for i in target.elts)) elif isinstance(item, ast.AnnAssign): tree_items |= {item.target.id} for item in stubtree.body: if isinstance(item, ast.Assign): stubtree_items |= set((i.id for i in item.targets if hasattr(i, 'id') and (not i.id.startswith('_') or i.id.endswith('__')))) for target in item.targets: if isinstance(target, ast.Tuple): stubtree_items |= set((i.id for i in target.elts)) elif isinstance(item, ast.AnnAssign): stubtree_items |= {item.target.id} try: all_ = ast.literal_eval(ast.unparse(get_subtree(tree, '__all__').value)) except ValueError: all_ = [] if all_: missing = tree_items - stubtree_items & set(all_) else: missing = tree_items - stubtree_items deprecated = set() for item_name in missing: item = get_subtree(tree, item_name) if hasattr(item, 'decorator_list'): if 'deprecated' in [i.func.attr for i in item.decorator_list if hasattr(i, 'func') and hasattr(i.func, 'attr')]: deprecated |= {item_name} if missing - deprecated and ~ignore & MISSING_STUB: print(f'{path}: {missing - deprecated} missing from stubs') ret |= MISSING_STUB count += 1 non_class_or_func = set() for item_name in stubtree_items - tree_items: try: get_subtree(tree, item_name) except ValueError: pass else: non_class_or_func |= {item_name} missing_implementation = stubtree_items - tree_items - non_class_or_func if missing_implementation and ~ignore & MISSING_IMPL: print(f'{path}: {missing_implementation} in stubs and not source') ret |= MISSING_IMPL count += 1 for item_name in tree_items & stubtree_items: item = get_subtree(tree, item_name) stubitem = get_subtree(stubtree, item_name) if isinstance(item, ast.FunctionDef) and isinstance(stubitem, ast.FunctionDef): (err, c) = check_function(item, stubitem, f'{path}::{item_name}', ignore) ret |= err count += c if isinstance(item, ast.ClassDef): (err, c) = check_namespace(item, stubitem, f'{path}::{item_name}', ignore | MISSING_STUB | MISSING_IMPL) ret |= err count += c return (ret, count) def check_function(item, stubitem, path, ignore): ret = 0 count = 0 overloaded = 'overload' in [i.id for i in stubitem.decorator_list if hasattr(i, 'id')] if overloaded: return (0, 0) item_posargs = [a.arg for a in item.args.posonlyargs] stubitem_posargs = [a.arg for a in stubitem.args.posonlyargs] if item_posargs != stubitem_posargs and ~ignore & POS_ARGS: print(f'{path} {item.name} posargs differ: {item_posargs} vs {stubitem_posargs}') ret |= POS_ARGS count += 1 item_args = [a.arg for a in item.args.args] stubitem_args = [a.arg for a in stubitem.args.args] if item_args != stubitem_args and ~ignore & ARGS: print(f'{path} args differ for {item.name}: {item_args} vs {stubitem_args}') ret |= ARGS count += 1 item_vararg = item.args.vararg stubitem_vararg = stubitem.args.vararg if ~ignore & VARARG: if (item_vararg is None) ^ (stubitem_vararg is None): if item_vararg: print(f'{path} {item.name} vararg differ: {item_vararg.arg} vs {stubitem_vararg}') else: print(f'{path} {item.name} vararg differ: {item_vararg} vs {stubitem_vararg.arg}') ret |= VARARG count += 1 elif item_vararg is None: pass elif item_vararg.arg != stubitem_vararg.arg: print(f'{path} {item.name} vararg differ: {item_vararg.arg} vs {stubitem_vararg.arg}') ret |= VARARG count += 1 item_kwonlyargs = [a.arg for a in item.args.kwonlyargs] stubitem_kwonlyargs = [a.arg for a in stubitem.args.kwonlyargs] if item_kwonlyargs != stubitem_kwonlyargs and ~ignore & KWARGS: print(f'{path} {item.name} kwonlyargs differ: {item_kwonlyargs} vs {stubitem_kwonlyargs}') ret |= KWARGS count += 1 item_kwarg = item.args.kwarg stubitem_kwarg = stubitem.args.kwarg if ~ignore & VARKWARG: if (item_kwarg is None) ^ (stubitem_kwarg is None): if item_kwarg: print(f'{path} {item.name} varkwarg differ: {item_kwarg.arg} vs {stubitem_kwarg}') else: print(f'{path} {item.name} varkwarg differ: {item_kwarg} vs {stubitem_kwarg.arg}') ret |= VARKWARG count += 1 elif item_kwarg is None: pass elif item_kwarg.arg != stubitem_kwarg.arg: print(f'{path} {item.name} varkwarg differ: {item_kwarg.arg} vs {stubitem_kwarg.arg}') ret |= VARKWARG count += 1 return (ret, count) def get_subtree(tree, name): for item in tree.body: if isinstance(item, ast.Assign): if name in [i.id for i in item.targets if hasattr(i, 'id')]: return item for target in item.targets: if isinstance(target, ast.Tuple): if name in [i.id for i in target.elts]: return item if isinstance(item, ast.AnnAssign): if name == item.target.id: return item if not hasattr(item, 'name'): continue if item.name == name: return item raise ValueError(f'no such item {name} in tree') if __name__ == '__main__': out = 0 count = 0 basedir = pathlib.Path('lib/matplotlib') per_file_ignore = {basedir / '__init__.py': MISSING_IMPL, basedir / 'ticker.py': VARKWARG, basedir / 'layout_engine.py': VARKWARG} for f in basedir.rglob('**/*.py'): (err, c) = check_file(f, ignore=0 | per_file_ignore.get(f, 0)) out |= err count += c print('\n') print(f'{count} total errors found') sys.exit(out) # File: matplotlib-main/tools/embed_js.py """""" from collections import namedtuple from pathlib import Path import re import shutil import subprocess import sys Package = namedtuple('Package', ['name', 'source', 'license']) JAVASCRIPT_PACKAGES = [Package('@jsxtools/resize-observer', 'index.js', 'LICENSE.md')] MPLJS_MAGIC_HEADER = '///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////\n' def safe_name(name): return '_'.join(re.split('[@/-]', name)).upper() def prep_package(web_backend_path, pkg): source = web_backend_path / 'node_modules' / pkg.name / pkg.source license = web_backend_path / 'node_modules' / pkg.name / pkg.license if not source.exists(): try: subprocess.run(['npm', 'install', '--no-save', pkg.name], cwd=web_backend_path) except FileNotFoundError as err: raise ValueError(f'npm must be installed to fetch {pkg.name}') from err if not source.exists(): raise ValueError(f'{pkg.name} package is missing source in {pkg.source}') elif not license.exists(): raise ValueError(f'{pkg.name} package is missing license in {pkg.license}') return (source, license) def gen_embedded_lines(pkg, source): name = safe_name(pkg.name) print('Embedding', source, 'as', name) yield '// prettier-ignore\n' for line in source.read_text().splitlines(): yield (line.replace('module.exports=function', f'var {name}=function') + ' // eslint-disable-line\n') def build_mpljs(web_backend_path, license_path): mpljs_path = web_backend_path / 'js/mpl.js' mpljs_orig = mpljs_path.read_text().splitlines(keepends=True) try: mpljs_orig = mpljs_orig[:mpljs_orig.index(MPLJS_MAGIC_HEADER) + 1] except IndexError as err: raise ValueError(f'The mpl.js file *must* have the exact line: {MPLJS_MAGIC_HEADER}') from err with mpljs_path.open('w') as mpljs: mpljs.writelines(mpljs_orig) for pkg in JAVASCRIPT_PACKAGES: (source, license) = prep_package(web_backend_path, pkg) mpljs.writelines(gen_embedded_lines(pkg, source)) shutil.copy(license, license_path / f'LICENSE{safe_name(pkg.name)}') if __name__ == '__main__': if len(sys.argv) > 1: web_backend_path = Path(sys.argv[1]) else: web_backend_path = Path(__file__).parent.parent / 'lib/matplotlib/backends/web_backend' if len(sys.argv) > 2: license_path = Path(sys.argv[2]) else: license_path = Path(__file__).parent.parent / 'LICENSE' build_mpljs(web_backend_path, license_path) # File: matplotlib-main/tools/generate_matplotlibrc.py """""" import sys from pathlib import Path if len(sys.argv) != 4: raise SystemExit('usage: {sys.argv[0]} ') input = Path(sys.argv[1]) output = Path(sys.argv[2]) backend = sys.argv[3] template_lines = input.read_text(encoding='utf-8').splitlines(True) (backend_line_idx,) = (idx for (idx, line) in enumerate(template_lines) if '#backend:' in line) template_lines[backend_line_idx] = f'#backend: {backend}\n' if backend not in ['', 'auto'] else '##backend: Agg\n' output.write_text(''.join(template_lines), encoding='utf-8') # File: matplotlib-main/tools/gh_api.py """""" import getpass import json import os import re import sys import requests try: import requests_cache except ImportError: print('no cache', file=sys.stderr) else: requests_cache.install_cache('gh_api', expire_after=3600) fake_username = 'ipython_tools' class Obj(dict): def __getattr__(self, name): try: return self[name] except KeyError as err: raise AttributeError(name) from err def __setattr__(self, name, val): self[name] = val token = None def get_auth_token(): global token if token is not None: return token try: with open(os.path.join(os.path.expanduser('~'), '.ghoauth')) as f: (token,) = f return token except Exception: pass import keyring token = keyring.get_password('github', fake_username) if token is not None: return token print('Please enter your github username and password. These are not stored, only used to get an oAuth token. You can revoke this at any time on GitHub.') user = input('Username: ') pw = getpass.getpass('Password: ') auth_request = {'scopes': ['public_repo', 'gist'], 'note': 'IPython tools', 'note_url': 'https://github.com/ipython/ipython/tree/master/tools'} response = requests.post('https://api.github.com/authorizations', auth=(user, pw), data=json.dumps(auth_request)) response.raise_for_status() token = json.loads(response.text)['token'] keyring.set_password('github', fake_username, token) return token def make_auth_header(): return {'Authorization': 'token ' + get_auth_token().replace('\n', '')} def post_issue_comment(project, num, body): url = f'https://api.github.com/repos/{project}/issues/{num}/comments' payload = json.dumps({'body': body}) requests.post(url, data=payload, headers=make_auth_header()) def post_gist(content, description='', filename='file', auth=False): post_data = json.dumps({'description': description, 'public': True, 'files': {filename: {'content': content}}}).encode('utf-8') headers = make_auth_header() if auth else {} response = requests.post('https://api.github.com/gists', data=post_data, headers=headers) response.raise_for_status() response_data = json.loads(response.text) return response_data['html_url'] def get_pull_request(project, num, auth=False): url = f'https://api.github.com/repos/{project}/pulls/{num}' if auth: header = make_auth_header() else: header = None print('fetching %s' % url, file=sys.stderr) response = requests.get(url, headers=header) response.raise_for_status() return json.loads(response.text, object_hook=Obj) def get_pull_request_files(project, num, auth=False): url = f'https://api.github.com/repos/{project}/pulls/{num}/files' if auth: header = make_auth_header() else: header = None return get_paged_request(url, headers=header) element_pat = re.compile('<(.+?)>') rel_pat = re.compile('rel=[\\\'"](\\w+)[\\\'"]') def get_paged_request(url, headers=None, **params): results = [] params.setdefault('per_page', 100) while True: if '?' in url: params = None print(f'fetching {url}', file=sys.stderr) else: print(f'fetching {url} with {params}', file=sys.stderr) response = requests.get(url, headers=headers, params=params) response.raise_for_status() results.extend(response.json()) if 'next' in response.links: url = response.links['next']['url'] else: break return results def get_pulls_list(project, auth=False, **params): params.setdefault('state', 'closed') url = f'https://api.github.com/repos/{project}/pulls' if auth: headers = make_auth_header() else: headers = None pages = get_paged_request(url, headers=headers, **params) return pages def get_issues_list(project, auth=False, **params): params.setdefault('state', 'closed') url = f'https://api.github.com/repos/{project}/issues' if auth: headers = make_auth_header() else: headers = None pages = get_paged_request(url, headers=headers, **params) return pages def get_milestones(project, auth=False, **params): params.setdefault('state', 'all') url = f'https://api.github.com/repos/{project}/milestones' if auth: headers = make_auth_header() else: headers = None milestones = get_paged_request(url, headers=headers, **params) return milestones def get_milestone_id(project, milestone, auth=False, **params): milestones = get_milestones(project, auth=auth, **params) for mstone in milestones: if mstone['title'] == milestone: return mstone['number'] raise ValueError('milestone %s not found' % milestone) def is_pull_request(issue): return bool(issue.get('pull_request', {}).get('html_url', None)) def get_authors(pr): print('getting authors for #%i' % pr['number'], file=sys.stderr) h = make_auth_header() r = requests.get(pr['commits_url'], headers=h) r.raise_for_status() commits = r.json() authors = [] for commit in commits: author = commit['commit']['author'] authors.append(f"{author['name']} <{author['email']}>") return authors def iter_fields(fields): fields = fields.copy() for key in ['key', 'acl', 'Filename', 'success_action_status', 'AWSAccessKeyId', 'Policy', 'Signature', 'Content-Type', 'file']: yield (key, fields.pop(key)) yield from fields.items() def encode_multipart_formdata(fields, boundary=None): from io import BytesIO from requests.packages.urllib3.filepost import choose_boundary, writer, b, get_content_type body = BytesIO() if boundary is None: boundary = choose_boundary() for (fieldname, value) in iter_fields(fields): body.write(b('--%s\r\n' % boundary)) if isinstance(value, tuple): (filename, data) = value writer(body).write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (fieldname, filename)) body.write(b('Content-Type: %s\r\n\r\n' % get_content_type(filename))) else: data = value writer(body).write('Content-Disposition: form-data; name="%s"\r\n' % fieldname) body.write(b'Content-Type: text/plain\r\n\r\n') if isinstance(data, int): data = str(data) if isinstance(data, str): writer(body).write(data) else: body.write(data) body.write(b'\r\n') body.write(b('--%s--\r\n' % boundary)) content_type = b('multipart/form-data; boundary=%s' % boundary) return (body.getvalue(), content_type) def post_download(project, filename, name=None, description=''): if name is None: name = os.path.basename(filename) with open(filename, 'rb') as f: filedata = f.read() url = f'https://api.github.com/repos/{project}/downloads' payload = json.dumps(dict(name=name, size=len(filedata), description=description)) response = requests.post(url, data=payload, headers=make_auth_header()) response.raise_for_status() reply = json.loads(response.content) s3_url = reply['s3_url'] fields = dict(key=reply['path'], acl=reply['acl'], success_action_status=201, Filename=reply['name'], AWSAccessKeyId=reply['accesskeyid'], Policy=reply['policy'], Signature=reply['signature'], file=(reply['name'], filedata)) fields['Content-Type'] = reply['mime_type'] (data, content_type) = encode_multipart_formdata(fields) s3r = requests.post(s3_url, data=data, headers={'Content-Type': content_type}) return s3r # File: matplotlib-main/tools/github_stats.py """""" import sys from argparse import ArgumentParser from datetime import datetime, timedelta from subprocess import check_output from gh_api import get_paged_request, make_auth_header, get_pull_request, is_pull_request, get_milestone_id, get_issues_list, get_authors ISO8601 = '%Y-%m-%dT%H:%M:%SZ' PER_PAGE = 100 REPORT_TEMPLATE = '.. _github-stats:\n\n{title}\n{title_underline}\n\nGitHub statistics for {since_day} (tag: {tag}) - {today}\n\nThese lists are automatically generated, and may be incomplete or contain duplicates.\n\nWe closed {n_issues} issues and merged {n_pulls} pull requests.\n{milestone}\nThe following {nauthors} authors contributed {ncommits} commits.\n\n{unique_authors}\n{links}\n\nPrevious GitHub statistics\n--------------------------\n\n.. toctree::\n :maxdepth: 1\n :glob:\n :reversed:\n\n prev_whats_new/github_stats_*' MILESTONE_TEMPLATE = 'The full list can be seen `on GitHub `__\n' LINKS_TEMPLATE = '\nGitHub issues and pull requests:\n\nPull Requests ({n_pulls}):\n\n{pull_request_report}\n\nIssues ({n_issues}):\n\n{issue_report}\n' def round_hour(dt): return dt.replace(minute=0, second=0, microsecond=0) def _parse_datetime(s): return datetime.strptime(s, ISO8601) if s else datetime.fromtimestamp(0) def issues2dict(issues): return {i['number']: i for i in issues} def split_pulls(all_issues, project='matplotlib/matplotlib'): pulls = [] issues = [] for i in all_issues: if is_pull_request(i): pull = get_pull_request(project, i['number'], auth=True) pulls.append(pull) else: issues.append(i) return (issues, pulls) def issues_closed_since(period=timedelta(days=365), project='matplotlib/matplotlib', pulls=False): which = 'pulls' if pulls else 'issues' if isinstance(period, timedelta): since = round_hour(datetime.utcnow() - period) else: since = period url = f'https://api.github.com/repos/{project}/{which}?state=closed&sort=updated&since={since.strftime(ISO8601)}&per_page={PER_PAGE}' allclosed = get_paged_request(url, headers=make_auth_header()) filtered = (i for i in allclosed if _parse_datetime(i['closed_at']) > since) if pulls: filtered = (i for i in filtered if _parse_datetime(i['merged_at']) > since) filtered = (i for i in filtered if i['base']['ref'] == 'main') else: filtered = (i for i in filtered if not is_pull_request(i)) return list(filtered) def sorted_by_field(issues, field='closed_at', reverse=False): return sorted(issues, key=lambda i: i[field], reverse=reverse) def report(issues, show_urls=False): lines = [] if show_urls: for i in issues: role = 'ghpull' if 'merged_at' in i else 'ghissue' number = i['number'] title = i['title'].replace('`', '``').strip() lines.append(f'* :{role}:`{number}`: {title}') else: for i in issues: number = i['number'] title = i['title'].replace('`', '``').strip() lines.append('* {number}: {title}') return '\n'.join(lines) if __name__ == '__main__': show_urls = True parser = ArgumentParser() parser.add_argument('--since-tag', type=str, help='The git tag to use for the starting point (typically the last macro release).') parser.add_argument('--milestone', type=str, help='The GitHub milestone to use for filtering issues [optional].') parser.add_argument('--days', type=int, help='The number of days of data to summarize (use this or --since-tag).') parser.add_argument('--project', type=str, default='matplotlib/matplotlib', help='The project to summarize.') parser.add_argument('--links', action='store_true', default=False, help='Include links to all closed Issues and PRs in the output.') opts = parser.parse_args() tag = opts.since_tag if opts.days: since = datetime.utcnow() - timedelta(days=opts.days) else: if not tag: tag = check_output(['git', 'describe', '--abbrev=0'], encoding='utf8').strip() cmd = ['git', 'log', '-1', '--format=%ai', tag] (tagday, tz) = check_output(cmd, encoding='utf8').strip().rsplit(' ', 1) since = datetime.strptime(tagday, '%Y-%m-%d %H:%M:%S') h = int(tz[1:3]) m = int(tz[3:]) td = timedelta(hours=h, minutes=m) if tz[0] == '-': since += td else: since -= td since = round_hour(since) milestone = opts.milestone project = opts.project print(f'fetching GitHub stats since {since} (tag: {tag}, milestone: {milestone})', file=sys.stderr) if milestone: milestone_id = get_milestone_id(project=project, milestone=milestone, auth=True) issues_and_pulls = get_issues_list(project=project, milestone=milestone_id, state='closed', auth=True) (issues, pulls) = split_pulls(issues_and_pulls, project=project) else: issues = issues_closed_since(since, project=project, pulls=False) pulls = issues_closed_since(since, project=project, pulls=True) issues = sorted_by_field(issues, reverse=True) pulls = sorted_by_field(pulls, reverse=True) (n_issues, n_pulls) = map(len, (issues, pulls)) n_total = n_issues + n_pulls since_day = since.strftime('%Y/%m/%d') today = datetime.today() title = f"GitHub statistics for {milestone.lstrip('v')} {today.strftime('(%b %d, %Y)')}" ncommits = 0 all_authors = [] if tag: since_tag = f'{tag}..' cmd = ['git', 'log', '--oneline', since_tag] ncommits += len(check_output(cmd).splitlines()) author_cmd = ['git', 'log', '--use-mailmap', '--format=* %aN', since_tag] all_authors.extend(check_output(author_cmd, encoding='utf-8', errors='replace').splitlines()) pr_authors = [] for pr in pulls: pr_authors.extend(get_authors(pr)) ncommits = len(pr_authors) + ncommits - len(pulls) author_cmd = ['git', 'check-mailmap'] + pr_authors with_email = check_output(author_cmd, encoding='utf-8', errors='replace').splitlines() all_authors.extend(['* ' + a.split(' <')[0] for a in with_email]) unique_authors = sorted(set(all_authors), key=lambda s: s.lower()) if milestone: milestone_str = MILESTONE_TEMPLATE.format(project=project, milestone_id=milestone_id) else: milestone_str = '' if opts.links: links = LINKS_TEMPLATE.format(n_pulls=n_pulls, pull_request_report=report(pulls, show_urls), n_issues=n_issues, issue_report=report(issues, show_urls)) else: links = '' print(REPORT_TEMPLATE.format(title=title, title_underline='=' * len(title), since_day=since_day, tag=tag, today=today.strftime('%Y/%m/%d'), n_issues=n_issues, n_pulls=n_pulls, milestone=milestone_str, nauthors=len(unique_authors), ncommits=ncommits, unique_authors='\n'.join(unique_authors), links=links)) # File: matplotlib-main/tools/make_icons.py """""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from io import BytesIO from pathlib import Path import tarfile import urllib.request import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np plt.rcdefaults() plt.rcParams['svg.fonttype'] = 'path' plt.rcParams['pdf.fonttype'] = 3 plt.rcParams['pdf.compression'] = 9 def get_fontawesome(): cached_path = Path(mpl.get_cachedir(), 'FontAwesome.otf') if not cached_path.exists(): with urllib.request.urlopen('https://github.com/FortAwesome/Font-Awesome/archive/v4.7.0.tar.gz') as req, tarfile.open(fileobj=BytesIO(req.read()), mode='r:gz') as tf: cached_path.write_bytes(tf.extractfile(tf.getmember('Font-Awesome-4.7.0/fonts/FontAwesome.otf')).read()) return cached_path def save_icon(fig, dest_dir, name, add_black_fg_color): if add_black_fg_color: svg_bytes_io = BytesIO() fig.savefig(svg_bytes_io, format='svg') svg = svg_bytes_io.getvalue() (before, sep, after) = svg.rpartition(b'\nz\n"') svg = before + sep + b' style="fill:black;"' + after (dest_dir / (name + '.svg')).write_bytes(svg) else: fig.savefig(dest_dir / (name + '.svg')) fig.savefig(dest_dir / (name + '.pdf')) for (dpi, suffix) in [(24, ''), (48, '_large')]: fig.savefig(dest_dir / (name + suffix + '.png'), dpi=dpi) def make_icon(font_path, ccode): fig = plt.figure(figsize=(1, 1)) fig.patch.set_alpha(0.0) fig.text(0.5, 0.48, chr(ccode), ha='center', va='center', font=font_path, fontsize=68) return fig def make_matplotlib_icon(): fig = plt.figure(figsize=(1, 1)) fig.patch.set_alpha(0.0) ax = fig.add_axes([0.025, 0.025, 0.95, 0.95], projection='polar') ax.set_axisbelow(True) N = 7 arc = 2 * np.pi theta = np.arange(0, arc, arc / N) radii = 10 * np.array([0.2, 0.6, 0.8, 0.7, 0.4, 0.5, 0.8]) width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3]) bars = ax.bar(theta, radii, width=width, bottom=0.0, linewidth=1, edgecolor='k') for (r, bar) in zip(radii, bars): bar.set_facecolor(mpl.cm.jet(r / 10)) ax.tick_params(labelleft=False, labelright=False, labelbottom=False, labeltop=False) ax.grid(lw=0.0) ax.set_yticks(np.arange(1, 9, 2)) ax.set_rmax(9) return fig icon_defs = [('home', 61461), ('back', 61536), ('forward', 61537), ('zoom_to_rect', 61442), ('move', 61511), ('filesave', 61639), ('subplots', 61918), ('qt4_editor_options', 61953), ('help', 61736)] def make_icons(): parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('-d', '--dest-dir', type=Path, default=Path(__file__).parent / '../lib/matplotlib/mpl-data/images', help='Directory where to store the images.') args = parser.parse_args() font_path = get_fontawesome() for (name, ccode) in icon_defs: fig = make_icon(font_path, ccode) save_icon(fig, args.dest_dir, name, True) fig = make_matplotlib_icon() save_icon(fig, args.dest_dir, 'matplotlib', False) if __name__ == '__main__': make_icons() # File: matplotlib-main/tools/memleak.py import gc from io import BytesIO import tracemalloc try: import psutil except ImportError as err: raise ImportError('This script requires psutil') from err import numpy as np def run_memleak_test(bench, iterations, report): tracemalloc.start() starti = min(50, iterations // 2) endi = iterations malloc_arr = np.empty(endi, dtype=np.int64) rss_arr = np.empty(endi, dtype=np.int64) rss_peaks = np.empty(endi, dtype=np.int64) nobjs_arr = np.empty(endi, dtype=np.int64) garbage_arr = np.empty(endi, dtype=np.int64) open_files_arr = np.empty(endi, dtype=np.int64) rss_peak = 0 p = psutil.Process() for i in range(endi): bench() gc.collect() rss = p.memory_info().rss (malloc, peak) = tracemalloc.get_traced_memory() nobjs = len(gc.get_objects()) garbage = len(gc.garbage) open_files = len(p.open_files()) print(f'{i: 4d}: pymalloc {malloc: 10d}, rss {rss: 10d}, nobjs {nobjs: 10d}, garbage {garbage: 4d}, files: {open_files: 4d}') if i == starti: print(f"{' warmup done ':-^86s}") malloc_arr[i] = malloc rss_arr[i] = rss if rss > rss_peak: rss_peak = rss rss_peaks[i] = rss_peak nobjs_arr[i] = nobjs garbage_arr[i] = garbage open_files_arr[i] = open_files print('Average memory consumed per loop: {:1.4f} bytes\n'.format(np.sum(rss_peaks[starti + 1:] - rss_peaks[starti:-1]) / (endi - starti))) from matplotlib import pyplot as plt from matplotlib.ticker import EngFormatter bytes_formatter = EngFormatter(unit='B') (fig, (ax1, ax2, ax3)) = plt.subplots(3) for ax in (ax1, ax2, ax3): ax.axvline(starti, linestyle='--', color='k') ax1b = ax1.twinx() ax1b.yaxis.set_major_formatter(bytes_formatter) ax1.plot(malloc_arr, 'C0') ax1b.plot(rss_arr, 'C1', label='rss') ax1b.plot(rss_peaks, 'C1', linestyle='--', label='rss max') ax1.set_ylabel('pymalloc', color='C0') ax1b.set_ylabel('rss', color='C1') ax1b.legend() ax2b = ax2.twinx() ax2.plot(nobjs_arr, 'C0') ax2b.plot(garbage_arr, 'C1') ax2.set_ylabel('total objects', color='C0') ax2b.set_ylabel('garbage objects', color='C1') ax3.plot(open_files_arr) ax3.set_ylabel('open file handles') if not report.endswith('.pdf'): report = report + '.pdf' fig.tight_layout() fig.savefig(report, format='pdf') class MemleakTest: def __init__(self, empty): self.empty = empty def __call__(self): import matplotlib.pyplot as plt fig = plt.figure(1) if not self.empty: t1 = np.arange(0.0, 2.0, 0.01) y1 = np.sin(2 * np.pi * t1) y2 = np.random.rand(len(t1)) X = np.random.rand(50, 50) ax = fig.add_subplot(221) ax.plot(t1, y1, '-') ax.plot(t1, y2, 's') ax = fig.add_subplot(222) ax.imshow(X) ax = fig.add_subplot(223) ax.scatter(np.random.rand(50), np.random.rand(50), s=100 * np.random.rand(50), c=np.random.rand(50)) ax = fig.add_subplot(224) ax.pcolor(10 * np.random.rand(50, 50)) fig.savefig(BytesIO(), dpi=75) fig.canvas.flush_events() plt.close(1) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser('Run memory leak tests') parser.add_argument('backend', type=str, nargs=1, help='backend to test') parser.add_argument('iterations', type=int, nargs=1, help='number of iterations') parser.add_argument('report', type=str, nargs=1, help='filename to save report') parser.add_argument('--empty', action='store_true', help="Don't plot any content, just test creating and destroying figures") parser.add_argument('--interactive', action='store_true', help='Turn on interactive mode to actually open windows. Only works with some GUI backends.') args = parser.parse_args() import matplotlib matplotlib.use(args.backend[0]) if args.interactive: import matplotlib.pyplot as plt plt.ion() run_memleak_test(MemleakTest(args.empty), args.iterations[0], args.report[0]) # File: matplotlib-main/tools/run_examples.py """""" from argparse import ArgumentParser from contextlib import ExitStack import os from pathlib import Path import subprocess import sys from tempfile import TemporaryDirectory import time import tokenize _preamble = 'from matplotlib import pyplot as plt\n\ndef pseudo_show(block=True):\n for num in plt.get_fignums():\n plt.figure(num).savefig(f"{num}")\n\nplt.show = pseudo_show\n\n' class RunInfo: def __init__(self, backend, elapsed, failed): self.backend = backend self.elapsed = elapsed self.failed = failed def __str__(self): s = '' if self.backend: s += f'{self.backend}: ' s += f'{self.elapsed}ms' if self.failed: s += ' (failed!)' return s def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--backend', action='append', help='backend to test; can be passed multiple times; defaults to the default backend') parser.add_argument('--include-sgskip', action='store_true', help='do not filter out *_sgskip.py examples') parser.add_argument('--rundir', type=Path, help='directory from where the tests are run; defaults to a temporary directory') parser.add_argument('paths', nargs='*', type=Path, help='examples to run; defaults to all examples (except *_sgskip.py)') args = parser.parse_args() root = Path(__file__).resolve().parent.parent / 'examples' paths = args.paths if args.paths else sorted(root.glob('**/*.py')) if not args.include_sgskip: paths = [path for path in paths if not path.stem.endswith('sgskip')] relpaths = [path.resolve().relative_to(root) for path in paths] width = max((len(str(relpath)) for relpath in relpaths)) for relpath in relpaths: print(str(relpath).ljust(width + 1), end='', flush=True) runinfos = [] with ExitStack() as stack: if args.rundir: cwd = args.rundir / relpath.with_suffix('') cwd.mkdir(parents=True) else: cwd = stack.enter_context(TemporaryDirectory()) with tokenize.open(root / relpath) as src: Path(cwd, relpath.name).write_text(_preamble + src.read(), encoding='utf-8') for backend in args.backend or [None]: env = {**os.environ} if backend is not None: env['MPLBACKEND'] = backend start = time.perf_counter() proc = subprocess.run([sys.executable, relpath.name], cwd=cwd, env=env) elapsed = round(1000 * (time.perf_counter() - start)) runinfos.append(RunInfo(backend, elapsed, proc.returncode)) print('\t'.join(map(str, runinfos))) if __name__ == '__main__': main() # File: matplotlib-main/tools/subset.py import getopt import os import struct import subprocess import sys import fontforge def log_namelist(name, unicode): if name and isinstance(unicode, int): print(f'0x{unicode:04X}', fontforge.nameeFromUnicode(unicode), file=name) def select_with_refs(font, unicode, newfont, pe=None, name=None): newfont.selection.select(('more', 'unicode'), unicode) log_namelist(name, unicode) if pe: print(f'SelectMore({unicode})', file=pe) try: for ref in font[unicode].references: newfont.selection.select(('more',), ref[0]) log_namelist(name, ref[0]) if pe: print(f'SelectMore("{ref[0]}")', file=pe) except Exception: print(f'Resolving references on u+{unicode:04x} failed') def subset_font_raw(font_in, font_out, unicodes, opts): if '--namelist' in opts: name_fn = f'{font_out}.name' name = open(name_fn, 'w') else: name = None if '--script' in opts: pe_fn = '/tmp/script.pe' pe = open(pe_fn, 'w') else: pe = None font = fontforge.open(font_in) if pe: print(f'Open("{font_in}")', file=pe) extract_vert_to_script(font_in, pe) for i in unicodes: select_with_refs(font, i, font, pe, name) addl_glyphs = [] if '--nmr' in opts: addl_glyphs.append('nonmarkingreturn') if '--null' in opts: addl_glyphs.append('.null') if '--nd' in opts: addl_glyphs.append('.notdef') for glyph in addl_glyphs: font.selection.select(('more',), glyph) if name: print(f'0x{fontforge.unicodeFromName(glyph):0.4X}', glyph, file=name) if pe: print(f'SelectMore("{glyph}")', file=pe) flags = () if '--opentype-features' in opts: flags += ('opentype',) if '--simplify' in opts: font.simplify() font.round() flags += ('omit-instructions',) if '--strip_names' in opts: font.sfnt_names = () if '--new' in opts: font.copy() new = fontforge.font() new.encoding = font.encoding new.em = font.em new.layers['Fore'].is_quadratic = font.layers['Fore'].is_quadratic for i in unicodes: select_with_refs(font, i, new, pe, name) new.paste() font.selection.select('space') font.copy() new.selection.select('space') new.paste() new.sfnt_names = font.sfnt_names font = new else: font.selection.invert() print('SelectInvert()', file=pe) font.cut() print('Clear()', file=pe) if '--move-display' in opts: print('Moving display glyphs into Unicode ranges...') font.familyname += ' Display' font.fullname += ' Display' font.fontname += 'Display' font.appendSFNTName('English (US)', 'Family', font.familyname) font.appendSFNTName('English (US)', 16, font.familyname) font.appendSFNTName('English (US)', 17, 'Display') font.appendSFNTName('English (US)', 'Fullname', font.fullname) for glname in unicodes: font.selection.none() if isinstance(glname, str): if glname.endswith('.display'): font.selection.select(glname) font.copy() font.selection.none() newgl = glname.replace('.display', '') font.selection.select(newgl) font.paste() font.selection.select(glname) font.cut() if name: print('Writing NameList', end='') name.close() if pe: print(f'Generate("{font_out}")', file=pe) pe.close() subprocess.call(['fontforge', '-script', pe_fn]) else: font.generate(font_out, flags=flags) font.close() if '--roundtrip' in opts: font2 = fontforge.open(font_out) font2.generate(font_out, flags=flags) def subset_font(font_in, font_out, unicodes, opts): font_out_raw = font_out if not font_out_raw.endswith('.ttf'): font_out_raw += '.ttf' subset_font_raw(font_in, font_out_raw, unicodes, opts) if font_out != font_out_raw: os.rename(font_out_raw, font_out) def getsubset(subset, font_in): subsets = subset.split('+') quotes = [8211, 8212, 8216, 8217, 8218, 8220, 8221, 8222, 8226, 8249, 8250] latin = [*range(32, 127), *range(160, 256), 8364, 338, 339, 59, 183, 305, 710, 730, 732, 8308, 8725, 8260, 57599, 61437, 61440] result = quotes if 'menu' in subsets: font = fontforge.open(font_in) result = [*map(ord, font.familyname), 32] if 'latin' in subsets: result += latin if 'latin-ext' in subsets: result += [*range(256, 880), *range(7424, 7840), *range(7922, 7936), *range(8304, 8400), *range(11360, 11392), *range(42752, 43008)] if 'vietnamese' in subsets: result += [192, 193, 194, 195, 200, 201, 202, 204, 205, 210, 211, 212, 213, 217, 218, 221, 224, 225, 226, 227, 232, 233, 234, 236, 237, 242, 243, 244, 245, 249, 250, 253, 258, 259, 272, 273, 296, 297, 360, 361, 416, 417, 431, 432, 8363, *range(7840, 7930)] if 'greek' in subsets: result += [*range(880, 1024)] if 'greek-ext' in subsets: result += [*range(880, 1024), *range(7936, 8192)] if 'cyrillic' in subsets: result += [*range(1024, 1120), 1168, 1169, 1200, 1201, 8470] if 'cyrillic-ext' in subsets: result += [*range(1024, 1328), 8372, 8470, *range(11744, 11776), *range(42560, 42656)] if 'arabic' in subsets: result += [13, 32, 1569, 1575, 1581, 1583, 1585, 1587, 1589, 1591, 1593, 1603, 1604, 1605, 1607, 1608, 1609, 1600, 1646, 1647, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1780, 1781, 1782, 1726, 1746, 1705, 1711, 1722, 1642, 1567, 1548, 1563, 1643, 1644, 1645, 1611, 1613, 1614, 1615, 1612, 1616, 1617, 1618, 1619, 1620, 1621, 1648, 1622, 1557, 1670, 1571, 1573, 1570, 1649, 1576, 1662, 1578, 1579, 1657, 1577, 1580, 1582, 1584, 1672, 1586, 1681, 1688, 1588, 1590, 1592, 1594, 1601, 1602, 1606, 1749, 1728, 1572, 1610, 1740, 1747, 1574, 1730, 1729, 1731, 1776, 1777, 1778, 1779, 1785, 1783, 1784, 64611, 1650, 1651, 1653, 1654, 1655, 1656, 1658, 1659, 1660, 1661, 1663, 1664, 1665, 1666, 1667, 1668, 1669, 1671, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1682, 1683, 1684, 1685, 1686, 1687, 1689, 1690, 1691, 1692, 1693, 1694, 1695, 1696, 1697, 1698, 1699, 1701, 1702, 1703, 1704, 1706, 1707, 1708, 1709, 1710, 1712, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1723, 1724, 1725, 1727, 1732, 1733, 1741, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1759, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1770, 1771, 1773, 1787, 1788, 1789, 1790, 1536, 1537, 1538, 1539, 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1623, 1624, 1774, 1775, 1791, 1547, 1566, 1625, 1626, 1627, 1628, 1629, 1630, 1872, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1700, 1734, 1735, 1736, 1737, 1738, 1739, 1743, 1742, 1744, 1745, 1748, 1786, 1757, 1758, 1760, 1769, 1549, 64830, 64831, 9676, 1595, 1596, 1597, 1598, 1599, 1568, 1652, 1652, 1772] if 'dejavu-ext' in subsets: font = fontforge.open(font_in) for glyph in font.glyphs(): if glyph.glyphname.endswith('.display'): result.append(glyph.glyphname) return result class Sfnt: def __init__(self, data): (_, numTables, _, _, _) = struct.unpack('>IHHHH', data[:12]) self.tables = {} for i in range(numTables): (tag, _, offset, length) = struct.unpack('>4sIII', data[12 + 16 * i:28 + 16 * i]) self.tables[tag] = data[offset:offset + length] def hhea(self): r = {} d = self.tables['hhea'] (r['Ascender'], r['Descender'], r['LineGap']) = struct.unpack('>hhh', d[4:10]) return r def os2(self): r = {} d = self.tables['OS/2'] (r['fsSelection'],) = struct.unpack('>H', d[62:64]) (r['sTypoAscender'], r['sTypoDescender'], r['sTypoLineGap']) = struct.unpack('>hhh', d[68:74]) (r['usWinAscender'], r['usWinDescender']) = struct.unpack('>HH', d[74:78]) return r def set_os2(pe, name, val): print(f'SetOS2Value("{name}", {val:d})', file=pe) def set_os2_vert(pe, name, val): set_os2(pe, name + 'IsOffset', 0) set_os2(pe, name, val) def extract_vert_to_script(font_in, pe): with open(font_in, 'rb') as in_file: data = in_file.read() sfnt = Sfnt(data) hhea = sfnt.hhea() os2 = sfnt.os2() set_os2_vert(pe, 'WinAscent', os2['usWinAscender']) set_os2_vert(pe, 'WinDescent', os2['usWinDescender']) set_os2_vert(pe, 'TypoAscent', os2['sTypoAscender']) set_os2_vert(pe, 'TypoDescent', os2['sTypoDescender']) set_os2_vert(pe, 'HHeadAscent', hhea['Ascender']) set_os2_vert(pe, 'HHeadDescent', hhea['Descender']) def main(argv): (optlist, args) = getopt.gnu_getopt(argv, '', ['string=', 'strip_names', 'opentype-features', 'simplify', 'new', 'script', 'nmr', 'roundtrip', 'subset=', 'namelist', 'null', 'nd', 'move-display']) (font_in, font_out) = args opts = dict(optlist) if '--string' in opts: subset = map(ord, opts['--string']) else: subset = getsubset(opts.get('--subset', 'latin'), font_in) subset_font(font_in, font_out, subset, opts) if __name__ == '__main__': main(sys.argv[1:])