scale.py 25 KB

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