scale.py 26 KB

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