rcsetup.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  1. """
  2. The rcsetup module contains the validation code for customization using
  3. Matplotlib's rc settings.
  4. Each rc setting is assigned a function used to validate any attempted changes
  5. to that setting. The validation functions are defined in the rcsetup module,
  6. and are used to construct the rcParams global object which stores the settings
  7. and is referenced throughout Matplotlib.
  8. The default values of the rc settings are set in the default matplotlibrc file.
  9. Any additions or deletions to the parameter set listed here should also be
  10. propagated to the :file:`matplotlibrc.template` in Matplotlib's root source
  11. directory.
  12. """
  13. import ast
  14. from functools import lru_cache, reduce
  15. import logging
  16. from numbers import Number
  17. import operator
  18. import os
  19. import re
  20. import numpy as np
  21. from matplotlib import animation, cbook
  22. from matplotlib.cbook import ls_mapper
  23. from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  24. from matplotlib.colors import is_color_like
  25. # Don't let the original cycler collide with our validating cycler
  26. from cycler import Cycler, cycler as ccycler
  27. _log = logging.getLogger(__name__)
  28. # The capitalized forms are needed for ipython at present; this may
  29. # change for later versions.
  30. interactive_bk = ['GTK3Agg', 'GTK3Cairo',
  31. 'MacOSX',
  32. 'nbAgg',
  33. 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo',
  34. 'TkAgg', 'TkCairo',
  35. 'WebAgg',
  36. 'WX', 'WXAgg', 'WXCairo']
  37. non_interactive_bk = ['agg', 'cairo',
  38. 'pdf', 'pgf', 'ps', 'svg', 'template']
  39. all_backends = interactive_bk + non_interactive_bk
  40. class ValidateInStrings:
  41. def __init__(self, key, valid, ignorecase=False, *,
  42. _deprecated_since=None):
  43. """*valid* is a list of legal strings."""
  44. self.key = key
  45. self.ignorecase = ignorecase
  46. self._deprecated_since = _deprecated_since
  47. def func(s):
  48. if ignorecase:
  49. return s.lower()
  50. else:
  51. return s
  52. self.valid = {func(k): k for k in valid}
  53. def __call__(self, s):
  54. if self._deprecated_since:
  55. name, = (k for k, v in globals().items() if v is self)
  56. cbook.warn_deprecated(
  57. self._deprecated_since, name=name, obj_type="function")
  58. if self.ignorecase:
  59. s = s.lower()
  60. if s in self.valid:
  61. return self.valid[s]
  62. msg = (f"{s!r} is not a valid value for {self.key}; supported values "
  63. f"are {[*self.valid.values()]}")
  64. if (isinstance(s, str)
  65. and (s.startswith('"') and s.endswith('"')
  66. or s.startswith("'") and s.endswith("'"))
  67. and s[1:-1] in self.valid):
  68. msg += "; remove quotes surrounding your string"
  69. raise ValueError(msg)
  70. @lru_cache()
  71. def _listify_validator(scalar_validator, allow_stringlist=False, *,
  72. n=None, doc=None):
  73. def f(s):
  74. if isinstance(s, str):
  75. try:
  76. val = [scalar_validator(v.strip()) for v in s.split(',')
  77. if v.strip()]
  78. except Exception:
  79. if allow_stringlist:
  80. # Sometimes, a list of colors might be a single string
  81. # of single-letter colornames. So give that a shot.
  82. val = [scalar_validator(v.strip()) for v in s if v.strip()]
  83. else:
  84. raise
  85. # Allow any ordered sequence type -- generators, np.ndarray, pd.Series
  86. # -- but not sets, whose iteration order is non-deterministic.
  87. elif np.iterable(s) and not isinstance(s, (set, frozenset)):
  88. # The condition on this list comprehension will preserve the
  89. # behavior of filtering out any empty strings (behavior was
  90. # from the original validate_stringlist()), while allowing
  91. # any non-string/text scalar values such as numbers and arrays.
  92. val = [scalar_validator(v) for v in s
  93. if not isinstance(v, str) or v]
  94. else:
  95. raise ValueError(
  96. f"Expected str or other non-set iterable, but got {s}")
  97. if n is not None and len(val) != n:
  98. raise ValueError(
  99. f"Expected {n} values, but there are {len(val)} values in {s}")
  100. return val
  101. try:
  102. f.__name__ = "{}list".format(scalar_validator.__name__)
  103. except AttributeError: # class instance.
  104. f.__name__ = "{}List".format(type(scalar_validator).__name__)
  105. f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__
  106. f.__doc__ = doc if doc is not None else scalar_validator.__doc__
  107. return f
  108. def validate_any(s):
  109. return s
  110. validate_anylist = _listify_validator(validate_any)
  111. def _validate_date(s):
  112. try:
  113. np.datetime64(s)
  114. return s
  115. except ValueError:
  116. raise ValueError(
  117. f'{s!r} should be a string that can be parsed by numpy.datetime64')
  118. @cbook.deprecated("3.2", alternative="os.path.exists")
  119. def validate_path_exists(s):
  120. """If s is a path, return s, else False"""
  121. if s is None:
  122. return None
  123. if os.path.exists(s):
  124. return s
  125. else:
  126. raise RuntimeError('"%s" should be a path but it does not exist' % s)
  127. def validate_bool(b):
  128. """Convert b to ``bool`` or raise."""
  129. if isinstance(b, str):
  130. b = b.lower()
  131. if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
  132. return True
  133. elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
  134. return False
  135. else:
  136. raise ValueError('Could not convert "%s" to bool' % b)
  137. @cbook.deprecated("3.3")
  138. def validate_bool_maybe_none(b):
  139. """Convert b to ``bool`` or raise, passing through *None*."""
  140. if isinstance(b, str):
  141. b = b.lower()
  142. if b is None or b == 'none':
  143. return None
  144. if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
  145. return True
  146. elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
  147. return False
  148. else:
  149. raise ValueError('Could not convert "%s" to bool' % b)
  150. def _validate_tex_preamble(s):
  151. if s is None or s == 'None':
  152. cbook.warn_deprecated(
  153. "3.3", message="Support for setting the 'text.latex.preamble' or "
  154. "'pgf.preamble' rcParam to None is deprecated since %(since)s and "
  155. "will be removed %(removal)s; set it to an empty string instead.")
  156. return ""
  157. try:
  158. if isinstance(s, str):
  159. return s
  160. elif np.iterable(s):
  161. cbook.warn_deprecated(
  162. "3.3", message="Support for setting the 'text.latex.preamble' "
  163. "or 'pgf.preamble' rcParam to a list of strings is deprecated "
  164. "since %(since)s and will be removed %(removal)s; set it to a "
  165. "single string instead.")
  166. return '\n'.join(s)
  167. else:
  168. raise TypeError
  169. except TypeError as e:
  170. raise ValueError('Could not convert "%s" to string' % s) from e
  171. def validate_axisbelow(s):
  172. try:
  173. return validate_bool(s)
  174. except ValueError:
  175. if isinstance(s, str):
  176. if s == 'line':
  177. return 'line'
  178. if s.lower().startswith('line'):
  179. cbook.warn_deprecated(
  180. "3.3", message=f"Support for setting axes.axisbelow to "
  181. f"{s!r} to mean 'line' is deprecated since %(since)s and "
  182. f"will be removed %(removal)s; set it to 'line' instead.")
  183. return 'line'
  184. raise ValueError('%s cannot be interpreted as'
  185. ' True, False, or "line"' % s)
  186. def validate_dpi(s):
  187. """Confirm s is string 'figure' or convert s to float or raise."""
  188. if s == 'figure':
  189. return s
  190. try:
  191. return float(s)
  192. except ValueError as e:
  193. raise ValueError(f'{s!r} is not string "figure" and '
  194. f'could not convert {s!r} to float') from e
  195. def _make_type_validator(cls, *, allow_none=False):
  196. """
  197. Return a validator that converts inputs to *cls* or raises (and possibly
  198. allows ``None`` as well).
  199. """
  200. def validator(s):
  201. if (allow_none and
  202. (s is None or isinstance(s, str) and s.lower() == "none")):
  203. return None
  204. try:
  205. return cls(s)
  206. except ValueError as e:
  207. raise ValueError(
  208. f'Could not convert {s!r} to {cls.__name__}') from e
  209. validator.__name__ = f"validate_{cls.__name__}"
  210. if allow_none:
  211. validator.__name__ += "_or_None"
  212. validator.__qualname__ = (
  213. validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__)
  214. return validator
  215. validate_string = _make_type_validator(str)
  216. validate_string_or_None = _make_type_validator(str, allow_none=True)
  217. validate_stringlist = _listify_validator(
  218. validate_string, doc='return a list of strings')
  219. validate_int = _make_type_validator(int)
  220. validate_int_or_None = _make_type_validator(int, allow_none=True)
  221. validate_float = _make_type_validator(float)
  222. validate_float_or_None = _make_type_validator(float, allow_none=True)
  223. validate_floatlist = _listify_validator(
  224. validate_float, doc='return a list of floats')
  225. def validate_fonttype(s):
  226. """
  227. Confirm that this is a Postscript or PDF font type that we know how to
  228. convert to.
  229. """
  230. fonttypes = {'type3': 3,
  231. 'truetype': 42}
  232. try:
  233. fonttype = validate_int(s)
  234. except ValueError:
  235. try:
  236. return fonttypes[s.lower()]
  237. except KeyError as e:
  238. raise ValueError('Supported Postscript/PDF font types are %s'
  239. % list(fonttypes)) from e
  240. else:
  241. if fonttype not in fonttypes.values():
  242. raise ValueError(
  243. 'Supported Postscript/PDF font types are %s' %
  244. list(fonttypes.values()))
  245. return fonttype
  246. _validate_standard_backends = ValidateInStrings(
  247. 'backend', all_backends, ignorecase=True)
  248. _auto_backend_sentinel = object()
  249. def validate_backend(s):
  250. backend = (
  251. s if s is _auto_backend_sentinel or s.startswith("module://")
  252. else _validate_standard_backends(s))
  253. return backend
  254. validate_toolbar = ValidateInStrings(
  255. 'toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True,
  256. _deprecated_since="3.3")
  257. @cbook.deprecated("3.3")
  258. def _make_nseq_validator(cls, n=None, allow_none=False):
  259. def validator(s):
  260. """Convert *n* objects using ``cls``, or raise."""
  261. if isinstance(s, str):
  262. s = [x.strip() for x in s.split(',')]
  263. if n is not None and len(s) != n:
  264. raise ValueError(
  265. f'Expected exactly {n} comma-separated values, '
  266. f'but got {len(s)} comma-separated values: {s}')
  267. else:
  268. if n is not None and len(s) != n:
  269. raise ValueError(
  270. f'Expected exactly {n} values, '
  271. f'but got {len(s)} values: {s}')
  272. try:
  273. return [cls(val) if not allow_none or val is not None else val
  274. for val in s]
  275. except ValueError as e:
  276. raise ValueError(
  277. f'Could not convert all entries to {cls.__name__}s') from e
  278. return validator
  279. @cbook.deprecated("3.3")
  280. def validate_nseq_float(n):
  281. return _make_nseq_validator(float, n)
  282. @cbook.deprecated("3.3")
  283. def validate_nseq_int(n):
  284. return _make_nseq_validator(int, n)
  285. def validate_color_or_inherit(s):
  286. """Return a valid color arg."""
  287. if cbook._str_equal(s, 'inherit'):
  288. return s
  289. return validate_color(s)
  290. def validate_color_or_auto(s):
  291. if cbook._str_equal(s, 'auto'):
  292. return s
  293. return validate_color(s)
  294. def validate_color_for_prop_cycle(s):
  295. # N-th color cycle syntax can't go into the color cycle.
  296. if isinstance(s, str) and re.match("^C[0-9]$", s):
  297. raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler")
  298. return validate_color(s)
  299. def validate_color(s):
  300. """Return a valid color arg."""
  301. if isinstance(s, str):
  302. if s.lower() == 'none':
  303. return 'none'
  304. if len(s) == 6 or len(s) == 8:
  305. stmp = '#' + s
  306. if is_color_like(stmp):
  307. return stmp
  308. if is_color_like(s):
  309. return s
  310. # If it is still valid, it must be a tuple (as a string from matplotlibrc).
  311. try:
  312. color = ast.literal_eval(s)
  313. except (SyntaxError, ValueError):
  314. pass
  315. else:
  316. if is_color_like(color):
  317. return color
  318. raise ValueError(f'{s!r} does not look like a color arg')
  319. validate_colorlist = _listify_validator(
  320. validate_color, allow_stringlist=True, doc='return a list of colorspecs')
  321. validate_orientation = ValidateInStrings(
  322. 'orientation', ['landscape', 'portrait'], _deprecated_since="3.3")
  323. def validate_aspect(s):
  324. if s in ('auto', 'equal'):
  325. return s
  326. try:
  327. return float(s)
  328. except ValueError as e:
  329. raise ValueError('not a valid aspect specification') from e
  330. def validate_fontsize_None(s):
  331. if s is None or s == 'None':
  332. return None
  333. else:
  334. return validate_fontsize(s)
  335. def validate_fontsize(s):
  336. fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
  337. 'x-large', 'xx-large', 'smaller', 'larger']
  338. if isinstance(s, str):
  339. s = s.lower()
  340. if s in fontsizes:
  341. return s
  342. try:
  343. return float(s)
  344. except ValueError as e:
  345. raise ValueError("%s is not a valid font size. Valid font sizes "
  346. "are %s." % (s, ", ".join(fontsizes))) from e
  347. validate_fontsizelist = _listify_validator(validate_fontsize)
  348. def validate_fontweight(s):
  349. weights = [
  350. 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman',
  351. 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black']
  352. # Note: Historically, weights have been case-sensitive in Matplotlib
  353. if s in weights:
  354. return s
  355. try:
  356. return int(s)
  357. except (ValueError, TypeError) as e:
  358. raise ValueError(f'{s} is not a valid font weight.') from e
  359. def validate_font_properties(s):
  360. parse_fontconfig_pattern(s)
  361. return s
  362. def _validate_mathtext_fallback_to_cm(b):
  363. """
  364. Temporary validate for fallback_to_cm, while deprecated
  365. """
  366. if isinstance(b, str):
  367. b = b.lower()
  368. if b is None or b == 'none':
  369. return None
  370. else:
  371. cbook.warn_deprecated(
  372. "3.3", message="Support for setting the 'mathtext.fallback_to_cm' "
  373. "rcParam is deprecated since %(since)s and will be removed "
  374. "%(removal)s; use 'mathtext.fallback : 'cm' instead.")
  375. return validate_bool_maybe_none(b)
  376. def _validate_mathtext_fallback(s):
  377. _fallback_fonts = ['cm', 'stix', 'stixsans']
  378. if isinstance(s, str):
  379. s = s.lower()
  380. if s is None or s == 'none':
  381. return None
  382. elif s.lower() in _fallback_fonts:
  383. return s
  384. else:
  385. raise ValueError(
  386. f"{s} is not a valid fallback font name. Valid fallback font "
  387. f"names are {','.join(_fallback_fonts)}. Passing 'None' will turn "
  388. "fallback off.")
  389. validate_fontset = ValidateInStrings(
  390. 'fontset',
  391. ['dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans', 'custom'],
  392. _deprecated_since="3.3")
  393. validate_mathtext_default = ValidateInStrings(
  394. 'default', "rm cal it tt sf bf default bb frak scr regular".split(),
  395. _deprecated_since="3.3")
  396. _validate_alignment = ValidateInStrings(
  397. 'alignment',
  398. ['center', 'top', 'bottom', 'baseline', 'center_baseline'],
  399. _deprecated_since="3.3")
  400. def validate_whiskers(s):
  401. if s == 'range':
  402. cbook.warn_deprecated(
  403. "3.2", message="Support for setting the boxplot.whiskers rcParam "
  404. "to 'range' is deprecated since %(since)s and will be removed "
  405. "%(removal)s; set it to 0, 100 instead.")
  406. return 'range'
  407. else:
  408. try:
  409. return _listify_validator(validate_float, n=2)(s)
  410. except (TypeError, ValueError):
  411. try:
  412. return float(s)
  413. except ValueError as e:
  414. raise ValueError("Not a valid whisker value ['range', float, "
  415. "(float, float)]") from e
  416. @cbook.deprecated("3.2")
  417. def update_savefig_format(value):
  418. # The old savefig.extension could also have a value of "auto", but
  419. # the new savefig.format does not. We need to fix this here.
  420. value = validate_string(value)
  421. if value == 'auto':
  422. cbook.warn_deprecated(
  423. "3.2", message="Support for setting the 'savefig.format' rcParam "
  424. "to 'auto' is deprecated since %(since)s and will be removed "
  425. "%(removal)s; set it to 'png' instead.")
  426. value = 'png'
  427. return value
  428. # Replace by validate_string once deprecation period passes.
  429. def _update_savefig_format(value):
  430. # The old savefig.extension could also have a value of "auto", but
  431. # the new savefig.format does not. We need to fix this here.
  432. value = validate_string(value)
  433. if value == 'auto':
  434. cbook.warn_deprecated(
  435. "3.2", message="Support for setting the 'savefig.format' rcParam "
  436. "to 'auto' is deprecated since %(since)s and will be removed "
  437. "%(removal)s; set it to 'png' instead.")
  438. value = 'png'
  439. return value
  440. validate_ps_papersize = ValidateInStrings(
  441. 'ps_papersize',
  442. ['auto', 'letter', 'legal', 'ledger',
  443. 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10',
  444. 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10',
  445. ], ignorecase=True, _deprecated_since="3.3")
  446. def validate_ps_distiller(s):
  447. if isinstance(s, str):
  448. s = s.lower()
  449. if s in ('none', None, 'false', False):
  450. return None
  451. else:
  452. return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s)
  453. # A validator dedicated to the named line styles, based on the items in
  454. # ls_mapper, and a list of possible strings read from Line2D.set_linestyle
  455. _validate_named_linestyle = ValidateInStrings(
  456. 'linestyle',
  457. [*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''],
  458. ignorecase=True)
  459. def _validate_linestyle(ls):
  460. """
  461. A validator for all possible line styles, the named ones *and*
  462. the on-off ink sequences.
  463. """
  464. if isinstance(ls, str):
  465. try: # Look first for a valid named line style, like '--' or 'solid'.
  466. return _validate_named_linestyle(ls)
  467. except ValueError:
  468. pass
  469. try:
  470. ls = ast.literal_eval(ls) # Parsing matplotlibrc.
  471. except (SyntaxError, ValueError):
  472. pass # Will error with the ValueError at the end.
  473. def _is_iterable_not_string_like(x):
  474. # Explicitly exclude bytes/bytearrays so that they are not
  475. # nonsensically interpreted as sequences of numbers (codepoints).
  476. return np.iterable(x) and not isinstance(x, (str, bytes, bytearray))
  477. # (offset, (on, off, on, off, ...))
  478. if (_is_iterable_not_string_like(ls)
  479. and len(ls) == 2
  480. and isinstance(ls[0], (type(None), Number))
  481. and _is_iterable_not_string_like(ls[1])
  482. and len(ls[1]) % 2 == 0
  483. and all(isinstance(elem, Number) for elem in ls[1])):
  484. if ls[0] is None:
  485. cbook.warn_deprecated(
  486. "3.3", message="Passing the dash offset as None is deprecated "
  487. "since %(since)s and support for it will be removed "
  488. "%(removal)s; pass it as zero instead.")
  489. ls = (0, ls[1])
  490. return ls
  491. # For backcompat: (on, off, on, off, ...); the offset is implicitly None.
  492. if (_is_iterable_not_string_like(ls)
  493. and len(ls) % 2 == 0
  494. and all(isinstance(elem, Number) for elem in ls)):
  495. return (0, ls)
  496. raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.")
  497. def _deprecate_case_insensitive_join_cap(s):
  498. s_low = s.lower()
  499. if s != s_low:
  500. if s_low in ['miter', 'round', 'bevel']:
  501. cbook.warn_deprecated(
  502. "3.3", message="Case-insensitive capstyles are deprecated "
  503. "since %(since)s and support for them will be removed "
  504. "%(removal)s; please pass them in lowercase.")
  505. elif s_low in ['butt', 'round', 'projecting']:
  506. cbook.warn_deprecated(
  507. "3.3", message="Case-insensitive joinstyles are deprecated "
  508. "since %(since)s and support for them will be removed "
  509. "%(removal)s; please pass them in lowercase.")
  510. # Else, error out at the check_in_list stage.
  511. return s_low
  512. def validate_joinstyle(s):
  513. s = _deprecate_case_insensitive_join_cap(s)
  514. cbook._check_in_list(['miter', 'round', 'bevel'], joinstyle=s)
  515. return s
  516. def validate_capstyle(s):
  517. s = _deprecate_case_insensitive_join_cap(s)
  518. cbook._check_in_list(['butt', 'round', 'projecting'], capstyle=s)
  519. return s
  520. validate_fillstyle = ValidateInStrings(
  521. 'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none'])
  522. validate_joinstylelist = _listify_validator(validate_joinstyle)
  523. validate_capstylelist = _listify_validator(validate_capstyle)
  524. validate_fillstylelist = _listify_validator(validate_fillstyle)
  525. def validate_markevery(s):
  526. """
  527. Validate the markevery property of a Line2D object.
  528. Parameters
  529. ----------
  530. s : None, int, float, slice, length-2 tuple of ints,
  531. length-2 tuple of floats, list of ints
  532. Returns
  533. -------
  534. None, int, float, slice, length-2 tuple of ints,
  535. length-2 tuple of floats, list of ints
  536. """
  537. # Validate s against type slice float int and None
  538. if isinstance(s, (slice, float, int, type(None))):
  539. return s
  540. # Validate s against type tuple
  541. if isinstance(s, tuple):
  542. if (len(s) == 2
  543. and (all(isinstance(e, int) for e in s)
  544. or all(isinstance(e, float) for e in s))):
  545. return s
  546. else:
  547. raise TypeError(
  548. "'markevery' tuple must be pair of ints or of floats")
  549. # Validate s against type list
  550. if isinstance(s, list):
  551. if all(isinstance(e, int) for e in s):
  552. return s
  553. else:
  554. raise TypeError(
  555. "'markevery' list must have all elements of type int")
  556. raise TypeError("'markevery' is of an invalid type")
  557. validate_markeverylist = _listify_validator(validate_markevery)
  558. validate_legend_loc = ValidateInStrings(
  559. 'legend_loc',
  560. ['best',
  561. 'upper right',
  562. 'upper left',
  563. 'lower left',
  564. 'lower right',
  565. 'right',
  566. 'center left',
  567. 'center right',
  568. 'lower center',
  569. 'upper center',
  570. 'center'], ignorecase=True, _deprecated_since="3.3")
  571. validate_svg_fonttype = ValidateInStrings(
  572. 'svg.fonttype', ['none', 'path'], _deprecated_since="3.3")
  573. @cbook.deprecated("3.3")
  574. def validate_hinting(s):
  575. return _validate_hinting(s)
  576. # Replace by plain list in _prop_validators after deprecation period.
  577. def _validate_hinting(s):
  578. if s in (True, False):
  579. cbook.warn_deprecated(
  580. "3.2", message="Support for setting the text.hinting rcParam to "
  581. "True or False is deprecated since %(since)s and will be removed "
  582. "%(removal)s; set it to its synonyms 'auto' or 'none' instead.")
  583. return s
  584. return ValidateInStrings(
  585. 'text.hinting',
  586. ['default', 'no_autohint', 'force_autohint', 'no_hinting',
  587. 'auto', 'native', 'either', 'none'],
  588. ignorecase=True)(s)
  589. validate_pgf_texsystem = ValidateInStrings(
  590. 'pgf.texsystem', ['xelatex', 'lualatex', 'pdflatex'],
  591. _deprecated_since="3.3")
  592. @cbook.deprecated("3.3")
  593. def validate_movie_writer(s):
  594. # writers.list() would only list actually available writers, but
  595. # FFMpeg.isAvailable is slow and not worth paying for at every import.
  596. if s in animation.writers._registered:
  597. return s
  598. else:
  599. raise ValueError(f"Supported animation writers are "
  600. f"{sorted(animation.writers._registered)}")
  601. validate_movie_frame_fmt = ValidateInStrings(
  602. 'animation.frame_format', ['png', 'jpeg', 'tiff', 'raw', 'rgba'],
  603. _deprecated_since="3.3")
  604. validate_axis_locator = ValidateInStrings(
  605. 'major', ['minor', 'both', 'major'], _deprecated_since="3.3")
  606. validate_movie_html_fmt = ValidateInStrings(
  607. 'animation.html', ['html5', 'jshtml', 'none'], _deprecated_since="3.3")
  608. def validate_bbox(s):
  609. if isinstance(s, str):
  610. s = s.lower()
  611. if s == 'tight':
  612. return s
  613. if s == 'standard':
  614. return None
  615. raise ValueError("bbox should be 'tight' or 'standard'")
  616. elif s is not None:
  617. # Backwards compatibility. None is equivalent to 'standard'.
  618. raise ValueError("bbox should be 'tight' or 'standard'")
  619. return s
  620. def validate_sketch(s):
  621. if isinstance(s, str):
  622. s = s.lower()
  623. if s == 'none' or s is None:
  624. return None
  625. try:
  626. return tuple(_listify_validator(validate_float, n=3)(s))
  627. except ValueError:
  628. raise ValueError("Expected a (scale, length, randomness) triplet")
  629. def _validate_greaterequal0_lessthan1(s):
  630. s = validate_float(s)
  631. if 0 <= s < 1:
  632. return s
  633. else:
  634. raise RuntimeError(f'Value must be >=0 and <1; got {s}')
  635. def _validate_greaterequal0_lessequal1(s):
  636. s = validate_float(s)
  637. if 0 <= s <= 1:
  638. return s
  639. else:
  640. raise RuntimeError(f'Value must be >=0 and <=1; got {s}')
  641. _range_validators = { # Slightly nicer (internal) API.
  642. "0 <= x < 1": _validate_greaterequal0_lessthan1,
  643. "0 <= x <= 1": _validate_greaterequal0_lessequal1,
  644. }
  645. validate_grid_axis = ValidateInStrings(
  646. 'axes.grid.axis', ['x', 'y', 'both'], _deprecated_since="3.3")
  647. def validate_hatch(s):
  648. r"""
  649. Validate a hatch pattern.
  650. A hatch pattern string can have any sequence of the following
  651. characters: ``\ / | - + * . x o O``.
  652. """
  653. if not isinstance(s, str):
  654. raise ValueError("Hatch pattern must be a string")
  655. cbook._check_isinstance(str, hatch_pattern=s)
  656. unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
  657. if unknown:
  658. raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
  659. return s
  660. validate_hatchlist = _listify_validator(validate_hatch)
  661. validate_dashlist = _listify_validator(validate_floatlist)
  662. _prop_validators = {
  663. 'color': _listify_validator(validate_color_for_prop_cycle,
  664. allow_stringlist=True),
  665. 'linewidth': validate_floatlist,
  666. 'linestyle': _listify_validator(_validate_linestyle),
  667. 'facecolor': validate_colorlist,
  668. 'edgecolor': validate_colorlist,
  669. 'joinstyle': validate_joinstylelist,
  670. 'capstyle': validate_capstylelist,
  671. 'fillstyle': validate_fillstylelist,
  672. 'markerfacecolor': validate_colorlist,
  673. 'markersize': validate_floatlist,
  674. 'markeredgewidth': validate_floatlist,
  675. 'markeredgecolor': validate_colorlist,
  676. 'markevery': validate_markeverylist,
  677. 'alpha': validate_floatlist,
  678. 'marker': validate_stringlist,
  679. 'hatch': validate_hatchlist,
  680. 'dashes': validate_dashlist,
  681. }
  682. _prop_aliases = {
  683. 'c': 'color',
  684. 'lw': 'linewidth',
  685. 'ls': 'linestyle',
  686. 'fc': 'facecolor',
  687. 'ec': 'edgecolor',
  688. 'mfc': 'markerfacecolor',
  689. 'mec': 'markeredgecolor',
  690. 'mew': 'markeredgewidth',
  691. 'ms': 'markersize',
  692. }
  693. def cycler(*args, **kwargs):
  694. """
  695. Create a `~cycler.Cycler` object much like :func:`cycler.cycler`,
  696. but includes input validation.
  697. Call signatures::
  698. cycler(cycler)
  699. cycler(label=values[, label2=values2[, ...]])
  700. cycler(label, values)
  701. Form 1 copies a given `~cycler.Cycler` object.
  702. Form 2 creates a `~cycler.Cycler` which cycles over one or more
  703. properties simultaneously. If multiple properties are given, their
  704. value lists must have the same length.
  705. Form 3 creates a `~cycler.Cycler` for a single property. This form
  706. exists for compatibility with the original cycler. Its use is
  707. discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``.
  708. Parameters
  709. ----------
  710. cycler : Cycler
  711. Copy constructor for Cycler.
  712. label : str
  713. The property key. Must be a valid `.Artist` property.
  714. For example, 'color' or 'linestyle'. Aliases are allowed,
  715. such as 'c' for 'color' and 'lw' for 'linewidth'.
  716. values : iterable
  717. Finite-length iterable of the property values. These values
  718. are validated and will raise a ValueError if invalid.
  719. Returns
  720. -------
  721. Cycler
  722. A new :class:`~cycler.Cycler` for the given properties.
  723. Examples
  724. --------
  725. Creating a cycler for a single property:
  726. >>> c = cycler(color=['red', 'green', 'blue'])
  727. Creating a cycler for simultaneously cycling over multiple properties
  728. (e.g. red circle, green plus, blue cross):
  729. >>> c = cycler(color=['red', 'green', 'blue'],
  730. ... marker=['o', '+', 'x'])
  731. """
  732. if args and kwargs:
  733. raise TypeError("cycler() can only accept positional OR keyword "
  734. "arguments -- not both.")
  735. elif not args and not kwargs:
  736. raise TypeError("cycler() must have positional OR keyword arguments")
  737. if len(args) == 1:
  738. if not isinstance(args[0], Cycler):
  739. raise TypeError("If only one positional argument given, it must "
  740. " be a Cycler instance.")
  741. return validate_cycler(args[0])
  742. elif len(args) == 2:
  743. pairs = [(args[0], args[1])]
  744. elif len(args) > 2:
  745. raise TypeError("No more than 2 positional arguments allowed")
  746. else:
  747. pairs = kwargs.items()
  748. validated = []
  749. for prop, vals in pairs:
  750. norm_prop = _prop_aliases.get(prop, prop)
  751. validator = _prop_validators.get(norm_prop, None)
  752. if validator is None:
  753. raise TypeError("Unknown artist property: %s" % prop)
  754. vals = validator(vals)
  755. # We will normalize the property names as well to reduce
  756. # the amount of alias handling code elsewhere.
  757. validated.append((norm_prop, vals))
  758. return reduce(operator.add, (ccycler(k, v) for k, v in validated))
  759. def validate_cycler(s):
  760. """Return a Cycler object from a string repr or the object itself."""
  761. if isinstance(s, str):
  762. # TODO: We might want to rethink this...
  763. # While I think I have it quite locked down, it is execution of
  764. # arbitrary code without sanitation.
  765. # Combine this with the possibility that rcparams might come from the
  766. # internet (future plans), this could be downright dangerous.
  767. # I locked it down by only having the 'cycler()' function available.
  768. # UPDATE: Partly plugging a security hole.
  769. # I really should have read this:
  770. # http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
  771. # We should replace this eval with a combo of PyParsing and
  772. # ast.literal_eval()
  773. try:
  774. if '.__' in s.replace(' ', ''):
  775. raise ValueError("'%s' seems to have dunder methods. Raising"
  776. " an exception for your safety")
  777. s = eval(s, {'cycler': cycler, '__builtins__': {}})
  778. except BaseException as e:
  779. raise ValueError("'%s' is not a valid cycler construction: %s" %
  780. (s, e)) from e
  781. # Should make sure what comes from the above eval()
  782. # is a Cycler object.
  783. if isinstance(s, Cycler):
  784. cycler_inst = s
  785. else:
  786. raise ValueError("object was not a string or Cycler instance: %s" % s)
  787. unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
  788. if unknowns:
  789. raise ValueError("Unknown artist properties: %s" % unknowns)
  790. # Not a full validation, but it'll at least normalize property names
  791. # A fuller validation would require v0.10 of cycler.
  792. checker = set()
  793. for prop in cycler_inst.keys:
  794. norm_prop = _prop_aliases.get(prop, prop)
  795. if norm_prop != prop and norm_prop in cycler_inst.keys:
  796. raise ValueError("Cannot specify both '{0}' and alias '{1}'"
  797. " in the same prop_cycle".format(norm_prop, prop))
  798. if norm_prop in checker:
  799. raise ValueError("Another property was already aliased to '{0}'."
  800. " Collision normalizing '{1}'.".format(norm_prop,
  801. prop))
  802. checker.update([norm_prop])
  803. # This is just an extra-careful check, just in case there is some
  804. # edge-case I haven't thought of.
  805. assert len(checker) == len(cycler_inst.keys)
  806. # Now, it should be safe to mutate this cycler
  807. for prop in cycler_inst.keys:
  808. norm_prop = _prop_aliases.get(prop, prop)
  809. cycler_inst.change_key(prop, norm_prop)
  810. for key, vals in cycler_inst.by_key().items():
  811. _prop_validators[key](vals)
  812. return cycler_inst
  813. def validate_hist_bins(s):
  814. valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"]
  815. if isinstance(s, str) and s in valid_strs:
  816. return s
  817. try:
  818. return int(s)
  819. except (TypeError, ValueError):
  820. pass
  821. try:
  822. return validate_floatlist(s)
  823. except ValueError:
  824. pass
  825. raise ValueError("'hist.bins' must be one of {}, an int or"
  826. " a sequence of floats".format(valid_strs))
  827. @cbook.deprecated("3.2")
  828. def validate_animation_writer_path(p):
  829. # Make sure it's a string and then figure out if the animations
  830. # are already loaded and reset the writers (which will validate
  831. # the path on next call)
  832. cbook._check_isinstance(str, path=p)
  833. from sys import modules
  834. # set dirty, so that the next call to the registry will re-evaluate
  835. # the state.
  836. # only set dirty if already loaded. If not loaded, the load will
  837. # trigger the checks.
  838. if "matplotlib.animation" in modules:
  839. modules["matplotlib.animation"].writers.set_dirty()
  840. return p
  841. @cbook.deprecated("3.3")
  842. def validate_webagg_address(s):
  843. if s is not None:
  844. import socket
  845. try:
  846. socket.inet_aton(s)
  847. except socket.error as e:
  848. raise ValueError(
  849. "'webagg.address' is not a valid IP address") from e
  850. return s
  851. raise ValueError("'webagg.address' is not a valid IP address")
  852. validate_axes_titlelocation = ValidateInStrings(
  853. 'axes.titlelocation', ['left', 'center', 'right'], _deprecated_since="3.3")
  854. class _ignorecase(list):
  855. """A marker class indicating that a list-of-str is case-insensitive."""
  856. def _convert_validator_spec(key, conv):
  857. if isinstance(conv, list):
  858. ignorecase = isinstance(conv, _ignorecase)
  859. return ValidateInStrings(key, conv, ignorecase=ignorecase)
  860. else:
  861. return conv
  862. # Mapping of rcParams to validators.
  863. # Converters given as lists or _ignorecase are converted to ValidateInStrings
  864. # immediately below.
  865. # The rcParams defaults are defined in matplotlibrc.template, which gets copied
  866. # to matplotlib/mpl-data/matplotlibrc by the setup script.
  867. _validators = {
  868. "backend": validate_backend,
  869. "backend_fallback": validate_bool,
  870. "toolbar": _ignorecase(["none", "toolbar2", "toolmanager"]),
  871. "datapath": validate_any, # see _get_data_path_cached
  872. "interactive": validate_bool,
  873. "timezone": validate_string,
  874. "webagg.port": validate_int,
  875. "webagg.address": validate_string,
  876. "webagg.open_in_browser": validate_bool,
  877. "webagg.port_retries": validate_int,
  878. # line props
  879. "lines.linewidth": validate_float, # line width in points
  880. "lines.linestyle": _validate_linestyle, # solid line
  881. "lines.color": validate_color, # first color in color cycle
  882. "lines.marker": validate_string, # marker name
  883. "lines.markerfacecolor": validate_color_or_auto, # default color
  884. "lines.markeredgecolor": validate_color_or_auto, # default color
  885. "lines.markeredgewidth": validate_float,
  886. "lines.markersize": validate_float, # markersize, in points
  887. "lines.antialiased": validate_bool, # antialiased (no jaggies)
  888. "lines.dash_joinstyle": validate_joinstyle,
  889. "lines.solid_joinstyle": validate_joinstyle,
  890. "lines.dash_capstyle": validate_capstyle,
  891. "lines.solid_capstyle": validate_capstyle,
  892. "lines.dashed_pattern": validate_floatlist,
  893. "lines.dashdot_pattern": validate_floatlist,
  894. "lines.dotted_pattern": validate_floatlist,
  895. "lines.scale_dashes": validate_bool,
  896. # marker props
  897. "markers.fillstyle": validate_fillstyle,
  898. ## pcolor(mesh) props:
  899. "pcolor.shading": ["auto", "flat", "nearest", "gouraud"],
  900. ## patch props
  901. "patch.linewidth": validate_float, # line width in points
  902. "patch.edgecolor": validate_color,
  903. "patch.force_edgecolor": validate_bool,
  904. "patch.facecolor": validate_color, # first color in cycle
  905. "patch.antialiased": validate_bool, # antialiased (no jaggies)
  906. ## hatch props
  907. "hatch.color": validate_color,
  908. "hatch.linewidth": validate_float,
  909. ## Histogram properties
  910. "hist.bins": validate_hist_bins,
  911. ## Boxplot properties
  912. "boxplot.notch": validate_bool,
  913. "boxplot.vertical": validate_bool,
  914. "boxplot.whiskers": validate_whiskers,
  915. "boxplot.bootstrap": validate_int_or_None,
  916. "boxplot.patchartist": validate_bool,
  917. "boxplot.showmeans": validate_bool,
  918. "boxplot.showcaps": validate_bool,
  919. "boxplot.showbox": validate_bool,
  920. "boxplot.showfliers": validate_bool,
  921. "boxplot.meanline": validate_bool,
  922. "boxplot.flierprops.color": validate_color,
  923. "boxplot.flierprops.marker": validate_string,
  924. "boxplot.flierprops.markerfacecolor": validate_color_or_auto,
  925. "boxplot.flierprops.markeredgecolor": validate_color,
  926. "boxplot.flierprops.markeredgewidth": validate_float,
  927. "boxplot.flierprops.markersize": validate_float,
  928. "boxplot.flierprops.linestyle": _validate_linestyle,
  929. "boxplot.flierprops.linewidth": validate_float,
  930. "boxplot.boxprops.color": validate_color,
  931. "boxplot.boxprops.linewidth": validate_float,
  932. "boxplot.boxprops.linestyle": _validate_linestyle,
  933. "boxplot.whiskerprops.color": validate_color,
  934. "boxplot.whiskerprops.linewidth": validate_float,
  935. "boxplot.whiskerprops.linestyle": _validate_linestyle,
  936. "boxplot.capprops.color": validate_color,
  937. "boxplot.capprops.linewidth": validate_float,
  938. "boxplot.capprops.linestyle": _validate_linestyle,
  939. "boxplot.medianprops.color": validate_color,
  940. "boxplot.medianprops.linewidth": validate_float,
  941. "boxplot.medianprops.linestyle": _validate_linestyle,
  942. "boxplot.meanprops.color": validate_color,
  943. "boxplot.meanprops.marker": validate_string,
  944. "boxplot.meanprops.markerfacecolor": validate_color,
  945. "boxplot.meanprops.markeredgecolor": validate_color,
  946. "boxplot.meanprops.markersize": validate_float,
  947. "boxplot.meanprops.linestyle": _validate_linestyle,
  948. "boxplot.meanprops.linewidth": validate_float,
  949. ## font props
  950. "font.family": validate_stringlist, # used by text object
  951. "font.style": validate_string,
  952. "font.variant": validate_string,
  953. "font.stretch": validate_string,
  954. "font.weight": validate_fontweight,
  955. "font.size": validate_float, # Base font size in points
  956. "font.serif": validate_stringlist,
  957. "font.sans-serif": validate_stringlist,
  958. "font.cursive": validate_stringlist,
  959. "font.fantasy": validate_stringlist,
  960. "font.monospace": validate_stringlist,
  961. # text props
  962. "text.color": validate_color,
  963. "text.usetex": validate_bool,
  964. "text.latex.preamble": _validate_tex_preamble,
  965. "text.latex.preview": validate_bool,
  966. "text.hinting": _validate_hinting,
  967. "text.hinting_factor": validate_int,
  968. "text.kerning_factor": validate_int,
  969. "text.antialiased": validate_bool,
  970. "mathtext.cal": validate_font_properties,
  971. "mathtext.rm": validate_font_properties,
  972. "mathtext.tt": validate_font_properties,
  973. "mathtext.it": validate_font_properties,
  974. "mathtext.bf": validate_font_properties,
  975. "mathtext.sf": validate_font_properties,
  976. "mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix",
  977. "stixsans", "custom"],
  978. "mathtext.default": ["rm", "cal", "it", "tt", "sf", "bf", "default",
  979. "bb", "frak", "scr", "regular"],
  980. "mathtext.fallback_to_cm": _validate_mathtext_fallback_to_cm,
  981. "mathtext.fallback": _validate_mathtext_fallback,
  982. "image.aspect": validate_aspect, # equal, auto, a number
  983. "image.interpolation": validate_string,
  984. "image.cmap": validate_string, # gray, jet, etc.
  985. "image.lut": validate_int, # lookup table
  986. "image.origin": ["upper", "lower"],
  987. "image.resample": validate_bool,
  988. # Specify whether vector graphics backends will combine all images on a
  989. # set of axes into a single composite image
  990. "image.composite_image": validate_bool,
  991. # contour props
  992. "contour.negative_linestyle": _validate_linestyle,
  993. "contour.corner_mask": validate_bool,
  994. "contour.linewidth": validate_float_or_None,
  995. # errorbar props
  996. "errorbar.capsize": validate_float,
  997. # axis props
  998. # alignment of x/y axis title
  999. "xaxis.labellocation": ["left", "center", "right"],
  1000. "yaxis.labellocation": ["bottom", "center", "top"],
  1001. # axes props
  1002. "axes.axisbelow": validate_axisbelow,
  1003. "axes.facecolor": validate_color, # background color
  1004. "axes.edgecolor": validate_color, # edge color
  1005. "axes.linewidth": validate_float, # edge linewidth
  1006. "axes.spines.left": validate_bool, # Set visibility of axes spines,
  1007. "axes.spines.right": validate_bool, # i.e., the lines around the chart
  1008. "axes.spines.bottom": validate_bool, # denoting data boundary.
  1009. "axes.spines.top": validate_bool,
  1010. "axes.titlesize": validate_fontsize, # axes title fontsize
  1011. "axes.titlelocation": ["left", "center", "right"], # axes title alignment
  1012. "axes.titleweight": validate_fontweight, # axes title font weight
  1013. "axes.titlecolor": validate_color_or_auto, # axes title font color
  1014. # title location, axes units, None means auto
  1015. "axes.titley": validate_float_or_None,
  1016. # pad from axes top decoration to title in points
  1017. "axes.titlepad": validate_float,
  1018. "axes.grid": validate_bool, # display grid or not
  1019. "axes.grid.which": ["minor", "both", "major"], # which grids are drawn
  1020. "axes.grid.axis": ["x", "y", "both"], # grid type
  1021. "axes.labelsize": validate_fontsize, # fontsize of x & y labels
  1022. "axes.labelpad": validate_float, # space between label and axis
  1023. "axes.labelweight": validate_fontweight, # fontsize of x & y labels
  1024. "axes.labelcolor": validate_color, # color of axis label
  1025. # use scientific notation if log10 of the axis range is smaller than the
  1026. # first or larger than the second
  1027. "axes.formatter.limits": _listify_validator(validate_int, n=2),
  1028. # use current locale to format ticks
  1029. "axes.formatter.use_locale": validate_bool,
  1030. "axes.formatter.use_mathtext": validate_bool,
  1031. # minimum exponent to format in scientific notation
  1032. "axes.formatter.min_exponent": validate_int,
  1033. "axes.formatter.useoffset": validate_bool,
  1034. "axes.formatter.offset_threshold": validate_int,
  1035. "axes.unicode_minus": validate_bool,
  1036. # This entry can be either a cycler object or a string repr of a
  1037. # cycler-object, which gets eval()'ed to create the object.
  1038. "axes.prop_cycle": validate_cycler,
  1039. # If "data", axes limits are set close to the data.
  1040. # If "round_numbers" axes limits are set to the nearest round numbers.
  1041. "axes.autolimit_mode": ["data", "round_numbers"],
  1042. "axes.xmargin": _range_validators["0 <= x <= 1"], # margin added to xaxis
  1043. "axes.ymargin": _range_validators["0 <= x <= 1"], # margin added to yaxis
  1044. "polaraxes.grid": validate_bool, # display polar grid or not
  1045. "axes3d.grid": validate_bool, # display 3d grid
  1046. # scatter props
  1047. "scatter.marker": validate_string,
  1048. "scatter.edgecolors": validate_string,
  1049. "date.epoch": _validate_date,
  1050. "date.autoformatter.year": validate_string,
  1051. "date.autoformatter.month": validate_string,
  1052. "date.autoformatter.day": validate_string,
  1053. "date.autoformatter.hour": validate_string,
  1054. "date.autoformatter.minute": validate_string,
  1055. "date.autoformatter.second": validate_string,
  1056. "date.autoformatter.microsecond": validate_string,
  1057. # legend properties
  1058. "legend.fancybox": validate_bool,
  1059. "legend.loc": _ignorecase([
  1060. "best",
  1061. "upper right", "upper left", "lower left", "lower right", "right",
  1062. "center left", "center right", "lower center", "upper center",
  1063. "center"]),
  1064. # the number of points in the legend line
  1065. "legend.numpoints": validate_int,
  1066. # the number of points in the legend line for scatter
  1067. "legend.scatterpoints": validate_int,
  1068. "legend.fontsize": validate_fontsize,
  1069. "legend.title_fontsize": validate_fontsize_None,
  1070. # the relative size of legend markers vs. original
  1071. "legend.markerscale": validate_float,
  1072. "legend.shadow": validate_bool,
  1073. # whether or not to draw a frame around legend
  1074. "legend.frameon": validate_bool,
  1075. # alpha value of the legend frame
  1076. "legend.framealpha": validate_float_or_None,
  1077. ## the following dimensions are in fraction of the font size
  1078. "legend.borderpad": validate_float, # units are fontsize
  1079. # the vertical space between the legend entries
  1080. "legend.labelspacing": validate_float,
  1081. # the length of the legend lines
  1082. "legend.handlelength": validate_float,
  1083. # the length of the legend lines
  1084. "legend.handleheight": validate_float,
  1085. # the space between the legend line and legend text
  1086. "legend.handletextpad": validate_float,
  1087. # the border between the axes and legend edge
  1088. "legend.borderaxespad": validate_float,
  1089. # the border between the axes and legend edge
  1090. "legend.columnspacing": validate_float,
  1091. "legend.facecolor": validate_color_or_inherit,
  1092. "legend.edgecolor": validate_color_or_inherit,
  1093. # tick properties
  1094. "xtick.top": validate_bool, # draw ticks on top side
  1095. "xtick.bottom": validate_bool, # draw ticks on bottom side
  1096. "xtick.labeltop": validate_bool, # draw label on top
  1097. "xtick.labelbottom": validate_bool, # draw label on bottom
  1098. "xtick.major.size": validate_float, # major xtick size in points
  1099. "xtick.minor.size": validate_float, # minor xtick size in points
  1100. "xtick.major.width": validate_float, # major xtick width in points
  1101. "xtick.minor.width": validate_float, # minor xtick width in points
  1102. "xtick.major.pad": validate_float, # distance to label in points
  1103. "xtick.minor.pad": validate_float, # distance to label in points
  1104. "xtick.color": validate_color, # color of xtick labels
  1105. "xtick.minor.visible": validate_bool, # visibility of minor xticks
  1106. "xtick.minor.top": validate_bool, # draw top minor xticks
  1107. "xtick.minor.bottom": validate_bool, # draw bottom minor xticks
  1108. "xtick.major.top": validate_bool, # draw top major xticks
  1109. "xtick.major.bottom": validate_bool, # draw bottom major xticks
  1110. "xtick.labelsize": validate_fontsize, # fontsize of xtick labels
  1111. "xtick.direction": validate_string, # direction of xticks
  1112. "xtick.alignment": ["center", "right", "left"],
  1113. "ytick.left": validate_bool, # draw ticks on left side
  1114. "ytick.right": validate_bool, # draw ticks on right side
  1115. "ytick.labelleft": validate_bool, # draw tick labels on left side
  1116. "ytick.labelright": validate_bool, # draw tick labels on right side
  1117. "ytick.major.size": validate_float, # major ytick size in points
  1118. "ytick.minor.size": validate_float, # minor ytick size in points
  1119. "ytick.major.width": validate_float, # major ytick width in points
  1120. "ytick.minor.width": validate_float, # minor ytick width in points
  1121. "ytick.major.pad": validate_float, # distance to label in points
  1122. "ytick.minor.pad": validate_float, # distance to label in points
  1123. "ytick.color": validate_color, # color of ytick labels
  1124. "ytick.minor.visible": validate_bool, # visibility of minor yticks
  1125. "ytick.minor.left": validate_bool, # draw left minor yticks
  1126. "ytick.minor.right": validate_bool, # draw right minor yticks
  1127. "ytick.major.left": validate_bool, # draw left major yticks
  1128. "ytick.major.right": validate_bool, # draw right major yticks
  1129. "ytick.labelsize": validate_fontsize, # fontsize of ytick labels
  1130. "ytick.direction": validate_string, # direction of yticks
  1131. "ytick.alignment": [
  1132. "center", "top", "bottom", "baseline", "center_baseline"],
  1133. "grid.color": validate_color, # grid color
  1134. "grid.linestyle": _validate_linestyle, # solid
  1135. "grid.linewidth": validate_float, # in points
  1136. "grid.alpha": validate_float,
  1137. ## figure props
  1138. # figure title
  1139. "figure.titlesize": validate_fontsize,
  1140. "figure.titleweight": validate_fontweight,
  1141. # figure size in inches: width by height
  1142. "figure.figsize": _listify_validator(validate_float, n=2),
  1143. "figure.dpi": validate_float,
  1144. "figure.facecolor": validate_color,
  1145. "figure.edgecolor": validate_color,
  1146. "figure.frameon": validate_bool,
  1147. "figure.autolayout": validate_bool,
  1148. "figure.max_open_warning": validate_int,
  1149. "figure.raise_window": validate_bool,
  1150. "figure.subplot.left": _range_validators["0 <= x <= 1"],
  1151. "figure.subplot.right": _range_validators["0 <= x <= 1"],
  1152. "figure.subplot.bottom": _range_validators["0 <= x <= 1"],
  1153. "figure.subplot.top": _range_validators["0 <= x <= 1"],
  1154. "figure.subplot.wspace": _range_validators["0 <= x < 1"],
  1155. "figure.subplot.hspace": _range_validators["0 <= x < 1"],
  1156. "figure.constrained_layout.use": validate_bool, # run constrained_layout?
  1157. # wspace and hspace are fraction of adjacent subplots to use for space.
  1158. # Much smaller than above because we don't need room for the text.
  1159. "figure.constrained_layout.hspace": _range_validators["0 <= x < 1"],
  1160. "figure.constrained_layout.wspace": _range_validators["0 <= x < 1"],
  1161. # buffer around the axes, in inches.
  1162. 'figure.constrained_layout.h_pad': validate_float,
  1163. 'figure.constrained_layout.w_pad': validate_float,
  1164. ## Saving figure's properties
  1165. 'savefig.dpi': validate_dpi,
  1166. 'savefig.facecolor': validate_color_or_auto,
  1167. 'savefig.edgecolor': validate_color_or_auto,
  1168. 'savefig.orientation': ['landscape', 'portrait'],
  1169. 'savefig.jpeg_quality': validate_int,
  1170. "savefig.format": _update_savefig_format,
  1171. "savefig.bbox": validate_bbox, # "tight", or "standard" (= None)
  1172. "savefig.pad_inches": validate_float,
  1173. # default directory in savefig dialog box
  1174. "savefig.directory": validate_string,
  1175. "savefig.transparent": validate_bool,
  1176. "tk.window_focus": validate_bool, # Maintain shell focus for TkAgg
  1177. # Set the papersize/type
  1178. "ps.papersize": _ignorecase(["auto", "letter", "legal", "ledger",
  1179. *[f"{ab}{i}"
  1180. for ab in "ab" for i in range(11)]]),
  1181. "ps.useafm": validate_bool,
  1182. # use ghostscript or xpdf to distill ps output
  1183. "ps.usedistiller": validate_ps_distiller,
  1184. "ps.distiller.res": validate_int, # dpi
  1185. "ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
  1186. "pdf.compression": validate_int, # 0-9 compression level; 0 to disable
  1187. "pdf.inheritcolor": validate_bool, # skip color setting commands
  1188. # use only the 14 PDF core fonts embedded in every PDF viewing application
  1189. "pdf.use14corefonts": validate_bool,
  1190. "pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
  1191. "pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used
  1192. "pgf.rcfonts": validate_bool, # use mpl's rc settings for font config
  1193. "pgf.preamble": _validate_tex_preamble, # custom LaTeX preamble
  1194. # write raster image data into the svg file
  1195. "svg.image_inline": validate_bool,
  1196. "svg.fonttype": ["none", "path"], # save text as text ("none") or "paths"
  1197. "svg.hashsalt": validate_string_or_None,
  1198. # set this when you want to generate hardcopy docstring
  1199. "docstring.hardcopy": validate_bool,
  1200. "path.simplify": validate_bool,
  1201. "path.simplify_threshold": _range_validators["0 <= x <= 1"],
  1202. "path.snap": validate_bool,
  1203. "path.sketch": validate_sketch,
  1204. "path.effects": validate_anylist,
  1205. "agg.path.chunksize": validate_int, # 0 to disable chunking
  1206. # key-mappings (multi-character mappings should be a list/tuple)
  1207. "keymap.fullscreen": validate_stringlist,
  1208. "keymap.home": validate_stringlist,
  1209. "keymap.back": validate_stringlist,
  1210. "keymap.forward": validate_stringlist,
  1211. "keymap.pan": validate_stringlist,
  1212. "keymap.zoom": validate_stringlist,
  1213. "keymap.save": validate_stringlist,
  1214. "keymap.quit": validate_stringlist,
  1215. "keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q"
  1216. "keymap.grid": validate_stringlist,
  1217. "keymap.grid_minor": validate_stringlist,
  1218. "keymap.yscale": validate_stringlist,
  1219. "keymap.xscale": validate_stringlist,
  1220. "keymap.all_axes": validate_stringlist,
  1221. "keymap.help": validate_stringlist,
  1222. "keymap.copy": validate_stringlist,
  1223. # Animation settings
  1224. "animation.html": ["html5", "jshtml", "none"],
  1225. # Limit, in MB, of size of base64 encoded animation in HTML
  1226. # (i.e. IPython notebook)
  1227. "animation.embed_limit": validate_float,
  1228. "animation.writer": validate_string,
  1229. "animation.codec": validate_string,
  1230. "animation.bitrate": validate_int,
  1231. # Controls image format when frames are written to disk
  1232. "animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba"],
  1233. # Additional arguments for HTML writer
  1234. "animation.html_args": validate_stringlist,
  1235. # Path to ffmpeg binary. If just binary name, subprocess uses $PATH.
  1236. "animation.ffmpeg_path": validate_string,
  1237. # Additional arguments for ffmpeg movie writer (using pipes)
  1238. "animation.ffmpeg_args": validate_stringlist,
  1239. # Path to AVConv binary. If just binary name, subprocess uses $PATH.
  1240. "animation.avconv_path": validate_string,
  1241. # Additional arguments for avconv movie writer (using pipes)
  1242. "animation.avconv_args": validate_stringlist,
  1243. # Path to convert binary. If just binary name, subprocess uses $PATH.
  1244. "animation.convert_path": validate_string,
  1245. # Additional arguments for convert movie writer (using pipes)
  1246. "animation.convert_args": validate_stringlist,
  1247. "mpl_toolkits.legacy_colorbar": validate_bool,
  1248. # Classic (pre 2.0) compatibility mode
  1249. # This is used for things that are hard to make backward compatible
  1250. # with a sane rcParam alone. This does *not* turn on classic mode
  1251. # altogether. For that use `matplotlib.style.use("classic")`.
  1252. "_internal.classic_mode": validate_bool
  1253. }
  1254. _hardcoded_defaults = { # Defaults not inferred from matplotlibrc.template...
  1255. # ... because it can"t be:
  1256. "backend": _auto_backend_sentinel,
  1257. # ... because they are private:
  1258. "_internal.classic_mode": False,
  1259. # ... because they are deprecated:
  1260. "animation.avconv_path": "avconv",
  1261. "animation.avconv_args": [],
  1262. "animation.html_args": [],
  1263. "mathtext.fallback_to_cm": None,
  1264. "keymap.all_axes": ["a"],
  1265. "savefig.jpeg_quality": 95,
  1266. "text.latex.preview": False,
  1267. }
  1268. _validators = {k: _convert_validator_spec(k, conv)
  1269. for k, conv in _validators.items()}