__init__.py 52 KB

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