__init__.py 55 KB

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