__init__.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. """
  2. An object-oriented plotting library.
  3. A procedural interface is provided by the companion pyplot module,
  4. which may be imported directly, e.g.::
  5. import matplotlib.pyplot as plt
  6. or using ipython::
  7. ipython
  8. at your terminal, followed by::
  9. In [1]: %matplotlib
  10. In [2]: import matplotlib.pyplot as plt
  11. at the ipython shell prompt.
  12. For the most part, direct use of the object-oriented library is encouraged when
  13. programming; pyplot is primarily for working interactively. The exceptions are
  14. the pyplot functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`,
  15. and `.pyplot.savefig`, which can greatly simplify scripting.
  16. Modules include:
  17. :mod:`matplotlib.axes`
  18. The `~.axes.Axes` class. Most pyplot functions are wrappers for
  19. `~.axes.Axes` methods. The axes module is the highest level of OO
  20. access to the library.
  21. :mod:`matplotlib.figure`
  22. The `.Figure` class.
  23. :mod:`matplotlib.artist`
  24. The `.Artist` base class for all classes that draw things.
  25. :mod:`matplotlib.lines`
  26. The `.Line2D` class for drawing lines and markers.
  27. :mod:`matplotlib.patches`
  28. Classes for drawing polygons.
  29. :mod:`matplotlib.text`
  30. The `.Text` and `.Annotation` classes.
  31. :mod:`matplotlib.image`
  32. The `.AxesImage` and `.FigureImage` classes.
  33. :mod:`matplotlib.collections`
  34. Classes for efficient drawing of groups of lines or polygons.
  35. :mod:`matplotlib.colors`
  36. Color specifications and making colormaps.
  37. :mod:`matplotlib.cm`
  38. Colormaps, and the `.ScalarMappable` mixin class for providing color
  39. mapping functionality to other classes.
  40. :mod:`matplotlib.ticker`
  41. Calculation of tick mark locations and formatting of tick labels.
  42. :mod:`matplotlib.backends`
  43. A subpackage with modules for various GUI libraries and output formats.
  44. The base matplotlib namespace includes:
  45. `~matplotlib.rcParams`
  46. Default configuration settings; their defaults may be overridden using
  47. a :file:`matplotlibrc` file.
  48. `~matplotlib.use`
  49. Setting the Matplotlib backend. This should be called before any
  50. figure is created, because it is not possible to switch between
  51. different GUI backends after that.
  52. Matplotlib was initially written by John D. Hunter (1968-2012) and is now
  53. developed and maintained by a host of others.
  54. Occasionally the internal documentation (python docstrings) will refer
  55. to MATLAB®, a registered trademark of The MathWorks, Inc.
  56. """
  57. import atexit
  58. from collections import namedtuple
  59. from collections.abc import MutableMapping
  60. import contextlib
  61. from distutils.version import LooseVersion
  62. import functools
  63. import importlib
  64. import inspect
  65. from inspect import Parameter
  66. import locale
  67. import logging
  68. import os
  69. from pathlib import Path
  70. import pprint
  71. import re
  72. import shutil
  73. import subprocess
  74. import sys
  75. import tempfile
  76. import warnings
  77. # cbook must import matplotlib only within function
  78. # definitions, so it is safe to import from it here.
  79. from . import cbook, rcsetup
  80. from matplotlib.cbook import MatplotlibDeprecationWarning, sanitize_sequence
  81. from matplotlib.cbook import mplDeprecation # deprecated
  82. from matplotlib.rcsetup import validate_backend, cycler
  83. import numpy
  84. # Get the version from the _version.py versioneer file. For a git checkout,
  85. # this is computed based on the number of commits since the last tag.
  86. from ._version import get_versions
  87. __version__ = str(get_versions()['version'])
  88. del get_versions
  89. _log = logging.getLogger(__name__)
  90. __bibtex__ = r"""@Article{Hunter:2007,
  91. Author = {Hunter, J. D.},
  92. Title = {Matplotlib: A 2D graphics environment},
  93. Journal = {Computing in Science \& Engineering},
  94. Volume = {9},
  95. Number = {3},
  96. Pages = {90--95},
  97. abstract = {Matplotlib is a 2D graphics package used for Python
  98. for application development, interactive scripting, and
  99. publication-quality image generation across user
  100. interfaces and operating systems.},
  101. publisher = {IEEE COMPUTER SOC},
  102. year = 2007
  103. }"""
  104. @cbook.deprecated("3.2")
  105. def compare_versions(a, b):
  106. """Return whether version *a* is greater than or equal to version *b*."""
  107. if isinstance(a, bytes):
  108. cbook.warn_deprecated(
  109. "3.0", message="compare_versions arguments should be strs.")
  110. a = a.decode('ascii')
  111. if isinstance(b, bytes):
  112. cbook.warn_deprecated(
  113. "3.0", message="compare_versions arguments should be strs.")
  114. b = b.decode('ascii')
  115. if a:
  116. return LooseVersion(a) >= LooseVersion(b)
  117. else:
  118. return False
  119. def _check_versions():
  120. # Quickfix to ensure Microsoft Visual C++ redistributable
  121. # DLLs are loaded before importing kiwisolver
  122. from . import ft2font
  123. for modname, minver in [
  124. ("cycler", "0.10"),
  125. ("dateutil", "2.1"),
  126. ("kiwisolver", "1.0.1"),
  127. ("numpy", "1.15"),
  128. ("pyparsing", "2.0.1"),
  129. ]:
  130. module = importlib.import_module(modname)
  131. if LooseVersion(module.__version__) < minver:
  132. raise ImportError("Matplotlib requires {}>={}; you have {}"
  133. .format(modname, minver, module.__version__))
  134. _check_versions()
  135. # The decorator ensures this always returns the same handler (and it is only
  136. # attached once).
  137. @functools.lru_cache()
  138. def _ensure_handler():
  139. """
  140. The first time this function is called, attach a `StreamHandler` using the
  141. same format as `logging.basicConfig` to the Matplotlib root logger.
  142. Return this handler every time this function is called.
  143. """
  144. handler = logging.StreamHandler()
  145. handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
  146. _log.addHandler(handler)
  147. return handler
  148. def set_loglevel(level):
  149. """
  150. Set Matplotlib's root logger and root logger handler level, creating
  151. the handler if it does not exist yet.
  152. Typically, one should call ``set_loglevel("info")`` or
  153. ``set_loglevel("debug")`` to get additional debugging information.
  154. Parameters
  155. ----------
  156. level : {"notset", "debug", "info", "warning", "error", "critical"}
  157. The log level of the handler.
  158. Notes
  159. -----
  160. The first time this function is called, an additional handler is attached
  161. to Matplotlib's root handler; this handler is reused every time and this
  162. function simply manipulates the logger and handler's level.
  163. """
  164. _log.setLevel(level.upper())
  165. _ensure_handler().setLevel(level.upper())
  166. def _logged_cached(fmt, func=None):
  167. """
  168. Decorator that logs a function's return value, and memoizes that value.
  169. After ::
  170. @_logged_cached(fmt)
  171. def func(): ...
  172. the first call to *func* will log its return value at the DEBUG level using
  173. %-format string *fmt*, and memoize it; later calls to *func* will directly
  174. return that value.
  175. """
  176. if func is None: # Return the actual decorator.
  177. return functools.partial(_logged_cached, fmt)
  178. called = False
  179. ret = None
  180. @functools.wraps(func)
  181. def wrapper(**kwargs):
  182. nonlocal called, ret
  183. if not called:
  184. ret = func(**kwargs)
  185. called = True
  186. _log.debug(fmt, ret)
  187. return ret
  188. return wrapper
  189. _ExecInfo = namedtuple("_ExecInfo", "executable version")
  190. class ExecutableNotFoundError(FileNotFoundError):
  191. """
  192. Error raised when an executable that Matplotlib optionally
  193. depends on can't be found.
  194. """
  195. pass
  196. @functools.lru_cache()
  197. def _get_executable_info(name):
  198. """
  199. Get the version of some executable that Matplotlib optionally depends on.
  200. .. warning:
  201. The list of executables that this function supports is set according to
  202. Matplotlib's internal needs, and may change without notice.
  203. Parameters
  204. ----------
  205. name : str
  206. The executable to query. The following values are currently supported:
  207. "dvipng", "gs", "inkscape", "magick", "pdftops". This list is subject
  208. to change without notice.
  209. Returns
  210. -------
  211. If the executable is found, a namedtuple with fields ``executable`` (`str`)
  212. and ``version`` (`distutils.version.LooseVersion`, or ``None`` if the
  213. version cannot be determined).
  214. Raises
  215. ------
  216. ExecutableNotFoundError
  217. If the executable is not found or older than the oldest version
  218. supported by Matplotlib.
  219. ValueError
  220. If the executable is not one that we know how to query.
  221. """
  222. def impl(args, regex, min_ver=None, ignore_exit_code=False):
  223. # Execute the subprocess specified by args; capture stdout and stderr.
  224. # Search for a regex match in the output; if the match succeeds, the
  225. # first group of the match is the version.
  226. # Return an _ExecInfo if the executable exists, and has a version of
  227. # at least min_ver (if set); else, raise ExecutableNotFoundError.
  228. try:
  229. output = subprocess.check_output(
  230. args, stderr=subprocess.STDOUT,
  231. universal_newlines=True, errors="replace")
  232. except subprocess.CalledProcessError as _cpe:
  233. if ignore_exit_code:
  234. output = _cpe.output
  235. else:
  236. raise ExecutableNotFoundError(str(_cpe)) from _cpe
  237. except OSError as _ose:
  238. raise ExecutableNotFoundError(str(_ose)) from _ose
  239. match = re.search(regex, output)
  240. if match:
  241. version = LooseVersion(match.group(1))
  242. if min_ver is not None and version < min_ver:
  243. raise ExecutableNotFoundError(
  244. f"You have {args[0]} version {version} but the minimum "
  245. f"version supported by Matplotlib is {min_ver}")
  246. return _ExecInfo(args[0], version)
  247. else:
  248. raise ExecutableNotFoundError(
  249. f"Failed to determine the version of {args[0]} from "
  250. f"{' '.join(args)}, which output {output}")
  251. if name == "dvipng":
  252. return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
  253. elif name == "gs":
  254. execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
  255. if sys.platform == "win32" else
  256. ["gs"])
  257. for e in execs:
  258. try:
  259. return impl([e, "--version"], "(.*)", "9")
  260. except ExecutableNotFoundError:
  261. pass
  262. message = "Failed to find a Ghostscript installation"
  263. raise ExecutableNotFoundError(message)
  264. elif name == "inkscape":
  265. try:
  266. # Try headless option first (needed for Inkscape version < 1.0):
  267. return impl(["inkscape", "--without-gui", "-V"],
  268. "Inkscape ([^ ]*)")
  269. except ExecutableNotFoundError:
  270. pass # Suppress exception chaining.
  271. # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
  272. # try without it:
  273. return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
  274. elif name == "magick":
  275. path = None
  276. if sys.platform == "win32":
  277. # Check the registry to avoid confusing ImageMagick's convert with
  278. # Windows's builtin convert.exe.
  279. import winreg
  280. binpath = ""
  281. for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
  282. try:
  283. with winreg.OpenKeyEx(
  284. winreg.HKEY_LOCAL_MACHINE,
  285. r"Software\Imagemagick\Current",
  286. 0, winreg.KEY_QUERY_VALUE | flag) as hkey:
  287. binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
  288. except OSError:
  289. pass
  290. if binpath:
  291. for name in ["convert.exe", "magick.exe"]:
  292. candidate = Path(binpath, name)
  293. if candidate.exists():
  294. path = str(candidate)
  295. break
  296. else:
  297. path = "convert"
  298. if path is None:
  299. raise ExecutableNotFoundError(
  300. "Failed to find an ImageMagick installation")
  301. return impl([path, "--version"], r"^Version: ImageMagick (\S*)")
  302. elif name == "pdftops":
  303. info = impl(["pdftops", "-v"], "^pdftops version (.*)",
  304. ignore_exit_code=True)
  305. if info and not ("3.0" <= info.version
  306. # poppler version numbers.
  307. or "0.9" <= info.version <= "1.0"):
  308. raise ExecutableNotFoundError(
  309. f"You have pdftops version {info.version} but the minimum "
  310. f"version supported by Matplotlib is 3.0")
  311. return info
  312. else:
  313. raise ValueError("Unknown executable: {!r}".format(name))
  314. @cbook.deprecated("3.2")
  315. def checkdep_ps_distiller(s):
  316. if not s:
  317. return False
  318. try:
  319. _get_executable_info("gs")
  320. except ExecutableNotFoundError:
  321. _log.warning(
  322. "Setting rcParams['ps.usedistiller'] requires ghostscript.")
  323. return False
  324. if s == "xpdf":
  325. try:
  326. _get_executable_info("pdftops")
  327. except ExecutableNotFoundError:
  328. _log.warning(
  329. "Setting rcParams['ps.usedistiller'] to 'xpdf' requires xpdf.")
  330. return False
  331. return s
  332. def checkdep_usetex(s):
  333. if not s:
  334. return False
  335. if not shutil.which("tex"):
  336. _log.warning("usetex mode requires TeX.")
  337. return False
  338. try:
  339. _get_executable_info("dvipng")
  340. except ExecutableNotFoundError:
  341. _log.warning("usetex mode requires dvipng.")
  342. return False
  343. try:
  344. _get_executable_info("gs")
  345. except ExecutableNotFoundError:
  346. _log.warning("usetex mode requires ghostscript.")
  347. return False
  348. return True
  349. @cbook.deprecated("3.2", alternative="os.path.expanduser('~')")
  350. @_logged_cached('$HOME=%s')
  351. def get_home():
  352. """
  353. Return the user's home directory.
  354. If the user's home directory cannot be found, return None.
  355. """
  356. try:
  357. return str(Path.home())
  358. except Exception:
  359. return None
  360. def _get_xdg_config_dir():
  361. """
  362. Return the XDG configuration directory, according to the XDG base
  363. directory spec:
  364. https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  365. """
  366. return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
  367. def _get_xdg_cache_dir():
  368. """
  369. Return the XDG cache directory, according to the XDG base directory spec:
  370. https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  371. """
  372. return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
  373. def _get_config_or_cache_dir(xdg_base):
  374. configdir = os.environ.get('MPLCONFIGDIR')
  375. if configdir:
  376. configdir = Path(configdir).resolve()
  377. elif sys.platform.startswith(('linux', 'freebsd')) and xdg_base:
  378. configdir = Path(xdg_base, "matplotlib")
  379. else:
  380. configdir = Path.home() / ".matplotlib"
  381. try:
  382. configdir.mkdir(parents=True, exist_ok=True)
  383. except OSError:
  384. pass
  385. else:
  386. if os.access(str(configdir), os.W_OK) and configdir.is_dir():
  387. return str(configdir)
  388. # If the config or cache directory cannot be created or is not a writable
  389. # directory, create a temporary one.
  390. tmpdir = os.environ["MPLCONFIGDIR"] = \
  391. tempfile.mkdtemp(prefix="matplotlib-")
  392. atexit.register(shutil.rmtree, tmpdir)
  393. _log.warning(
  394. "Matplotlib created a temporary config/cache directory at %s because "
  395. "the default path (%s) is not a writable directory; it is highly "
  396. "recommended to set the MPLCONFIGDIR environment variable to a "
  397. "writable directory, in particular to speed up the import of "
  398. "Matplotlib and to better support multiprocessing.",
  399. tmpdir, configdir)
  400. return tmpdir
  401. @_logged_cached('CONFIGDIR=%s')
  402. def get_configdir():
  403. """
  404. Return the string path of the the configuration directory.
  405. The directory is chosen as follows:
  406. 1. If the MPLCONFIGDIR environment variable is supplied, choose that.
  407. 2. On Linux, follow the XDG specification and look first in
  408. ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
  409. platforms, choose ``$HOME/.matplotlib``.
  410. 3. If the chosen directory exists and is writable, use that as the
  411. configuration directory.
  412. 4. Else, create a temporary directory, and use it as the configuration
  413. directory.
  414. """
  415. return _get_config_or_cache_dir(_get_xdg_config_dir())
  416. @_logged_cached('CACHEDIR=%s')
  417. def get_cachedir():
  418. """
  419. Return the string path of the cache directory.
  420. The procedure used to find the directory is the same as for
  421. _get_config_dir, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
  422. """
  423. return _get_config_or_cache_dir(_get_xdg_cache_dir())
  424. @_logged_cached('matplotlib data path: %s')
  425. def get_data_path(*, _from_rc=None):
  426. """Return the path to Matplotlib data."""
  427. if _from_rc is not None:
  428. cbook.warn_deprecated(
  429. "3.2",
  430. message=("Setting the datapath via matplotlibrc is deprecated "
  431. "%(since)s and will be removed %(removal)s."),
  432. removal='3.4')
  433. path = Path(_from_rc)
  434. if path.is_dir():
  435. return str(path)
  436. else:
  437. warnings.warn(f"You passed datapath: {_from_rc!r} in your "
  438. f"matplotribrc file ({matplotlib_fname()}). "
  439. "However this path does not exist, falling back "
  440. "to standard paths.")
  441. return _get_data_path()
  442. @_logged_cached('(private) matplotlib data path: %s')
  443. def _get_data_path():
  444. path = Path(__file__).with_name("mpl-data")
  445. if path.is_dir():
  446. return str(path)
  447. cbook.warn_deprecated(
  448. "3.2", message="Matplotlib installs where the data is not in the "
  449. "mpl-data subdirectory of the package are deprecated since %(since)s "
  450. "and support for them will be removed %(removal)s.")
  451. def get_candidate_paths():
  452. # setuptools' namespace_packages may hijack this init file
  453. # so need to try something known to be in Matplotlib, not basemap.
  454. import matplotlib.afm
  455. yield Path(matplotlib.afm.__file__).with_name('mpl-data')
  456. # py2exe zips pure python, so still need special check.
  457. if getattr(sys, 'frozen', None):
  458. yield Path(sys.executable).with_name('mpl-data')
  459. # Try again assuming we need to step up one more directory.
  460. yield Path(sys.executable).parent.with_name('mpl-data')
  461. # Try again assuming sys.path[0] is a dir not a exe.
  462. yield Path(sys.path[0]) / 'mpl-data'
  463. for path in get_candidate_paths():
  464. if path.is_dir():
  465. defaultParams['datapath'][0] = str(path)
  466. return str(path)
  467. raise RuntimeError('Could not find the matplotlib data files')
  468. def matplotlib_fname():
  469. """
  470. Get the location of the config file.
  471. The file location is determined in the following order
  472. - ``$PWD/matplotlibrc``
  473. - ``$MATPLOTLIBRC`` if it is not a directory
  474. - ``$MATPLOTLIBRC/matplotlibrc``
  475. - ``$MPLCONFIGDIR/matplotlibrc``
  476. - On Linux,
  477. - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
  478. is defined)
  479. - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
  480. is not defined)
  481. - On other platforms,
  482. - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
  483. - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
  484. exist.
  485. """
  486. def gen_candidates():
  487. yield os.path.join(os.getcwd(), 'matplotlibrc')
  488. try:
  489. matplotlibrc = os.environ['MATPLOTLIBRC']
  490. except KeyError:
  491. pass
  492. else:
  493. yield matplotlibrc
  494. yield os.path.join(matplotlibrc, 'matplotlibrc')
  495. yield os.path.join(get_configdir(), 'matplotlibrc')
  496. yield os.path.join(_get_data_path(), 'matplotlibrc')
  497. for fname in gen_candidates():
  498. if os.path.exists(fname) and not os.path.isdir(fname):
  499. return fname
  500. raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
  501. "install is broken")
  502. # rcParams deprecated and automatically mapped to another key.
  503. # Values are tuples of (version, new_name, f_old2new, f_new2old).
  504. _deprecated_map = {}
  505. # rcParams deprecated; some can manually be mapped to another key.
  506. # Values are tuples of (version, new_name_or_None).
  507. _deprecated_ignore_map = {
  508. }
  509. # rcParams deprecated; can use None to suppress warnings; remain actually
  510. # listed in the rcParams (not included in _all_deprecated).
  511. # Values are tuples of (version,)
  512. _deprecated_remain_as_none = {
  513. 'datapath': ('3.2.1',),
  514. 'animation.avconv_path': ('3.3',),
  515. 'animation.avconv_args': ('3.3',),
  516. 'animation.html_args': ('3.3',),
  517. 'mathtext.fallback_to_cm': ('3.3',),
  518. 'keymap.all_axes': ('3.3',),
  519. 'savefig.jpeg_quality': ('3.3',),
  520. 'text.latex.preview': ('3.3',),
  521. }
  522. _all_deprecated = {*_deprecated_map, *_deprecated_ignore_map}
  523. class RcParams(MutableMapping, dict):
  524. """
  525. A dictionary object including validation.
  526. Validating functions are defined and associated with rc parameters in
  527. :mod:`matplotlib.rcsetup`.
  528. See Also
  529. --------
  530. :ref:`customizing-with-matplotlibrc-files`
  531. """
  532. validate = rcsetup._validators
  533. # validate values on the way in
  534. def __init__(self, *args, **kwargs):
  535. self.update(*args, **kwargs)
  536. def __setitem__(self, key, val):
  537. try:
  538. if key in _deprecated_map:
  539. version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
  540. cbook.warn_deprecated(
  541. version, name=key, obj_type="rcparam", alternative=alt_key)
  542. key = alt_key
  543. val = alt_val(val)
  544. elif key in _deprecated_remain_as_none and val is not None:
  545. version, = _deprecated_remain_as_none[key]
  546. cbook.warn_deprecated(
  547. version, name=key, obj_type="rcparam")
  548. elif key in _deprecated_ignore_map:
  549. version, alt_key = _deprecated_ignore_map[key]
  550. cbook.warn_deprecated(
  551. version, name=key, obj_type="rcparam", alternative=alt_key)
  552. return
  553. elif key == 'backend':
  554. if val is rcsetup._auto_backend_sentinel:
  555. if 'backend' in self:
  556. return
  557. try:
  558. cval = self.validate[key](val)
  559. except ValueError as ve:
  560. raise ValueError(f"Key {key}: {ve}") from None
  561. dict.__setitem__(self, key, cval)
  562. except KeyError as err:
  563. raise KeyError(
  564. f"{key} is not a valid rc parameter (see rcParams.keys() for "
  565. f"a list of valid parameters)") from err
  566. def __getitem__(self, key):
  567. if key in _deprecated_map:
  568. version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
  569. cbook.warn_deprecated(
  570. version, name=key, obj_type="rcparam", alternative=alt_key)
  571. return inverse_alt(dict.__getitem__(self, alt_key))
  572. elif key in _deprecated_ignore_map:
  573. version, alt_key = _deprecated_ignore_map[key]
  574. cbook.warn_deprecated(
  575. version, name=key, obj_type="rcparam", alternative=alt_key)
  576. return dict.__getitem__(self, alt_key) if alt_key else None
  577. elif key == "backend":
  578. val = dict.__getitem__(self, key)
  579. if val is rcsetup._auto_backend_sentinel:
  580. from matplotlib import pyplot as plt
  581. plt.switch_backend(rcsetup._auto_backend_sentinel)
  582. elif key == "datapath":
  583. return get_data_path()
  584. return dict.__getitem__(self, key)
  585. def __repr__(self):
  586. class_name = self.__class__.__name__
  587. indent = len(class_name) + 1
  588. with cbook._suppress_matplotlib_deprecation_warning():
  589. repr_split = pprint.pformat(dict(self), indent=1,
  590. width=80 - indent).split('\n')
  591. repr_indented = ('\n' + ' ' * indent).join(repr_split)
  592. return '{}({})'.format(class_name, repr_indented)
  593. def __str__(self):
  594. return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
  595. def __iter__(self):
  596. """Yield sorted list of keys."""
  597. with cbook._suppress_matplotlib_deprecation_warning():
  598. yield from sorted(dict.__iter__(self))
  599. def __len__(self):
  600. return dict.__len__(self)
  601. def find_all(self, pattern):
  602. """
  603. Return the subset of this RcParams dictionary whose keys match,
  604. using :func:`re.search`, the given ``pattern``.
  605. .. note::
  606. Changes to the returned dictionary are *not* propagated to
  607. the parent RcParams dictionary.
  608. """
  609. pattern_re = re.compile(pattern)
  610. return RcParams((key, value)
  611. for key, value in self.items()
  612. if pattern_re.search(key))
  613. def copy(self):
  614. return {k: dict.__getitem__(self, k) for k in self}
  615. def rc_params(fail_on_error=False):
  616. """Construct a `RcParams` instance from the default Matplotlib rc file."""
  617. return rc_params_from_file(matplotlib_fname(), fail_on_error)
  618. URL_REGEX = re.compile(r'^http://|^https://|^ftp://|^file:')
  619. def is_url(filename):
  620. """Return True if string is an http, ftp, or file URL path."""
  621. return URL_REGEX.match(filename) is not None
  622. @functools.lru_cache()
  623. def _get_ssl_context():
  624. try:
  625. import certifi
  626. except ImportError:
  627. _log.debug("Could not import certifi.")
  628. return None
  629. import ssl
  630. return ssl.create_default_context(cafile=certifi.where())
  631. @contextlib.contextmanager
  632. def _open_file_or_url(fname):
  633. if not isinstance(fname, Path) and is_url(fname):
  634. import urllib.request
  635. ssl_ctx = _get_ssl_context()
  636. if ssl_ctx is None:
  637. _log.debug(
  638. "Could not get certifi ssl context, https may not work."
  639. )
  640. with urllib.request.urlopen(fname, context=ssl_ctx) as f:
  641. yield (line.decode('utf-8') for line in f)
  642. else:
  643. fname = os.path.expanduser(fname)
  644. encoding = locale.getpreferredencoding(do_setlocale=False)
  645. if encoding is None:
  646. encoding = "utf-8"
  647. with open(fname, encoding=encoding) as f:
  648. yield f
  649. def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
  650. """
  651. Construct a `RcParams` instance from file *fname*.
  652. Unlike `rc_params_from_file`, the configuration class only contains the
  653. parameters specified in the file (i.e. default values are not filled in).
  654. Parameters
  655. ----------
  656. fname : path-like
  657. The loaded file.
  658. transform : callable, default: the identity function
  659. A function called on each individual line of the file to transform it,
  660. before further parsing.
  661. fail_on_error : bool, default: False
  662. Whether invalid entries should result in an exception or a warning.
  663. """
  664. rc_temp = {}
  665. with _open_file_or_url(fname) as fd:
  666. try:
  667. for line_no, line in enumerate(fd, 1):
  668. line = transform(line)
  669. strippedline = line.split('#', 1)[0].strip()
  670. if not strippedline:
  671. continue
  672. tup = strippedline.split(':', 1)
  673. if len(tup) != 2:
  674. _log.warning('Missing colon in file %r, line %d (%r)',
  675. fname, line_no, line.rstrip('\n'))
  676. continue
  677. key, val = tup
  678. key = key.strip()
  679. val = val.strip()
  680. if key in rc_temp:
  681. _log.warning('Duplicate key in file %r, line %d (%r)',
  682. fname, line_no, line.rstrip('\n'))
  683. rc_temp[key] = (val, line, line_no)
  684. except UnicodeDecodeError:
  685. _log.warning('Cannot decode configuration file %s with encoding '
  686. '%s, check LANG and LC_* variables.',
  687. fname,
  688. locale.getpreferredencoding(do_setlocale=False)
  689. or 'utf-8 (default)')
  690. raise
  691. config = RcParams()
  692. for key, (val, line, line_no) in rc_temp.items():
  693. if key in rcsetup._validators:
  694. if fail_on_error:
  695. config[key] = val # try to convert to proper type or raise
  696. else:
  697. try:
  698. config[key] = val # try to convert to proper type or skip
  699. except Exception as msg:
  700. _log.warning('Bad value in file %r, line %d (%r): %s',
  701. fname, line_no, line.rstrip('\n'), msg)
  702. elif key in _deprecated_ignore_map:
  703. version, alt_key = _deprecated_ignore_map[key]
  704. cbook.warn_deprecated(
  705. version, name=key, alternative=alt_key,
  706. addendum="Please update your matplotlibrc.")
  707. else:
  708. version = 'master' if '.post' in __version__ else f'v{__version__}'
  709. _log.warning("""
  710. Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
  711. You probably need to get an updated matplotlibrc file from
  712. https://github.com/matplotlib/matplotlib/blob/%(version)s/matplotlibrc.template
  713. or from the matplotlib source distribution""",
  714. dict(key=key, fname=fname, line_no=line_no,
  715. line=line.rstrip('\n'), version=version))
  716. return config
  717. def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
  718. """
  719. Construct a `RcParams` from file *fname*.
  720. Parameters
  721. ----------
  722. fname : str or path-like
  723. A file with Matplotlib rc settings.
  724. fail_on_error : bool
  725. If True, raise an error when the parser fails to convert a parameter.
  726. use_default_template : bool
  727. If True, initialize with default parameters before updating with those
  728. in the given file. If False, the configuration class only contains the
  729. parameters specified in the file. (Useful for updating dicts.)
  730. """
  731. config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
  732. if not use_default_template:
  733. return config_from_file
  734. with cbook._suppress_matplotlib_deprecation_warning():
  735. config = RcParams({**rcParamsDefault, **config_from_file})
  736. with cbook._suppress_matplotlib_deprecation_warning():
  737. if config['datapath'] is None:
  738. config['datapath'] = _get_data_path()
  739. else:
  740. config['datapath'] = get_data_path(_from_rc=config['datapath'])
  741. if "".join(config['text.latex.preamble']):
  742. _log.info("""
  743. *****************************************************************
  744. You have the following UNSUPPORTED LaTeX preamble customizations:
  745. %s
  746. Please do not ask for support with these customizations active.
  747. *****************************************************************
  748. """, '\n'.join(config['text.latex.preamble']))
  749. _log.debug('loaded rc file %s', fname)
  750. return config
  751. # When constructing the global instances, we need to perform certain updates
  752. # by explicitly calling the superclass (dict.update, dict.items) to avoid
  753. # triggering resolution of _auto_backend_sentinel.
  754. rcParamsDefault = _rc_params_in_file(
  755. cbook._get_data_path("matplotlibrc"),
  756. # Strip leading comment.
  757. transform=lambda line: line[1:] if line.startswith("#") else line,
  758. fail_on_error=True)
  759. dict.update(rcParamsDefault, rcsetup._hardcoded_defaults)
  760. rcParams = RcParams() # The global instance.
  761. dict.update(rcParams, dict.items(rcParamsDefault))
  762. dict.update(rcParams, _rc_params_in_file(matplotlib_fname()))
  763. with cbook._suppress_matplotlib_deprecation_warning():
  764. rcParamsOrig = RcParams(rcParams.copy())
  765. # This also checks that all rcParams are indeed listed in the template.
  766. # Assiging to rcsetup.defaultParams is left only for backcompat.
  767. defaultParams = rcsetup.defaultParams = {
  768. # We want to resolve deprecated rcParams, but not backend...
  769. key: [(rcsetup._auto_backend_sentinel if key == "backend" else
  770. rcParamsDefault[key]),
  771. validator]
  772. for key, validator in rcsetup._validators.items()}
  773. if rcParams['axes.formatter.use_locale']:
  774. locale.setlocale(locale.LC_ALL, '')
  775. def rc(group, **kwargs):
  776. """
  777. Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
  778. for ``lines.linewidth`` the group is ``lines``, for
  779. ``axes.facecolor``, the group is ``axes``, and so on. Group may
  780. also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
  781. *kwargs* is a dictionary attribute name/value pairs, e.g.,::
  782. rc('lines', linewidth=2, color='r')
  783. sets the current `.rcParams` and is equivalent to::
  784. rcParams['lines.linewidth'] = 2
  785. rcParams['lines.color'] = 'r'
  786. The following aliases are available to save typing for interactive users:
  787. ===== =================
  788. Alias Property
  789. ===== =================
  790. 'lw' 'linewidth'
  791. 'ls' 'linestyle'
  792. 'c' 'color'
  793. 'fc' 'facecolor'
  794. 'ec' 'edgecolor'
  795. 'mew' 'markeredgewidth'
  796. 'aa' 'antialiased'
  797. ===== =================
  798. Thus you could abbreviate the above call as::
  799. rc('lines', lw=2, c='r')
  800. Note you can use python's kwargs dictionary facility to store
  801. dictionaries of default parameters. e.g., you can customize the
  802. font rc as follows::
  803. font = {'family' : 'monospace',
  804. 'weight' : 'bold',
  805. 'size' : 'larger'}
  806. rc('font', **font) # pass in the font dict as kwargs
  807. This enables you to easily switch between several configurations. Use
  808. ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
  809. restore the default `.rcParams` after changes.
  810. Notes
  811. -----
  812. Similar functionality is available by using the normal dict interface, i.e.
  813. ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
  814. does not support abbreviations or grouping).
  815. """
  816. aliases = {
  817. 'lw': 'linewidth',
  818. 'ls': 'linestyle',
  819. 'c': 'color',
  820. 'fc': 'facecolor',
  821. 'ec': 'edgecolor',
  822. 'mew': 'markeredgewidth',
  823. 'aa': 'antialiased',
  824. }
  825. if isinstance(group, str):
  826. group = (group,)
  827. for g in group:
  828. for k, v in kwargs.items():
  829. name = aliases.get(k) or k
  830. key = '%s.%s' % (g, name)
  831. try:
  832. rcParams[key] = v
  833. except KeyError as err:
  834. raise KeyError(('Unrecognized key "%s" for group "%s" and '
  835. 'name "%s"') % (key, g, name)) from err
  836. def rcdefaults():
  837. """
  838. Restore the `.rcParams` from Matplotlib's internal default style.
  839. Style-blacklisted `.rcParams` (defined in
  840. `matplotlib.style.core.STYLE_BLACKLIST`) are not updated.
  841. See Also
  842. --------
  843. matplotlib.rc_file_defaults
  844. Restore the `.rcParams` from the rc file originally loaded by
  845. Matplotlib.
  846. matplotlib.style.use
  847. Use a specific style file. Call ``style.use('default')`` to restore
  848. the default style.
  849. """
  850. # Deprecation warnings were already handled when creating rcParamsDefault,
  851. # no need to reemit them here.
  852. with cbook._suppress_matplotlib_deprecation_warning():
  853. from .style.core import STYLE_BLACKLIST
  854. rcParams.clear()
  855. rcParams.update({k: v for k, v in rcParamsDefault.items()
  856. if k not in STYLE_BLACKLIST})
  857. def rc_file_defaults():
  858. """
  859. Restore the `.rcParams` from the original rc file loaded by Matplotlib.
  860. Style-blacklisted `.rcParams` (defined in
  861. `matplotlib.style.core.STYLE_BLACKLIST`) are not updated.
  862. """
  863. # Deprecation warnings were already handled when creating rcParamsOrig, no
  864. # need to reemit them here.
  865. with cbook._suppress_matplotlib_deprecation_warning():
  866. from .style.core import STYLE_BLACKLIST
  867. rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
  868. if k not in STYLE_BLACKLIST})
  869. def rc_file(fname, *, use_default_template=True):
  870. """
  871. Update `.rcParams` from file.
  872. Style-blacklisted `.rcParams` (defined in
  873. `matplotlib.style.core.STYLE_BLACKLIST`) are not updated.
  874. Parameters
  875. ----------
  876. fname : str or path-like
  877. A file with Matplotlib rc settings.
  878. use_default_template : bool
  879. If True, initialize with default parameters before updating with those
  880. in the given file. If False, the current configuration persists
  881. and only the parameters specified in the file are updated.
  882. """
  883. # Deprecation warnings were already handled in rc_params_from_file, no need
  884. # to reemit them here.
  885. with cbook._suppress_matplotlib_deprecation_warning():
  886. from .style.core import STYLE_BLACKLIST
  887. rc_from_file = rc_params_from_file(
  888. fname, use_default_template=use_default_template)
  889. rcParams.update({k: rc_from_file[k] for k in rc_from_file
  890. if k not in STYLE_BLACKLIST})
  891. @contextlib.contextmanager
  892. def rc_context(rc=None, fname=None):
  893. """
  894. Return a context manager for temporarily changing rcParams.
  895. Parameters
  896. ----------
  897. rc : dict
  898. The rcParams to temporarily set.
  899. fname : str or path-like
  900. A file with Matplotlib rc settings. If both *fname* and *rc* are given,
  901. settings from *rc* take precedence.
  902. See Also
  903. --------
  904. :ref:`customizing-with-matplotlibrc-files`
  905. Examples
  906. --------
  907. Passing explicit values via a dict::
  908. with mpl.rc_context({'interactive': False}):
  909. fig, ax = plt.subplots()
  910. ax.plot(range(3), range(3))
  911. fig.savefig('example.png')
  912. plt.close(fig)
  913. Loading settings from a file::
  914. with mpl.rc_context(fname='print.rc'):
  915. plt.plot(x, y) # uses 'print.rc'
  916. """
  917. orig = rcParams.copy()
  918. try:
  919. if fname:
  920. rc_file(fname)
  921. if rc:
  922. rcParams.update(rc)
  923. yield
  924. finally:
  925. dict.update(rcParams, orig) # Revert to the original rcs.
  926. def use(backend, *, force=True):
  927. """
  928. Select the backend used for rendering and GUI integration.
  929. Parameters
  930. ----------
  931. backend : str
  932. The backend to switch to. This can either be one of the standard
  933. backend names, which are case-insensitive:
  934. - interactive backends:
  935. GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
  936. Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
  937. TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo
  938. - non-interactive backends:
  939. agg, cairo, pdf, pgf, ps, svg, template
  940. or a string of the form: ``module://my.module.name``.
  941. force : bool, default: True
  942. If True (the default), raise an `ImportError` if the backend cannot be
  943. set up (either because it fails to import, or because an incompatible
  944. GUI interactive framework is already running); if False, ignore the
  945. failure.
  946. See Also
  947. --------
  948. :ref:`backends`
  949. matplotlib.get_backend
  950. """
  951. name = validate_backend(backend)
  952. # we need to use the base-class method here to avoid (prematurely)
  953. # resolving the "auto" backend setting
  954. if dict.__getitem__(rcParams, 'backend') == name:
  955. # Nothing to do if the requested backend is already set
  956. pass
  957. else:
  958. # if pyplot is not already imported, do not import it. Doing
  959. # so may trigger a `plt.switch_backend` to the _default_ backend
  960. # before we get a chance to change to the one the user just requested
  961. plt = sys.modules.get('matplotlib.pyplot')
  962. # if pyplot is imported, then try to change backends
  963. if plt is not None:
  964. try:
  965. # we need this import check here to re-raise if the
  966. # user does not have the libraries to support their
  967. # chosen backend installed.
  968. plt.switch_backend(name)
  969. except ImportError:
  970. if force:
  971. raise
  972. # if we have not imported pyplot, then we can set the rcParam
  973. # value which will be respected when the user finally imports
  974. # pyplot
  975. else:
  976. rcParams['backend'] = backend
  977. # if the user has asked for a given backend, do not helpfully
  978. # fallback
  979. rcParams['backend_fallback'] = False
  980. if os.environ.get('MPLBACKEND'):
  981. rcParams['backend'] = os.environ.get('MPLBACKEND')
  982. def get_backend():
  983. """
  984. Return the name of the current backend.
  985. See Also
  986. --------
  987. matplotlib.use
  988. """
  989. return rcParams['backend']
  990. def interactive(b):
  991. """
  992. Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
  993. """
  994. rcParams['interactive'] = b
  995. def is_interactive():
  996. """Return whether to redraw after every plotting command."""
  997. return rcParams['interactive']
  998. default_test_modules = [
  999. 'matplotlib.tests',
  1000. 'mpl_toolkits.tests',
  1001. ]
  1002. def _init_tests():
  1003. # The version of FreeType to install locally for running the
  1004. # tests. This must match the value in `setupext.py`
  1005. LOCAL_FREETYPE_VERSION = '2.6.1'
  1006. from matplotlib import ft2font
  1007. if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
  1008. ft2font.__freetype_build_type__ != 'local'):
  1009. _log.warning(
  1010. f"Matplotlib is not built with the correct FreeType version to "
  1011. f"run tests. Rebuild without setting system_freetype=1 in "
  1012. f"setup.cfg. Expect many image comparison failures below. "
  1013. f"Expected freetype version {LOCAL_FREETYPE_VERSION}. "
  1014. f"Found freetype version {ft2font.__freetype_version__}. "
  1015. "Freetype build type is {}local".format(
  1016. "" if ft2font.__freetype_build_type__ == 'local' else "not "))
  1017. @cbook._delete_parameter("3.2", "switch_backend_warn")
  1018. @cbook._delete_parameter("3.3", "recursionlimit")
  1019. def test(verbosity=None, coverage=False, switch_backend_warn=True,
  1020. recursionlimit=0, **kwargs):
  1021. """Run the matplotlib test suite."""
  1022. try:
  1023. import pytest
  1024. except ImportError:
  1025. print("matplotlib.test requires pytest to run.")
  1026. return -1
  1027. if not os.path.isdir(os.path.join(os.path.dirname(__file__), 'tests')):
  1028. print("Matplotlib test data is not installed")
  1029. return -1
  1030. old_backend = get_backend()
  1031. old_recursionlimit = sys.getrecursionlimit()
  1032. try:
  1033. use('agg')
  1034. if recursionlimit:
  1035. sys.setrecursionlimit(recursionlimit)
  1036. args = kwargs.pop('argv', [])
  1037. provide_default_modules = True
  1038. use_pyargs = True
  1039. for arg in args:
  1040. if any(arg.startswith(module_path)
  1041. for module_path in default_test_modules):
  1042. provide_default_modules = False
  1043. break
  1044. if os.path.exists(arg):
  1045. provide_default_modules = False
  1046. use_pyargs = False
  1047. break
  1048. if use_pyargs:
  1049. args += ['--pyargs']
  1050. if provide_default_modules:
  1051. args += default_test_modules
  1052. if coverage:
  1053. args += ['--cov']
  1054. if verbosity:
  1055. args += ['-' + 'v' * verbosity]
  1056. retcode = pytest.main(args, **kwargs)
  1057. finally:
  1058. if old_backend.lower() != 'agg':
  1059. use(old_backend)
  1060. if recursionlimit:
  1061. sys.setrecursionlimit(old_recursionlimit)
  1062. return retcode
  1063. test.__test__ = False # pytest: this function is not a test
  1064. def _replacer(data, value):
  1065. """
  1066. Either returns ``data[value]`` or passes ``data`` back, converts either to
  1067. a sequence.
  1068. """
  1069. try:
  1070. # if key isn't a string don't bother
  1071. if isinstance(value, str):
  1072. # try to use __getitem__
  1073. value = data[value]
  1074. except Exception:
  1075. # key does not exist, silently fall back to key
  1076. pass
  1077. return sanitize_sequence(value)
  1078. def _label_from_arg(y, default_name):
  1079. try:
  1080. return y.name
  1081. except AttributeError:
  1082. if isinstance(default_name, str):
  1083. return default_name
  1084. return None
  1085. _DATA_DOC_TITLE = """
  1086. Notes
  1087. -----
  1088. """
  1089. _DATA_DOC_APPENDIX = """
  1090. .. note::
  1091. In addition to the above described arguments, this function can take
  1092. a *data* keyword argument. If such a *data* argument is given,
  1093. {replaced}
  1094. Objects passed as **data** must support item access (``data[s]``) and
  1095. membership test (``s in data``).
  1096. """
  1097. def _add_data_doc(docstring, replace_names):
  1098. """
  1099. Add documentation for a *data* field to the given docstring.
  1100. Parameters
  1101. ----------
  1102. docstring : str
  1103. The input docstring.
  1104. replace_names : list of str or None
  1105. The list of parameter names which arguments should be replaced by
  1106. ``data[name]`` (if ``data[name]`` does not throw an exception). If
  1107. None, replacement is attempted for all arguments.
  1108. Returns
  1109. -------
  1110. str
  1111. The augmented docstring.
  1112. """
  1113. if (docstring is None
  1114. or replace_names is not None and len(replace_names) == 0):
  1115. return docstring
  1116. docstring = inspect.cleandoc(docstring)
  1117. repl = (
  1118. (" every other argument can also be string ``s``, which is\n"
  1119. " interpreted as ``data[s]`` (unless this raises an exception).")
  1120. if replace_names is None else
  1121. (" the following arguments can also be string ``s``, which is\n"
  1122. " interpreted as ``data[s]`` (unless this raises an exception):\n"
  1123. " " + ", ".join(map("*{}*".format, replace_names))) + ".")
  1124. addendum = _DATA_DOC_APPENDIX.format(replaced=repl)
  1125. if _DATA_DOC_TITLE not in docstring:
  1126. addendum = _DATA_DOC_TITLE + addendum
  1127. return docstring + addendum
  1128. def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
  1129. """
  1130. A decorator to add a 'data' kwarg to a function.
  1131. When applied::
  1132. @_preprocess_data()
  1133. def func(ax, *args, **kwargs): ...
  1134. the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
  1135. with the following behavior:
  1136. - if called with ``data=None``, forward the other arguments to ``func``;
  1137. - otherwise, *data* must be a mapping; for any argument passed in as a
  1138. string ``name``, replace the argument by ``data[name]`` (if this does not
  1139. throw an exception), then forward the arguments to ``func``.
  1140. In either case, any argument that is a `MappingView` is also converted to a
  1141. list.
  1142. Parameters
  1143. ----------
  1144. replace_names : list of str or None, default: None
  1145. The list of parameter names for which lookup into *data* should be
  1146. attempted. If None, replacement is attempted for all arguments.
  1147. label_namer : str, default: None
  1148. If set e.g. to "namer" (which must be a kwarg in the function's
  1149. signature -- not as ``**kwargs``), if the *namer* argument passed in is
  1150. a (string) key of *data* and no *label* kwarg is passed, then use the
  1151. (string) value of the *namer* as *label*. ::
  1152. @_preprocess_data(label_namer="foo")
  1153. def func(foo, label=None): ...
  1154. func("key", data={"key": value})
  1155. # is equivalent to
  1156. func.__wrapped__(value, label="key")
  1157. """
  1158. if func is None: # Return the actual decorator.
  1159. return functools.partial(
  1160. _preprocess_data,
  1161. replace_names=replace_names, label_namer=label_namer)
  1162. sig = inspect.signature(func)
  1163. varargs_name = None
  1164. varkwargs_name = None
  1165. arg_names = []
  1166. params = list(sig.parameters.values())
  1167. for p in params:
  1168. if p.kind is Parameter.VAR_POSITIONAL:
  1169. varargs_name = p.name
  1170. elif p.kind is Parameter.VAR_KEYWORD:
  1171. varkwargs_name = p.name
  1172. else:
  1173. arg_names.append(p.name)
  1174. data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
  1175. if varkwargs_name:
  1176. params.insert(-1, data_param)
  1177. else:
  1178. params.append(data_param)
  1179. new_sig = sig.replace(parameters=params)
  1180. arg_names = arg_names[1:] # remove the first "ax" / self arg
  1181. assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
  1182. "Matplotlib internal error: invalid replace_names ({!r}) for {!r}"
  1183. .format(replace_names, func.__name__))
  1184. assert label_namer is None or label_namer in arg_names, (
  1185. "Matplotlib internal error: invalid label_namer ({!r}) for {!r}"
  1186. .format(label_namer, func.__name__))
  1187. @functools.wraps(func)
  1188. def inner(ax, *args, data=None, **kwargs):
  1189. if data is None:
  1190. return func(ax, *map(sanitize_sequence, args), **kwargs)
  1191. bound = new_sig.bind(ax, *args, **kwargs)
  1192. auto_label = (bound.arguments.get(label_namer)
  1193. or bound.kwargs.get(label_namer))
  1194. for k, v in bound.arguments.items():
  1195. if k == varkwargs_name:
  1196. for k1, v1 in v.items():
  1197. if replace_names is None or k1 in replace_names:
  1198. v[k1] = _replacer(data, v1)
  1199. elif k == varargs_name:
  1200. if replace_names is None:
  1201. bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
  1202. else:
  1203. if replace_names is None or k in replace_names:
  1204. bound.arguments[k] = _replacer(data, v)
  1205. new_args = bound.args
  1206. new_kwargs = bound.kwargs
  1207. args_and_kwargs = {**bound.arguments, **bound.kwargs}
  1208. if label_namer and "label" not in args_and_kwargs:
  1209. new_kwargs["label"] = _label_from_arg(
  1210. args_and_kwargs.get(label_namer), auto_label)
  1211. return func(*new_args, **new_kwargs)
  1212. inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
  1213. inner.__signature__ = new_sig
  1214. return inner
  1215. _log.debug('matplotlib version %s', __version__)
  1216. _log.debug('interactive is %s', is_interactive())
  1217. _log.debug('platform is %s', sys.platform)
  1218. _log.debug('loaded modules: %s', list(sys.modules))