__init__.py 53 KB

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