scale.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. """
  2. Scales define the distribution of data values on an axis, e.g. a log scaling.
  3. They are attached to an `~.axis.Axis` and hold a `.Transform`, which is
  4. responsible for the actual data transformation.
  5. See also `.axes.Axes.set_xscale` and the scales examples in the documentation.
  6. """
  7. import inspect
  8. import textwrap
  9. import numpy as np
  10. from numpy import ma
  11. from matplotlib import cbook, docstring, rcParams
  12. from matplotlib.ticker import (
  13. NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
  14. NullLocator, LogLocator, AutoLocator, AutoMinorLocator,
  15. SymmetricalLogLocator, LogitLocator)
  16. from matplotlib.transforms import Transform, IdentityTransform
  17. from matplotlib.cbook import warn_deprecated
  18. class ScaleBase:
  19. """
  20. The base class for all scales.
  21. Scales are separable transformations, working on a single dimension.
  22. Any subclasses will want to override:
  23. - :attr:`name`
  24. - :meth:`get_transform`
  25. - :meth:`set_default_locators_and_formatters`
  26. And optionally:
  27. - :meth:`limit_range_for_scale`
  28. """
  29. def __init__(self, axis, **kwargs):
  30. r"""
  31. Construct a new scale.
  32. Notes
  33. -----
  34. The following note is for scale implementors.
  35. For back-compatibility reasons, scales take an `~matplotlib.axis.Axis`
  36. object as first argument. However, this argument should not
  37. be used: a single scale object should be usable by multiple
  38. `~matplotlib.axis.Axis`\es at the same time.
  39. """
  40. if kwargs:
  41. warn_deprecated(
  42. '3.2.0',
  43. message=(
  44. f"ScaleBase got an unexpected keyword "
  45. f"argument {next(iter(kwargs))!r}. "
  46. 'In the future this will raise TypeError')
  47. )
  48. def get_transform(self):
  49. """
  50. Return the :class:`~matplotlib.transforms.Transform` object
  51. associated with this scale.
  52. """
  53. raise NotImplementedError()
  54. def set_default_locators_and_formatters(self, axis):
  55. """
  56. Set the locators and formatters of *axis* to instances suitable for
  57. this scale.
  58. """
  59. raise NotImplementedError()
  60. def limit_range_for_scale(self, vmin, vmax, minpos):
  61. """
  62. Returns the range *vmin*, *vmax*, possibly limited to the
  63. domain supported by this scale.
  64. *minpos* should be the minimum positive value in the data.
  65. This is used by log scales to determine a minimum value.
  66. """
  67. return vmin, vmax
  68. class LinearScale(ScaleBase):
  69. """
  70. The default linear scale.
  71. """
  72. name = 'linear'
  73. def __init__(self, axis, **kwargs):
  74. # This method is present only to prevent inheritance of the base class'
  75. # constructor docstring, which would otherwise end up interpolated into
  76. # the docstring of Axis.set_scale.
  77. """
  78. """
  79. super().__init__(axis, **kwargs)
  80. def set_default_locators_and_formatters(self, axis):
  81. # docstring inherited
  82. axis.set_major_locator(AutoLocator())
  83. axis.set_major_formatter(ScalarFormatter())
  84. axis.set_minor_formatter(NullFormatter())
  85. # update the minor locator for x and y axis based on rcParams
  86. if (axis.axis_name == 'x' and rcParams['xtick.minor.visible']
  87. or axis.axis_name == 'y' and rcParams['ytick.minor.visible']):
  88. axis.set_minor_locator(AutoMinorLocator())
  89. else:
  90. axis.set_minor_locator(NullLocator())
  91. def get_transform(self):
  92. """
  93. Return the transform for linear scaling, which is just the
  94. `~matplotlib.transforms.IdentityTransform`.
  95. """
  96. return IdentityTransform()
  97. class FuncTransform(Transform):
  98. """
  99. A simple transform that takes and arbitrary function for the
  100. forward and inverse transform.
  101. """
  102. input_dims = output_dims = 1
  103. def __init__(self, forward, inverse):
  104. """
  105. Parameters
  106. ----------
  107. forward : callable
  108. The forward function for the transform. This function must have
  109. an inverse and, for best behavior, be monotonic.
  110. It must have the signature::
  111. def forward(values: array-like) -> array-like
  112. inverse : callable
  113. The inverse of the forward function. Signature as ``forward``.
  114. """
  115. super().__init__()
  116. if callable(forward) and callable(inverse):
  117. self._forward = forward
  118. self._inverse = inverse
  119. else:
  120. raise ValueError('arguments to FuncTransform must be functions')
  121. def transform_non_affine(self, values):
  122. return self._forward(values)
  123. def inverted(self):
  124. return FuncTransform(self._inverse, self._forward)
  125. class FuncScale(ScaleBase):
  126. """
  127. Provide an arbitrary scale with user-supplied function for the axis.
  128. """
  129. name = 'function'
  130. def __init__(self, axis, functions):
  131. """
  132. Parameters
  133. ----------
  134. axis : `~matplotlib.axis.Axis`
  135. The axis for the scale.
  136. functions : (callable, callable)
  137. two-tuple of the forward and inverse functions for the scale.
  138. The forward function must be monotonic.
  139. Both functions must have the signature::
  140. def forward(values: array-like) -> array-like
  141. """
  142. forward, inverse = functions
  143. transform = FuncTransform(forward, inverse)
  144. self._transform = transform
  145. def get_transform(self):
  146. """Return the `.FuncTransform` associated with this scale."""
  147. return self._transform
  148. def set_default_locators_and_formatters(self, axis):
  149. # docstring inherited
  150. axis.set_major_locator(AutoLocator())
  151. axis.set_major_formatter(ScalarFormatter())
  152. axis.set_minor_formatter(NullFormatter())
  153. # update the minor locator for x and y axis based on rcParams
  154. if (axis.axis_name == 'x' and rcParams['xtick.minor.visible']
  155. or axis.axis_name == 'y' and rcParams['ytick.minor.visible']):
  156. axis.set_minor_locator(AutoMinorLocator())
  157. else:
  158. axis.set_minor_locator(NullLocator())
  159. @cbook.deprecated("3.1", alternative="LogTransform")
  160. class LogTransformBase(Transform):
  161. input_dims = output_dims = 1
  162. def __init__(self, nonpos='clip'):
  163. Transform.__init__(self)
  164. self._clip = {"clip": True, "mask": False}[nonpos]
  165. def transform_non_affine(self, a):
  166. return LogTransform.transform_non_affine(self, a)
  167. def __str__(self):
  168. return "{}({!r})".format(
  169. type(self).__name__, "clip" if self._clip else "mask")
  170. @cbook.deprecated("3.1", alternative="InvertedLogTransform")
  171. class InvertedLogTransformBase(Transform):
  172. input_dims = output_dims = 1
  173. def transform_non_affine(self, a):
  174. return ma.power(self.base, a)
  175. def __str__(self):
  176. return "{}()".format(type(self).__name__)
  177. @cbook.deprecated("3.1", alternative="LogTransform")
  178. class Log10Transform(LogTransformBase):
  179. base = 10.0
  180. def inverted(self):
  181. return InvertedLog10Transform()
  182. @cbook.deprecated("3.1", alternative="InvertedLogTransform")
  183. class InvertedLog10Transform(InvertedLogTransformBase):
  184. base = 10.0
  185. def inverted(self):
  186. return Log10Transform()
  187. @cbook.deprecated("3.1", alternative="LogTransform")
  188. class Log2Transform(LogTransformBase):
  189. base = 2.0
  190. def inverted(self):
  191. return InvertedLog2Transform()
  192. @cbook.deprecated("3.1", alternative="InvertedLogTransform")
  193. class InvertedLog2Transform(InvertedLogTransformBase):
  194. base = 2.0
  195. def inverted(self):
  196. return Log2Transform()
  197. @cbook.deprecated("3.1", alternative="LogTransform")
  198. class NaturalLogTransform(LogTransformBase):
  199. base = np.e
  200. def inverted(self):
  201. return InvertedNaturalLogTransform()
  202. @cbook.deprecated("3.1", alternative="InvertedLogTransform")
  203. class InvertedNaturalLogTransform(InvertedLogTransformBase):
  204. base = np.e
  205. def inverted(self):
  206. return NaturalLogTransform()
  207. class LogTransform(Transform):
  208. input_dims = output_dims = 1
  209. def __init__(self, base, nonpos='clip'):
  210. Transform.__init__(self)
  211. self.base = base
  212. self._clip = {"clip": True, "mask": False}[nonpos]
  213. def __str__(self):
  214. return "{}(base={}, nonpos={!r})".format(
  215. type(self).__name__, self.base, "clip" if self._clip else "mask")
  216. def transform_non_affine(self, a):
  217. # Ignore invalid values due to nans being passed to the transform.
  218. with np.errstate(divide="ignore", invalid="ignore"):
  219. log = {np.e: np.log, 2: np.log2, 10: np.log10}.get(self.base)
  220. if log: # If possible, do everything in a single call to NumPy.
  221. out = log(a)
  222. else:
  223. out = np.log(a)
  224. out /= np.log(self.base)
  225. if self._clip:
  226. # SVG spec says that conforming viewers must support values up
  227. # to 3.4e38 (C float); however experiments suggest that
  228. # Inkscape (which uses cairo for rendering) runs into cairo's
  229. # 24-bit limit (which is apparently shared by Agg).
  230. # Ghostscript (used for pdf rendering appears to overflow even
  231. # earlier, with the max value around 2 ** 15 for the tests to
  232. # pass. On the other hand, in practice, we want to clip beyond
  233. # np.log10(np.nextafter(0, 1)) ~ -323
  234. # so 1000 seems safe.
  235. out[a <= 0] = -1000
  236. return out
  237. def inverted(self):
  238. return InvertedLogTransform(self.base)
  239. class InvertedLogTransform(Transform):
  240. input_dims = output_dims = 1
  241. def __init__(self, base):
  242. Transform.__init__(self)
  243. self.base = base
  244. def __str__(self):
  245. return "{}(base={})".format(type(self).__name__, self.base)
  246. def transform_non_affine(self, a):
  247. return ma.power(self.base, a)
  248. def inverted(self):
  249. return LogTransform(self.base)
  250. class LogScale(ScaleBase):
  251. """
  252. A standard logarithmic scale. Care is taken to only plot positive values.
  253. """
  254. name = 'log'
  255. # compatibility shim
  256. LogTransformBase = LogTransformBase
  257. Log10Transform = Log10Transform
  258. InvertedLog10Transform = InvertedLog10Transform
  259. Log2Transform = Log2Transform
  260. InvertedLog2Transform = InvertedLog2Transform
  261. NaturalLogTransform = NaturalLogTransform
  262. InvertedNaturalLogTransform = InvertedNaturalLogTransform
  263. LogTransform = LogTransform
  264. InvertedLogTransform = InvertedLogTransform
  265. def __init__(self, axis, **kwargs):
  266. """
  267. Parameters
  268. ----------
  269. axis : `~matplotlib.axis.Axis`
  270. The axis for the scale.
  271. basex, basey : float, default: 10
  272. The base of the logarithm.
  273. nonposx, nonposy : {'clip', 'mask'}, default: 'clip'
  274. Determines the behavior for non-positive values. They can either
  275. be masked as invalid, or clipped to a very small positive number.
  276. subsx, subsy : sequence of int, default: None
  277. Where to place the subticks between each major tick.
  278. For example, in a log10 scale: ``[2, 3, 4, 5, 6, 7, 8, 9]``
  279. will place 8 logarithmically spaced minor ticks between
  280. each major tick.
  281. """
  282. if axis.axis_name == 'x':
  283. base = kwargs.pop('basex', 10.0)
  284. subs = kwargs.pop('subsx', None)
  285. nonpos = kwargs.pop('nonposx', 'clip')
  286. cbook._check_in_list(['mask', 'clip'], nonposx=nonpos)
  287. else:
  288. base = kwargs.pop('basey', 10.0)
  289. subs = kwargs.pop('subsy', None)
  290. nonpos = kwargs.pop('nonposy', 'clip')
  291. cbook._check_in_list(['mask', 'clip'], nonposy=nonpos)
  292. if kwargs:
  293. raise TypeError(f"LogScale got an unexpected keyword "
  294. f"argument {next(iter(kwargs))!r}")
  295. if base <= 0 or base == 1:
  296. raise ValueError('The log base cannot be <= 0 or == 1')
  297. self._transform = LogTransform(base, nonpos)
  298. self.subs = subs
  299. @property
  300. def base(self):
  301. return self._transform.base
  302. def set_default_locators_and_formatters(self, axis):
  303. # docstring inherited
  304. axis.set_major_locator(LogLocator(self.base))
  305. axis.set_major_formatter(LogFormatterSciNotation(self.base))
  306. axis.set_minor_locator(LogLocator(self.base, self.subs))
  307. axis.set_minor_formatter(
  308. LogFormatterSciNotation(self.base,
  309. labelOnlyBase=(self.subs is not None)))
  310. def get_transform(self):
  311. """Return the `.LogTransform` associated with this scale."""
  312. return self._transform
  313. def limit_range_for_scale(self, vmin, vmax, minpos):
  314. """Limit the domain to positive values."""
  315. if not np.isfinite(minpos):
  316. minpos = 1e-300 # Should rarely (if ever) have a visible effect.
  317. return (minpos if vmin <= 0 else vmin,
  318. minpos if vmax <= 0 else vmax)
  319. class FuncScaleLog(LogScale):
  320. """
  321. Provide an arbitrary scale with user-supplied function for the axis and
  322. then put on a logarithmic axes.
  323. """
  324. name = 'functionlog'
  325. def __init__(self, axis, functions, base=10):
  326. """
  327. Parameters
  328. ----------
  329. axis : `matplotlib.axis.Axis`
  330. The axis for the scale.
  331. functions : (callable, callable)
  332. two-tuple of the forward and inverse functions for the scale.
  333. The forward function must be monotonic.
  334. Both functions must have the signature::
  335. def forward(values: array-like) -> array-like
  336. base : float
  337. logarithmic base of the scale (default = 10)
  338. """
  339. forward, inverse = functions
  340. self.subs = None
  341. self._transform = FuncTransform(forward, inverse) + LogTransform(base)
  342. @property
  343. def base(self):
  344. return self._transform._b.base # Base of the LogTransform.
  345. def get_transform(self):
  346. """Return the `.Transform` associated with this scale."""
  347. return self._transform
  348. class SymmetricalLogTransform(Transform):
  349. input_dims = output_dims = 1
  350. def __init__(self, base, linthresh, linscale):
  351. Transform.__init__(self)
  352. self.base = base
  353. self.linthresh = linthresh
  354. self.linscale = linscale
  355. self._linscale_adj = (linscale / (1.0 - self.base ** -1))
  356. self._log_base = np.log(base)
  357. def transform_non_affine(self, a):
  358. abs_a = np.abs(a)
  359. with np.errstate(divide="ignore", invalid="ignore"):
  360. out = np.sign(a) * self.linthresh * (
  361. self._linscale_adj +
  362. np.log(abs_a / self.linthresh) / self._log_base)
  363. inside = abs_a <= self.linthresh
  364. out[inside] = a[inside] * self._linscale_adj
  365. return out
  366. def inverted(self):
  367. return InvertedSymmetricalLogTransform(self.base, self.linthresh,
  368. self.linscale)
  369. class InvertedSymmetricalLogTransform(Transform):
  370. input_dims = output_dims = 1
  371. def __init__(self, base, linthresh, linscale):
  372. Transform.__init__(self)
  373. symlog = SymmetricalLogTransform(base, linthresh, linscale)
  374. self.base = base
  375. self.linthresh = linthresh
  376. self.invlinthresh = symlog.transform(linthresh)
  377. self.linscale = linscale
  378. self._linscale_adj = (linscale / (1.0 - self.base ** -1))
  379. def transform_non_affine(self, a):
  380. abs_a = np.abs(a)
  381. with np.errstate(divide="ignore", invalid="ignore"):
  382. out = np.sign(a) * self.linthresh * (
  383. np.power(self.base,
  384. abs_a / self.linthresh - self._linscale_adj))
  385. inside = abs_a <= self.invlinthresh
  386. out[inside] = a[inside] / self._linscale_adj
  387. return out
  388. def inverted(self):
  389. return SymmetricalLogTransform(self.base,
  390. self.linthresh, self.linscale)
  391. class SymmetricalLogScale(ScaleBase):
  392. """
  393. The symmetrical logarithmic scale is logarithmic in both the
  394. positive and negative directions from the origin.
  395. Since the values close to zero tend toward infinity, there is a
  396. need to have a range around zero that is linear. The parameter
  397. *linthresh* allows the user to specify the size of this range
  398. (-*linthresh*, *linthresh*).
  399. Parameters
  400. ----------
  401. basex, basey : float
  402. The base of the logarithm. Defaults to 10.
  403. linthreshx, linthreshy : float
  404. Defines the range ``(-x, x)``, within which the plot is linear.
  405. This avoids having the plot go to infinity around zero. Defaults to 2.
  406. subsx, subsy : sequence of int
  407. Where to place the subticks between each major tick.
  408. For example, in a log10 scale: ``[2, 3, 4, 5, 6, 7, 8, 9]`` will place
  409. 8 logarithmically spaced minor ticks between each major tick.
  410. linscalex, linscaley : float, optional
  411. This allows the linear range ``(-linthresh, linthresh)`` to be
  412. stretched relative to the logarithmic range. Its value is the number of
  413. decades to use for each half of the linear range. For example, when
  414. *linscale* == 1.0 (the default), the space used for the positive and
  415. negative halves of the linear range will be equal to one decade in
  416. the logarithmic range.
  417. """
  418. name = 'symlog'
  419. # compatibility shim
  420. SymmetricalLogTransform = SymmetricalLogTransform
  421. InvertedSymmetricalLogTransform = InvertedSymmetricalLogTransform
  422. def __init__(self, axis, **kwargs):
  423. if axis.axis_name == 'x':
  424. base = kwargs.pop('basex', 10.0)
  425. linthresh = kwargs.pop('linthreshx', 2.0)
  426. subs = kwargs.pop('subsx', None)
  427. linscale = kwargs.pop('linscalex', 1.0)
  428. else:
  429. base = kwargs.pop('basey', 10.0)
  430. linthresh = kwargs.pop('linthreshy', 2.0)
  431. subs = kwargs.pop('subsy', None)
  432. linscale = kwargs.pop('linscaley', 1.0)
  433. if kwargs:
  434. warn_deprecated(
  435. '3.2.0',
  436. message=(
  437. f"SymmetricalLogScale got an unexpected keyword "
  438. f"argument {next(iter(kwargs))!r}. "
  439. 'In the future this will raise TypeError')
  440. )
  441. # raise TypeError(f"SymmetricalLogScale got an unexpected keyword "
  442. # f"argument {next(iter(kwargs))!r}")
  443. if base <= 1.0:
  444. raise ValueError("'basex/basey' must be larger than 1")
  445. if linthresh <= 0.0:
  446. raise ValueError("'linthreshx/linthreshy' must be positive")
  447. if linscale <= 0.0:
  448. raise ValueError("'linscalex/linthreshy' must be positive")
  449. self._transform = SymmetricalLogTransform(base, linthresh, linscale)
  450. self.base = base
  451. self.linthresh = linthresh
  452. self.linscale = linscale
  453. self.subs = subs
  454. def set_default_locators_and_formatters(self, axis):
  455. # docstring inherited
  456. axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
  457. axis.set_major_formatter(LogFormatterSciNotation(self.base))
  458. axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(),
  459. self.subs))
  460. axis.set_minor_formatter(NullFormatter())
  461. def get_transform(self):
  462. """Return the `.SymmetricalLogTransform` associated with this scale."""
  463. return self._transform
  464. class LogitTransform(Transform):
  465. input_dims = output_dims = 1
  466. def __init__(self, nonpos='mask'):
  467. Transform.__init__(self)
  468. cbook._check_in_list(['mask', 'clip'], nonpos=nonpos)
  469. self._nonpos = nonpos
  470. self._clip = {"clip": True, "mask": False}[nonpos]
  471. def transform_non_affine(self, a):
  472. """logit transform (base 10), masked or clipped"""
  473. with np.errstate(divide="ignore", invalid="ignore"):
  474. out = np.log10(a / (1 - a))
  475. if self._clip: # See LogTransform for choice of clip value.
  476. out[a <= 0] = -1000
  477. out[1 <= a] = 1000
  478. return out
  479. def inverted(self):
  480. return LogisticTransform(self._nonpos)
  481. def __str__(self):
  482. return "{}({!r})".format(type(self).__name__, self._nonpos)
  483. class LogisticTransform(Transform):
  484. input_dims = output_dims = 1
  485. def __init__(self, nonpos='mask'):
  486. Transform.__init__(self)
  487. self._nonpos = nonpos
  488. def transform_non_affine(self, a):
  489. """logistic transform (base 10)"""
  490. return 1.0 / (1 + 10**(-a))
  491. def inverted(self):
  492. return LogitTransform(self._nonpos)
  493. def __str__(self):
  494. return "{}({!r})".format(type(self).__name__, self._nonpos)
  495. class LogitScale(ScaleBase):
  496. """
  497. Logit scale for data between zero and one, both excluded.
  498. This scale is similar to a log scale close to zero and to one, and almost
  499. linear around 0.5. It maps the interval ]0, 1[ onto ]-infty, +infty[.
  500. """
  501. name = 'logit'
  502. def __init__(
  503. self,
  504. axis,
  505. nonpos='mask',
  506. *,
  507. one_half=r"\frac{1}{2}",
  508. use_overline=False,
  509. ):
  510. r"""
  511. Parameters
  512. ----------
  513. axis : `matplotlib.axis.Axis`
  514. Currently unused.
  515. nonpos : {'mask', 'clip'}
  516. Determines the behavior for values beyond the open interval ]0, 1[.
  517. They can either be masked as invalid, or clipped to a number very
  518. close to 0 or 1.
  519. use_overline : bool, default: False
  520. Indicate the usage of survival notation (\overline{x}) in place of
  521. standard notation (1-x) for probability close to one.
  522. one_half : str, default: r"\frac{1}{2}"
  523. The string used for ticks formatter to represent 1/2.
  524. """
  525. self._transform = LogitTransform(nonpos)
  526. self._use_overline = use_overline
  527. self._one_half = one_half
  528. def get_transform(self):
  529. """Return the `.LogitTransform` associated with this scale."""
  530. return self._transform
  531. def set_default_locators_and_formatters(self, axis):
  532. # docstring inherited
  533. # ..., 0.01, 0.1, 0.5, 0.9, 0.99, ...
  534. axis.set_major_locator(LogitLocator())
  535. axis.set_major_formatter(
  536. LogitFormatter(
  537. one_half=self._one_half,
  538. use_overline=self._use_overline
  539. )
  540. )
  541. axis.set_minor_locator(LogitLocator(minor=True))
  542. axis.set_minor_formatter(
  543. LogitFormatter(
  544. minor=True,
  545. one_half=self._one_half,
  546. use_overline=self._use_overline
  547. )
  548. )
  549. def limit_range_for_scale(self, vmin, vmax, minpos):
  550. """
  551. Limit the domain to values between 0 and 1 (excluded).
  552. """
  553. if not np.isfinite(minpos):
  554. minpos = 1e-7 # Should rarely (if ever) have a visible effect.
  555. return (minpos if vmin <= 0 else vmin,
  556. 1 - minpos if vmax >= 1 else vmax)
  557. _scale_mapping = {
  558. 'linear': LinearScale,
  559. 'log': LogScale,
  560. 'symlog': SymmetricalLogScale,
  561. 'logit': LogitScale,
  562. 'function': FuncScale,
  563. 'functionlog': FuncScaleLog,
  564. }
  565. def get_scale_names():
  566. """Return the names of the available scales."""
  567. return sorted(_scale_mapping)
  568. def scale_factory(scale, axis, **kwargs):
  569. """
  570. Return a scale class by name.
  571. Parameters
  572. ----------
  573. scale : {%(names)s}
  574. axis : `matplotlib.axis.Axis`
  575. """
  576. scale = scale.lower()
  577. cbook._check_in_list(_scale_mapping, scale=scale)
  578. return _scale_mapping[scale](axis, **kwargs)
  579. if scale_factory.__doc__:
  580. scale_factory.__doc__ = scale_factory.__doc__ % {
  581. "names": ", ".join(map(repr, get_scale_names()))}
  582. def register_scale(scale_class):
  583. """
  584. Register a new kind of scale.
  585. Parameters
  586. ----------
  587. scale_class : subclass of `ScaleBase`
  588. The scale to register.
  589. """
  590. _scale_mapping[scale_class.name] = scale_class
  591. @cbook.deprecated(
  592. '3.1', message='get_scale_docs() is considered private API since '
  593. '3.1 and will be removed from the public API in 3.3.')
  594. def get_scale_docs():
  595. """
  596. Helper function for generating docstrings related to scales.
  597. """
  598. return _get_scale_docs()
  599. def _get_scale_docs():
  600. """
  601. Helper function for generating docstrings related to scales.
  602. """
  603. docs = []
  604. for name, scale_class in _scale_mapping.items():
  605. docs.extend([
  606. f" {name!r}",
  607. "",
  608. textwrap.indent(inspect.getdoc(scale_class.__init__), " " * 8),
  609. ""
  610. ])
  611. return "\n".join(docs)
  612. docstring.interpd.update(
  613. scale_type='{%s}' % ', '.join([repr(x) for x in get_scale_names()]),
  614. scale_docs=_get_scale_docs().rstrip(),
  615. )