You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2662 lines
86 KiB

4 years ago
  1. """
  2. Tick locating and formatting
  3. ============================
  4. This module contains classes to support completely configurable tick
  5. locating and formatting. Although the locators know nothing about major
  6. or minor ticks, they are used by the Axis class to support major and
  7. minor tick locating and formatting. Generic tick locators and
  8. formatters are provided, as well as domain specific custom ones.
  9. Default Formatter
  10. -----------------
  11. The default formatter identifies when the x-data being plotted is a
  12. small range on top of a large off set. To reduce the chances that the
  13. ticklabels overlap the ticks are labeled as deltas from a fixed offset.
  14. For example::
  15. ax.plot(np.arange(2000, 2010), range(10))
  16. will have tick of 0-9 with an offset of +2e3. If this is not desired
  17. turn off the use of the offset on the default formatter::
  18. ax.get_xaxis().get_major_formatter().set_useOffset(False)
  19. set the rcParam ``axes.formatter.useoffset=False`` to turn it off
  20. globally, or set a different formatter.
  21. Tick locating
  22. -------------
  23. The Locator class is the base class for all tick locators. The locators
  24. handle autoscaling of the view limits based on the data limits, and the
  25. choosing of tick locations. A useful semi-automatic tick locator is
  26. `MultipleLocator`. It is initialized with a base, e.g., 10, and it picks
  27. axis limits and ticks that are multiples of that base.
  28. The Locator subclasses defined here are
  29. :class:`AutoLocator`
  30. `MaxNLocator` with simple defaults. This is the default tick locator for
  31. most plotting.
  32. :class:`MaxNLocator`
  33. Finds up to a max number of intervals with ticks at nice locations.
  34. :class:`LinearLocator`
  35. Space ticks evenly from min to max.
  36. :class:`LogLocator`
  37. Space ticks logarithmically from min to max.
  38. :class:`MultipleLocator`
  39. Ticks and range are a multiple of base; either integer or float.
  40. :class:`FixedLocator`
  41. Tick locations are fixed.
  42. :class:`IndexLocator`
  43. Locator for index plots (e.g., where ``x = range(len(y))``).
  44. :class:`NullLocator`
  45. No ticks.
  46. :class:`SymmetricalLogLocator`
  47. Locator for use with with the symlog norm; works like `LogLocator` for the
  48. part outside of the threshold and adds 0 if inside the limits.
  49. :class:`LogitLocator`
  50. Locator for logit scaling.
  51. :class:`OldAutoLocator`
  52. Choose a `MultipleLocator` and dynamically reassign it for intelligent
  53. ticking during navigation.
  54. :class:`AutoMinorLocator`
  55. Locator for minor ticks when the axis is linear and the
  56. major ticks are uniformly spaced. Subdivides the major
  57. tick interval into a specified number of minor intervals,
  58. defaulting to 4 or 5 depending on the major interval.
  59. There are a number of locators specialized for date locations - see
  60. the `dates` module.
  61. You can define your own locator by deriving from Locator. You must
  62. override the ``__call__`` method, which returns a sequence of locations,
  63. and you will probably want to override the autoscale method to set the
  64. view limits from the data limits.
  65. If you want to override the default locator, use one of the above or a custom
  66. locator and pass it to the x or y axis instance. The relevant methods are::
  67. ax.xaxis.set_major_locator(xmajor_locator)
  68. ax.xaxis.set_minor_locator(xminor_locator)
  69. ax.yaxis.set_major_locator(ymajor_locator)
  70. ax.yaxis.set_minor_locator(yminor_locator)
  71. The default minor locator is `NullLocator`, i.e., no minor ticks on by default.
  72. Tick formatting
  73. ---------------
  74. Tick formatting is controlled by classes derived from Formatter. The formatter
  75. operates on a single tick value and returns a string to the axis.
  76. :class:`NullFormatter`
  77. No labels on the ticks.
  78. :class:`IndexFormatter`
  79. Set the strings from a list of labels.
  80. :class:`FixedFormatter`
  81. Set the strings manually for the labels.
  82. :class:`FuncFormatter`
  83. User defined function sets the labels.
  84. :class:`StrMethodFormatter`
  85. Use string `format` method.
  86. :class:`FormatStrFormatter`
  87. Use an old-style sprintf format string.
  88. :class:`ScalarFormatter`
  89. Default formatter for scalars: autopick the format string.
  90. :class:`LogFormatter`
  91. Formatter for log axes.
  92. :class:`LogFormatterExponent`
  93. Format values for log axis using ``exponent = log_base(value)``.
  94. :class:`LogFormatterMathtext`
  95. Format values for log axis using ``exponent = log_base(value)``
  96. using Math text.
  97. :class:`LogFormatterSciNotation`
  98. Format values for log axis using scientific notation.
  99. :class:`LogitFormatter`
  100. Probability formatter.
  101. :class:`EngFormatter`
  102. Format labels in engineering notation
  103. :class:`PercentFormatter`
  104. Format labels as a percentage
  105. You can derive your own formatter from the Formatter base class by
  106. simply overriding the ``__call__`` method. The formatter class has
  107. access to the axis view and data limits.
  108. To control the major and minor tick label formats, use one of the
  109. following methods::
  110. ax.xaxis.set_major_formatter(xmajor_formatter)
  111. ax.xaxis.set_minor_formatter(xminor_formatter)
  112. ax.yaxis.set_major_formatter(ymajor_formatter)
  113. ax.yaxis.set_minor_formatter(yminor_formatter)
  114. See :doc:`/gallery/ticks_and_spines/major_minor_demo` for an
  115. example of setting major and minor ticks. See the :mod:`matplotlib.dates`
  116. module for more information and examples of using date locators and formatters.
  117. """
  118. import itertools
  119. import logging
  120. import locale
  121. import math
  122. import numpy as np
  123. from matplotlib import rcParams
  124. from matplotlib import cbook
  125. from matplotlib import transforms as mtransforms
  126. import warnings
  127. _log = logging.getLogger(__name__)
  128. __all__ = ('TickHelper', 'Formatter', 'FixedFormatter',
  129. 'NullFormatter', 'FuncFormatter', 'FormatStrFormatter',
  130. 'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter',
  131. 'LogFormatterExponent', 'LogFormatterMathtext',
  132. 'IndexFormatter', 'LogFormatterSciNotation',
  133. 'LogitFormatter', 'EngFormatter', 'PercentFormatter',
  134. 'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator',
  135. 'LinearLocator', 'LogLocator', 'AutoLocator',
  136. 'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator',
  137. 'SymmetricalLogLocator', 'LogitLocator')
  138. # Work around numpy/numpy#6127.
  139. def _divmod(x, y):
  140. if isinstance(x, np.generic):
  141. x = x.item()
  142. if isinstance(y, np.generic):
  143. y = y.item()
  144. return divmod(x, y)
  145. def _mathdefault(s):
  146. return '\\mathdefault{%s}' % s
  147. class _DummyAxis(object):
  148. def __init__(self, minpos=0):
  149. self.dataLim = mtransforms.Bbox.unit()
  150. self.viewLim = mtransforms.Bbox.unit()
  151. self._minpos = minpos
  152. def get_view_interval(self):
  153. return self.viewLim.intervalx
  154. def set_view_interval(self, vmin, vmax):
  155. self.viewLim.intervalx = vmin, vmax
  156. def get_minpos(self):
  157. return self._minpos
  158. def get_data_interval(self):
  159. return self.dataLim.intervalx
  160. def set_data_interval(self, vmin, vmax):
  161. self.dataLim.intervalx = vmin, vmax
  162. def get_tick_space(self):
  163. # Just use the long-standing default of nbins==9
  164. return 9
  165. class TickHelper(object):
  166. axis = None
  167. def set_axis(self, axis):
  168. self.axis = axis
  169. def create_dummy_axis(self, **kwargs):
  170. if self.axis is None:
  171. self.axis = _DummyAxis(**kwargs)
  172. def set_view_interval(self, vmin, vmax):
  173. self.axis.set_view_interval(vmin, vmax)
  174. def set_data_interval(self, vmin, vmax):
  175. self.axis.set_data_interval(vmin, vmax)
  176. def set_bounds(self, vmin, vmax):
  177. self.set_view_interval(vmin, vmax)
  178. self.set_data_interval(vmin, vmax)
  179. class Formatter(TickHelper):
  180. """
  181. Create a string based on a tick value and location.
  182. """
  183. # some classes want to see all the locs to help format
  184. # individual ones
  185. locs = []
  186. def __call__(self, x, pos=None):
  187. """
  188. Return the format for tick value *x* at position pos.
  189. ``pos=None`` indicates an unspecified location.
  190. """
  191. raise NotImplementedError('Derived must override')
  192. def format_data(self, value):
  193. """
  194. Returns the full string representation of the value with the
  195. position unspecified.
  196. """
  197. return self.__call__(value)
  198. def format_data_short(self, value):
  199. """
  200. Return a short string version of the tick value.
  201. Defaults to the position-independent long value.
  202. """
  203. return self.format_data(value)
  204. def get_offset(self):
  205. return ''
  206. def set_locs(self, locs):
  207. self.locs = locs
  208. def fix_minus(self, s):
  209. """
  210. Some classes may want to replace a hyphen for minus with the
  211. proper unicode symbol (U+2212) for typographical correctness.
  212. The default is to not replace it.
  213. Note, if you use this method, e.g., in :meth:`format_data` or
  214. call, you probably don't want to use it for
  215. :meth:`format_data_short` since the toolbar uses this for
  216. interactive coord reporting and I doubt we can expect GUIs
  217. across platforms will handle the unicode correctly. So for
  218. now the classes that override :meth:`fix_minus` should have an
  219. explicit :meth:`format_data_short` method
  220. """
  221. return s
  222. class IndexFormatter(Formatter):
  223. """
  224. Format the position x to the nearest i-th label where i=int(x+0.5)
  225. """
  226. def __init__(self, labels):
  227. self.labels = labels
  228. self.n = len(labels)
  229. def __call__(self, x, pos=None):
  230. """
  231. Return the format for tick value `x` at position pos.
  232. The position is ignored and the value is rounded to the nearest
  233. integer, which is used to look up the label.
  234. """
  235. i = int(x + 0.5)
  236. if i < 0 or i >= self.n:
  237. return ''
  238. else:
  239. return self.labels[i]
  240. class NullFormatter(Formatter):
  241. """
  242. Always return the empty string.
  243. """
  244. def __call__(self, x, pos=None):
  245. """
  246. Returns an empty string for all inputs.
  247. """
  248. return ''
  249. class FixedFormatter(Formatter):
  250. """
  251. Return fixed strings for tick labels based only on position, not
  252. value.
  253. """
  254. def __init__(self, seq):
  255. """
  256. Set the sequence of strings that will be used for labels.
  257. """
  258. self.seq = seq
  259. self.offset_string = ''
  260. def __call__(self, x, pos=None):
  261. """
  262. Returns the label that matches the position regardless of the
  263. value.
  264. For positions ``pos < len(seq)``, return `seq[i]` regardless of
  265. `x`. Otherwise return empty string. `seq` is the sequence of
  266. strings that this object was initialized with.
  267. """
  268. if pos is None or pos >= len(self.seq):
  269. return ''
  270. else:
  271. return self.seq[pos]
  272. def get_offset(self):
  273. return self.offset_string
  274. def set_offset_string(self, ofs):
  275. self.offset_string = ofs
  276. class FuncFormatter(Formatter):
  277. """
  278. Use a user-defined function for formatting.
  279. The function should take in two inputs (a tick value ``x`` and a
  280. position ``pos``), and return a string containing the corresponding
  281. tick label.
  282. """
  283. def __init__(self, func):
  284. self.func = func
  285. def __call__(self, x, pos=None):
  286. """
  287. Return the value of the user defined function.
  288. `x` and `pos` are passed through as-is.
  289. """
  290. return self.func(x, pos)
  291. class FormatStrFormatter(Formatter):
  292. """
  293. Use an old-style ('%' operator) format string to format the tick.
  294. The format string should have a single variable format (%) in it.
  295. It will be applied to the value (not the position) of the tick.
  296. """
  297. def __init__(self, fmt):
  298. self.fmt = fmt
  299. def __call__(self, x, pos=None):
  300. """
  301. Return the formatted label string.
  302. Only the value `x` is formatted. The position is ignored.
  303. """
  304. return self.fmt % x
  305. class StrMethodFormatter(Formatter):
  306. """
  307. Use a new-style format string (as used by `str.format()`)
  308. to format the tick.
  309. The field used for the value must be labeled `x` and the field used
  310. for the position must be labeled `pos`.
  311. """
  312. def __init__(self, fmt):
  313. self.fmt = fmt
  314. def __call__(self, x, pos=None):
  315. """
  316. Return the formatted label string.
  317. `x` and `pos` are passed to `str.format` as keyword arguments
  318. with those exact names.
  319. """
  320. return self.fmt.format(x=x, pos=pos)
  321. class OldScalarFormatter(Formatter):
  322. """
  323. Tick location is a plain old number.
  324. """
  325. def __call__(self, x, pos=None):
  326. """
  327. Return the format for tick val `x` based on the width of the
  328. axis.
  329. The position `pos` is ignored.
  330. """
  331. xmin, xmax = self.axis.get_view_interval()
  332. d = abs(xmax - xmin)
  333. return self.pprint_val(x, d)
  334. def pprint_val(self, x, d):
  335. """
  336. Formats the value `x` based on the size of the axis range `d`.
  337. """
  338. #if the number is not too big and it's an int, format it as an
  339. #int
  340. if abs(x) < 1e4 and x == int(x):
  341. return '%d' % x
  342. if d < 1e-2:
  343. fmt = '%1.3e'
  344. elif d < 1e-1:
  345. fmt = '%1.3f'
  346. elif d > 1e5:
  347. fmt = '%1.1e'
  348. elif d > 10:
  349. fmt = '%1.1f'
  350. elif d > 1:
  351. fmt = '%1.2f'
  352. else:
  353. fmt = '%1.3f'
  354. s = fmt % x
  355. tup = s.split('e')
  356. if len(tup) == 2:
  357. mantissa = tup[0].rstrip('0').rstrip('.')
  358. sign = tup[1][0].replace('+', '')
  359. exponent = tup[1][1:].lstrip('0')
  360. s = '%se%s%s' % (mantissa, sign, exponent)
  361. else:
  362. s = s.rstrip('0').rstrip('.')
  363. return s
  364. class ScalarFormatter(Formatter):
  365. """
  366. Format tick values as a number.
  367. Tick value is interpreted as a plain old number. If
  368. ``useOffset==True`` and the data range is much smaller than the data
  369. average, then an offset will be determined such that the tick labels
  370. are meaningful. Scientific notation is used for ``data < 10^-n`` or
  371. ``data >= 10^m``, where ``n`` and ``m`` are the power limits set
  372. using ``set_powerlimits((n,m))``. The defaults for these are
  373. controlled by the ``axes.formatter.limits`` rc parameter.
  374. """
  375. def __init__(self, useOffset=None, useMathText=None, useLocale=None):
  376. # useOffset allows plotting small data ranges with large offsets: for
  377. # example: [1+1e-9,1+2e-9,1+3e-9] useMathText will render the offset
  378. # and scientific notation in mathtext
  379. if useOffset is None:
  380. useOffset = rcParams['axes.formatter.useoffset']
  381. self._offset_threshold = rcParams['axes.formatter.offset_threshold']
  382. self.set_useOffset(useOffset)
  383. self._usetex = rcParams['text.usetex']
  384. if useMathText is None:
  385. useMathText = rcParams['axes.formatter.use_mathtext']
  386. self.set_useMathText(useMathText)
  387. self.orderOfMagnitude = 0
  388. self.format = ''
  389. self._scientific = True
  390. self._powerlimits = rcParams['axes.formatter.limits']
  391. if useLocale is None:
  392. useLocale = rcParams['axes.formatter.use_locale']
  393. self._useLocale = useLocale
  394. def get_useOffset(self):
  395. return self._useOffset
  396. def set_useOffset(self, val):
  397. if val in [True, False]:
  398. self.offset = 0
  399. self._useOffset = val
  400. else:
  401. self._useOffset = False
  402. self.offset = val
  403. useOffset = property(fget=get_useOffset, fset=set_useOffset)
  404. def get_useLocale(self):
  405. return self._useLocale
  406. def set_useLocale(self, val):
  407. if val is None:
  408. self._useLocale = rcParams['axes.formatter.use_locale']
  409. else:
  410. self._useLocale = val
  411. useLocale = property(fget=get_useLocale, fset=set_useLocale)
  412. def get_useMathText(self):
  413. return self._useMathText
  414. def set_useMathText(self, val):
  415. if val is None:
  416. self._useMathText = rcParams['axes.formatter.use_mathtext']
  417. else:
  418. self._useMathText = val
  419. useMathText = property(fget=get_useMathText, fset=set_useMathText)
  420. def fix_minus(self, s):
  421. """
  422. Replace hyphens with a unicode minus.
  423. """
  424. if rcParams['text.usetex'] or not rcParams['axes.unicode_minus']:
  425. return s
  426. else:
  427. return s.replace('-', '\N{MINUS SIGN}')
  428. def __call__(self, x, pos=None):
  429. """
  430. Return the format for tick value `x` at position `pos`.
  431. """
  432. if len(self.locs) == 0:
  433. return ''
  434. else:
  435. s = self.pprint_val(x)
  436. return self.fix_minus(s)
  437. def set_scientific(self, b):
  438. """
  439. Turn scientific notation on or off.
  440. .. seealso:: Method :meth:`set_powerlimits`
  441. """
  442. self._scientific = bool(b)
  443. def set_powerlimits(self, lims):
  444. """
  445. Sets size thresholds for scientific notation.
  446. Parameters
  447. ----------
  448. lims : (min_exp, max_exp)
  449. A tuple containing the powers of 10 that determine the switchover
  450. threshold. Numbers below ``10**min_exp`` and above ``10**max_exp``
  451. will be displayed in scientific notation.
  452. For example, ``formatter.set_powerlimits((-3, 4))`` sets the
  453. pre-2007 default in which scientific notation is used for
  454. numbers less than 1e-3 or greater than 1e4.
  455. .. seealso:: Method :meth:`set_scientific`
  456. """
  457. if len(lims) != 2:
  458. raise ValueError("'lims' must be a sequence of length 2")
  459. self._powerlimits = lims
  460. def format_data_short(self, value):
  461. """
  462. Return a short formatted string representation of a number.
  463. """
  464. if self._useLocale:
  465. return locale.format_string('%-12g', (value,))
  466. else:
  467. return '%-12g' % value
  468. def format_data(self, value):
  469. """
  470. Return a formatted string representation of a number.
  471. """
  472. if self._useLocale:
  473. s = locale.format_string('%1.10e', (value,))
  474. else:
  475. s = '%1.10e' % value
  476. s = self._formatSciNotation(s)
  477. return self.fix_minus(s)
  478. def get_offset(self):
  479. """
  480. Return scientific notation, plus offset.
  481. """
  482. if len(self.locs) == 0:
  483. return ''
  484. s = ''
  485. if self.orderOfMagnitude or self.offset:
  486. offsetStr = ''
  487. sciNotStr = ''
  488. if self.offset:
  489. offsetStr = self.format_data(self.offset)
  490. if self.offset > 0:
  491. offsetStr = '+' + offsetStr
  492. if self.orderOfMagnitude:
  493. if self._usetex or self._useMathText:
  494. sciNotStr = self.format_data(10 ** self.orderOfMagnitude)
  495. else:
  496. sciNotStr = '1e%d' % self.orderOfMagnitude
  497. if self._useMathText:
  498. if sciNotStr != '':
  499. sciNotStr = r'\times%s' % _mathdefault(sciNotStr)
  500. s = ''.join(('$', sciNotStr, _mathdefault(offsetStr), '$'))
  501. elif self._usetex:
  502. if sciNotStr != '':
  503. sciNotStr = r'\times%s' % sciNotStr
  504. s = ''.join(('$', sciNotStr, offsetStr, '$'))
  505. else:
  506. s = ''.join((sciNotStr, offsetStr))
  507. return self.fix_minus(s)
  508. def set_locs(self, locs):
  509. """
  510. Set the locations of the ticks.
  511. """
  512. self.locs = locs
  513. if len(self.locs) > 0:
  514. vmin, vmax = self.axis.get_view_interval()
  515. d = abs(vmax - vmin)
  516. if self._useOffset:
  517. self._compute_offset()
  518. self._set_orderOfMagnitude(d)
  519. self._set_format(vmin, vmax)
  520. def _compute_offset(self):
  521. locs = self.locs
  522. if locs is None or not len(locs):
  523. self.offset = 0
  524. return
  525. # Restrict to visible ticks.
  526. vmin, vmax = sorted(self.axis.get_view_interval())
  527. locs = np.asarray(locs)
  528. locs = locs[(vmin <= locs) & (locs <= vmax)]
  529. if not len(locs):
  530. self.offset = 0
  531. return
  532. lmin, lmax = locs.min(), locs.max()
  533. # Only use offset if there are at least two ticks and every tick has
  534. # the same sign.
  535. if lmin == lmax or lmin <= 0 <= lmax:
  536. self.offset = 0
  537. return
  538. # min, max comparing absolute values (we want division to round towards
  539. # zero so we work on absolute values).
  540. abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))])
  541. sign = math.copysign(1, lmin)
  542. # What is the smallest power of ten such that abs_min and abs_max are
  543. # equal up to that precision?
  544. # Note: Internally using oom instead of 10 ** oom avoids some numerical
  545. # accuracy issues.
  546. oom_max = np.ceil(math.log10(abs_max))
  547. oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
  548. if abs_min // 10 ** oom != abs_max // 10 ** oom)
  549. if (abs_max - abs_min) / 10 ** oom <= 1e-2:
  550. # Handle the case of straddling a multiple of a large power of ten
  551. # (relative to the span).
  552. # What is the smallest power of ten such that abs_min and abs_max
  553. # are no more than 1 apart at that precision?
  554. oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
  555. if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)
  556. # Only use offset if it saves at least _offset_threshold digits.
  557. n = self._offset_threshold - 1
  558. self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom
  559. if abs_max // 10 ** oom >= 10**n
  560. else 0)
  561. def _set_orderOfMagnitude(self, range):
  562. # if scientific notation is to be used, find the appropriate exponent
  563. # if using an numerical offset, find the exponent after applying the
  564. # offset. When lower power limit = upper <> 0, use provided exponent.
  565. if not self._scientific:
  566. self.orderOfMagnitude = 0
  567. return
  568. if self._powerlimits[0] == self._powerlimits[1] != 0:
  569. # fixed scaling when lower power limit = upper <> 0.
  570. self.orderOfMagnitude = self._powerlimits[0]
  571. return
  572. locs = np.abs(self.locs)
  573. if self.offset:
  574. oom = math.floor(math.log10(range))
  575. else:
  576. if locs[0] > locs[-1]:
  577. val = locs[0]
  578. else:
  579. val = locs[-1]
  580. if val == 0:
  581. oom = 0
  582. else:
  583. oom = math.floor(math.log10(val))
  584. if oom <= self._powerlimits[0]:
  585. self.orderOfMagnitude = oom
  586. elif oom >= self._powerlimits[1]:
  587. self.orderOfMagnitude = oom
  588. else:
  589. self.orderOfMagnitude = 0
  590. def _set_format(self, vmin, vmax):
  591. # set the format string to format all the ticklabels
  592. if len(self.locs) < 2:
  593. # Temporarily augment the locations with the axis end points.
  594. _locs = [*self.locs, vmin, vmax]
  595. else:
  596. _locs = self.locs
  597. locs = (np.asarray(_locs) - self.offset) / 10. ** self.orderOfMagnitude
  598. loc_range = np.ptp(locs)
  599. # Curvilinear coordinates can yield two identical points.
  600. if loc_range == 0:
  601. loc_range = np.max(np.abs(locs))
  602. # Both points might be zero.
  603. if loc_range == 0:
  604. loc_range = 1
  605. if len(self.locs) < 2:
  606. # We needed the end points only for the loc_range calculation.
  607. locs = locs[:-2]
  608. loc_range_oom = int(math.floor(math.log10(loc_range)))
  609. # first estimate:
  610. sigfigs = max(0, 3 - loc_range_oom)
  611. # refined estimate:
  612. thresh = 1e-3 * 10 ** loc_range_oom
  613. while sigfigs >= 0:
  614. if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
  615. sigfigs -= 1
  616. else:
  617. break
  618. sigfigs += 1
  619. self.format = '%1.' + str(sigfigs) + 'f'
  620. if self._usetex:
  621. self.format = '$%s$' % self.format
  622. elif self._useMathText:
  623. self.format = '$%s$' % _mathdefault(self.format)
  624. def pprint_val(self, x):
  625. xp = (x - self.offset) / (10. ** self.orderOfMagnitude)
  626. if np.abs(xp) < 1e-8:
  627. xp = 0
  628. if self._useLocale:
  629. return locale.format_string(self.format, (xp,))
  630. else:
  631. return self.format % xp
  632. def _formatSciNotation(self, s):
  633. # transform 1e+004 into 1e4, for example
  634. if self._useLocale:
  635. decimal_point = locale.localeconv()['decimal_point']
  636. positive_sign = locale.localeconv()['positive_sign']
  637. else:
  638. decimal_point = '.'
  639. positive_sign = '+'
  640. tup = s.split('e')
  641. try:
  642. significand = tup[0].rstrip('0').rstrip(decimal_point)
  643. sign = tup[1][0].replace(positive_sign, '')
  644. exponent = tup[1][1:].lstrip('0')
  645. if self._useMathText or self._usetex:
  646. if significand == '1' and exponent != '':
  647. # reformat 1x10^y as 10^y
  648. significand = ''
  649. if exponent:
  650. exponent = '10^{%s%s}' % (sign, exponent)
  651. if significand and exponent:
  652. return r'%s{\times}%s' % (significand, exponent)
  653. else:
  654. return r'%s%s' % (significand, exponent)
  655. else:
  656. s = ('%se%s%s' % (significand, sign, exponent)).rstrip('e')
  657. return s
  658. except IndexError:
  659. return s
  660. class LogFormatter(Formatter):
  661. """
  662. Base class for formatting ticks on a log or symlog scale.
  663. It may be instantiated directly, or subclassed.
  664. Parameters
  665. ----------
  666. base : float, optional, default: 10.
  667. Base of the logarithm used in all calculations.
  668. labelOnlyBase : bool, optional, default: False
  669. If True, label ticks only at integer powers of base.
  670. This is normally True for major ticks and False for
  671. minor ticks.
  672. minor_thresholds : (subset, all), optional, default: (1, 0.4)
  673. If labelOnlyBase is False, these two numbers control
  674. the labeling of ticks that are not at integer powers of
  675. base; normally these are the minor ticks. The controlling
  676. parameter is the log of the axis data range. In the typical
  677. case where base is 10 it is the number of decades spanned
  678. by the axis, so we can call it 'numdec'. If ``numdec <= all``,
  679. all minor ticks will be labeled. If ``all < numdec <= subset``,
  680. then only a subset of minor ticks will be labeled, so as to
  681. avoid crowding. If ``numdec > subset`` then no minor ticks will
  682. be labeled.
  683. linthresh : None or float, optional, default: None
  684. If a symmetric log scale is in use, its ``linthresh``
  685. parameter must be supplied here.
  686. Notes
  687. -----
  688. The `set_locs` method must be called to enable the subsetting
  689. logic controlled by the ``minor_thresholds`` parameter.
  690. In some cases such as the colorbar, there is no distinction between
  691. major and minor ticks; the tick locations might be set manually,
  692. or by a locator that puts ticks at integer powers of base and
  693. at intermediate locations. For this situation, disable the
  694. minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``,
  695. so that all ticks will be labeled.
  696. To disable labeling of minor ticks when 'labelOnlyBase' is False,
  697. use ``minor_thresholds=(0, 0)``. This is the default for the
  698. "classic" style.
  699. Examples
  700. --------
  701. To label a subset of minor ticks when the view limits span up
  702. to 2 decades, and all of the ticks when zoomed in to 0.5 decades
  703. or less, use ``minor_thresholds=(2, 0.5)``.
  704. To label all minor ticks when the view limits span up to 1.5
  705. decades, use ``minor_thresholds=(1.5, 1.5)``.
  706. """
  707. def __init__(self, base=10.0, labelOnlyBase=False,
  708. minor_thresholds=None,
  709. linthresh=None):
  710. self._base = float(base)
  711. self.labelOnlyBase = labelOnlyBase
  712. if minor_thresholds is None:
  713. if rcParams['_internal.classic_mode']:
  714. minor_thresholds = (0, 0)
  715. else:
  716. minor_thresholds = (1, 0.4)
  717. self.minor_thresholds = minor_thresholds
  718. self._sublabels = None
  719. self._linthresh = linthresh
  720. def base(self, base):
  721. """
  722. Change the *base* for labeling.
  723. .. warning::
  724. Should always match the base used for :class:`LogLocator`
  725. """
  726. self._base = base
  727. def label_minor(self, labelOnlyBase):
  728. """
  729. Switch minor tick labeling on or off.
  730. Parameters
  731. ----------
  732. labelOnlyBase : bool
  733. If True, label ticks only at integer powers of base.
  734. """
  735. self.labelOnlyBase = labelOnlyBase
  736. def set_locs(self, locs=None):
  737. """
  738. Use axis view limits to control which ticks are labeled.
  739. The *locs* parameter is ignored in the present algorithm.
  740. """
  741. if np.isinf(self.minor_thresholds[0]):
  742. self._sublabels = None
  743. return
  744. # Handle symlog case:
  745. linthresh = self._linthresh
  746. if linthresh is None:
  747. try:
  748. linthresh = self.axis.get_transform().linthresh
  749. except AttributeError:
  750. pass
  751. vmin, vmax = self.axis.get_view_interval()
  752. if vmin > vmax:
  753. vmin, vmax = vmax, vmin
  754. if linthresh is None and vmin <= 0:
  755. # It's probably a colorbar with
  756. # a format kwarg setting a LogFormatter in the manner
  757. # that worked with 1.5.x, but that doesn't work now.
  758. self._sublabels = {1} # label powers of base
  759. return
  760. b = self._base
  761. if linthresh is not None: # symlog
  762. # Only compute the number of decades in the logarithmic part of the
  763. # axis
  764. numdec = 0
  765. if vmin < -linthresh:
  766. rhs = min(vmax, -linthresh)
  767. numdec += math.log(vmin / rhs) / math.log(b)
  768. if vmax > linthresh:
  769. lhs = max(vmin, linthresh)
  770. numdec += math.log(vmax / lhs) / math.log(b)
  771. else:
  772. vmin = math.log(vmin) / math.log(b)
  773. vmax = math.log(vmax) / math.log(b)
  774. numdec = abs(vmax - vmin)
  775. if numdec > self.minor_thresholds[0]:
  776. # Label only bases
  777. self._sublabels = {1}
  778. elif numdec > self.minor_thresholds[1]:
  779. # Add labels between bases at log-spaced coefficients;
  780. # include base powers in case the locations include
  781. # "major" and "minor" points, as in colorbar.
  782. c = np.logspace(0, 1, int(b)//2 + 1, base=b)
  783. self._sublabels = set(np.round(c))
  784. # For base 10, this yields (1, 2, 3, 4, 6, 10).
  785. else:
  786. # Label all integer multiples of base**n.
  787. self._sublabels = set(np.arange(1, b + 1))
  788. def _num_to_string(self, x, vmin, vmax):
  789. if x > 10000:
  790. s = '%1.0e' % x
  791. elif x < 1:
  792. s = '%1.0e' % x
  793. else:
  794. s = self.pprint_val(x, vmax - vmin)
  795. return s
  796. def __call__(self, x, pos=None):
  797. """
  798. Return the format for tick val *x*.
  799. """
  800. if x == 0.0: # Symlog
  801. return '0'
  802. x = abs(x)
  803. b = self._base
  804. # only label the decades
  805. fx = math.log(x) / math.log(b)
  806. is_x_decade = is_close_to_int(fx)
  807. exponent = np.round(fx) if is_x_decade else np.floor(fx)
  808. coeff = np.round(x / b ** exponent)
  809. if self.labelOnlyBase and not is_x_decade:
  810. return ''
  811. if self._sublabels is not None and coeff not in self._sublabels:
  812. return ''
  813. vmin, vmax = self.axis.get_view_interval()
  814. vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
  815. s = self._num_to_string(x, vmin, vmax)
  816. return self.fix_minus(s)
  817. def format_data(self, value):
  818. b = self.labelOnlyBase
  819. self.labelOnlyBase = False
  820. value = cbook.strip_math(self.__call__(value))
  821. self.labelOnlyBase = b
  822. return value
  823. def format_data_short(self, value):
  824. """
  825. Return a short formatted string representation of a number.
  826. """
  827. return '%-12g' % value
  828. def pprint_val(self, x, d):
  829. #if the number is not too big and it's an int, format it as an
  830. #int
  831. if abs(x) < 1e4 and x == int(x):
  832. return '%d' % x
  833. if d < 1e-2:
  834. fmt = '%1.3e'
  835. elif d < 1e-1:
  836. fmt = '%1.3f'
  837. elif d > 1e5:
  838. fmt = '%1.1e'
  839. elif d > 10:
  840. fmt = '%1.1f'
  841. elif d > 1:
  842. fmt = '%1.2f'
  843. else:
  844. fmt = '%1.3f'
  845. s = fmt % x
  846. tup = s.split('e')
  847. if len(tup) == 2:
  848. mantissa = tup[0].rstrip('0').rstrip('.')
  849. exponent = int(tup[1])
  850. if exponent:
  851. s = '%se%d' % (mantissa, exponent)
  852. else:
  853. s = mantissa
  854. else:
  855. s = s.rstrip('0').rstrip('.')
  856. return s
  857. class LogFormatterExponent(LogFormatter):
  858. """
  859. Format values for log axis using ``exponent = log_base(value)``.
  860. """
  861. def _num_to_string(self, x, vmin, vmax):
  862. fx = math.log(x) / math.log(self._base)
  863. if abs(fx) > 10000:
  864. s = '%1.0g' % fx
  865. elif abs(fx) < 1:
  866. s = '%1.0g' % fx
  867. else:
  868. fd = math.log(vmax - vmin) / math.log(self._base)
  869. s = self.pprint_val(fx, fd)
  870. return s
  871. class LogFormatterMathtext(LogFormatter):
  872. """
  873. Format values for log axis using ``exponent = log_base(value)``.
  874. """
  875. def _non_decade_format(self, sign_string, base, fx, usetex):
  876. 'Return string for non-decade locations'
  877. if usetex:
  878. return (r'$%s%s^{%.2f}$') % (sign_string, base, fx)
  879. else:
  880. return ('$%s$' % _mathdefault('%s%s^{%.2f}' %
  881. (sign_string, base, fx)))
  882. def __call__(self, x, pos=None):
  883. """
  884. Return the format for tick value *x*.
  885. The position *pos* is ignored.
  886. """
  887. usetex = rcParams['text.usetex']
  888. min_exp = rcParams['axes.formatter.min_exponent']
  889. if x == 0: # Symlog
  890. if usetex:
  891. return '$0$'
  892. else:
  893. return '$%s$' % _mathdefault('0')
  894. sign_string = '-' if x < 0 else ''
  895. x = abs(x)
  896. b = self._base
  897. # only label the decades
  898. fx = math.log(x) / math.log(b)
  899. is_x_decade = is_close_to_int(fx)
  900. exponent = np.round(fx) if is_x_decade else np.floor(fx)
  901. coeff = np.round(x / b ** exponent)
  902. if is_x_decade:
  903. fx = round(fx)
  904. if self.labelOnlyBase and not is_x_decade:
  905. return ''
  906. if self._sublabels is not None and coeff not in self._sublabels:
  907. return ''
  908. # use string formatting of the base if it is not an integer
  909. if b % 1 == 0.0:
  910. base = '%d' % b
  911. else:
  912. base = '%s' % b
  913. if np.abs(fx) < min_exp:
  914. if usetex:
  915. return r'${0}{1:g}$'.format(sign_string, x)
  916. else:
  917. return '${0}$'.format(_mathdefault(
  918. '{0}{1:g}'.format(sign_string, x)))
  919. elif not is_x_decade:
  920. return self._non_decade_format(sign_string, base, fx, usetex)
  921. elif usetex:
  922. return r'$%s%s^{%d}$' % (sign_string, base, fx)
  923. else:
  924. return '$%s$' % _mathdefault('%s%s^{%d}' % (sign_string, base, fx))
  925. class LogFormatterSciNotation(LogFormatterMathtext):
  926. """
  927. Format values following scientific notation in a logarithmic axis.
  928. """
  929. def _non_decade_format(self, sign_string, base, fx, usetex):
  930. 'Return string for non-decade locations'
  931. b = float(base)
  932. exponent = math.floor(fx)
  933. coeff = b ** fx / b ** exponent
  934. if is_close_to_int(coeff):
  935. coeff = round(coeff)
  936. if usetex:
  937. return (r'$%s%g\times%s^{%d}$') % \
  938. (sign_string, coeff, base, exponent)
  939. else:
  940. return ('$%s$' % _mathdefault(r'%s%g\times%s^{%d}' %
  941. (sign_string, coeff, base, exponent)))
  942. class LogitFormatter(Formatter):
  943. """
  944. Probability formatter (using Math text).
  945. """
  946. def __call__(self, x, pos=None):
  947. s = ''
  948. if 0.01 <= x <= 0.99:
  949. s = '{:.2f}'.format(x)
  950. elif x < 0.01:
  951. if is_decade(x):
  952. s = '$10^{{{:.0f}}}$'.format(np.log10(x))
  953. else:
  954. s = '${:.5f}$'.format(x)
  955. else: # x > 0.99
  956. if is_decade(1-x):
  957. s = '$1-10^{{{:.0f}}}$'.format(np.log10(1-x))
  958. else:
  959. s = '$1-{:.5f}$'.format(1-x)
  960. return s
  961. def format_data_short(self, value):
  962. 'return a short formatted string representation of a number'
  963. return '%-12g' % value
  964. class EngFormatter(Formatter):
  965. """
  966. Formats axis values using engineering prefixes to represent powers
  967. of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7.
  968. """
  969. # The SI engineering prefixes
  970. ENG_PREFIXES = {
  971. -24: "y",
  972. -21: "z",
  973. -18: "a",
  974. -15: "f",
  975. -12: "p",
  976. -9: "n",
  977. -6: "\N{GREEK SMALL LETTER MU}",
  978. -3: "m",
  979. 0: "",
  980. 3: "k",
  981. 6: "M",
  982. 9: "G",
  983. 12: "T",
  984. 15: "P",
  985. 18: "E",
  986. 21: "Z",
  987. 24: "Y"
  988. }
  989. def __init__(self, unit="", places=None, sep=" "):
  990. """
  991. Parameters
  992. ----------
  993. unit : str (default: "")
  994. Unit symbol to use, suitable for use with single-letter
  995. representations of powers of 1000. For example, 'Hz' or 'm'.
  996. places : int (default: None)
  997. Precision with which to display the number, specified in
  998. digits after the decimal point (there will be between one
  999. and three digits before the decimal point). If it is None,
  1000. the formatting falls back to the floating point format '%g',
  1001. which displays up to 6 *significant* digits, i.e. the equivalent
  1002. value for *places* varies between 0 and 5 (inclusive).
  1003. sep : str (default: " ")
  1004. Separator used between the value and the prefix/unit. For
  1005. example, one get '3.14 mV' if ``sep`` is " " (default) and
  1006. '3.14mV' if ``sep`` is "". Besides the default behavior, some
  1007. other useful options may be:
  1008. * ``sep=""`` to append directly the prefix/unit to the value;
  1009. * ``sep="\\N{THIN SPACE}"`` (``U+2009``);
  1010. * ``sep="\\N{NARROW NO-BREAK SPACE}"`` (``U+202F``);
  1011. * ``sep="\\N{NO-BREAK SPACE}"`` (``U+00A0``).
  1012. """
  1013. self.unit = unit
  1014. self.places = places
  1015. self.sep = sep
  1016. def __call__(self, x, pos=None):
  1017. s = "%s%s" % (self.format_eng(x), self.unit)
  1018. # Remove the trailing separator when there is neither prefix nor unit
  1019. if self.sep and s.endswith(self.sep):
  1020. s = s[:-len(self.sep)]
  1021. return self.fix_minus(s)
  1022. def format_eng(self, num):
  1023. """
  1024. Formats a number in engineering notation, appending a letter
  1025. representing the power of 1000 of the original number.
  1026. Some examples:
  1027. >>> format_eng(0) # for self.places = 0
  1028. '0'
  1029. >>> format_eng(1000000) # for self.places = 1
  1030. '1.0 M'
  1031. >>> format_eng("-1e-6") # for self.places = 2
  1032. '-1.00 \N{GREEK SMALL LETTER MU}'
  1033. """
  1034. sign = 1
  1035. fmt = "g" if self.places is None else ".{:d}f".format(self.places)
  1036. if num < 0:
  1037. sign = -1
  1038. num = -num
  1039. if num != 0:
  1040. pow10 = int(math.floor(math.log10(num) / 3) * 3)
  1041. else:
  1042. pow10 = 0
  1043. # Force num to zero, to avoid inconsistencies like
  1044. # format_eng(-0) = "0" and format_eng(0.0) = "0"
  1045. # but format_eng(-0.0) = "-0.0"
  1046. num = 0.0
  1047. pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES))
  1048. mant = sign * num / (10.0 ** pow10)
  1049. # Taking care of the cases like 999.9..., which may be rounded to 1000
  1050. # instead of 1 k. Beware of the corner case of values that are beyond
  1051. # the range of SI prefixes (i.e. > 'Y').
  1052. if float(format(mant, fmt)) >= 1000 and pow10 < max(self.ENG_PREFIXES):
  1053. mant /= 1000
  1054. pow10 += 3
  1055. prefix = self.ENG_PREFIXES[int(pow10)]
  1056. formatted = "{mant:{fmt}}{sep}{prefix}".format(
  1057. mant=mant, sep=self.sep, prefix=prefix, fmt=fmt)
  1058. return formatted
  1059. class PercentFormatter(Formatter):
  1060. """
  1061. Format numbers as a percentage.
  1062. Parameters
  1063. ----------
  1064. xmax : float
  1065. Determines how the number is converted into a percentage.
  1066. *xmax* is the data value that corresponds to 100%.
  1067. Percentages are computed as ``x / xmax * 100``. So if the data is
  1068. already scaled to be percentages, *xmax* will be 100. Another common
  1069. situation is where `xmax` is 1.0.
  1070. decimals : None or int
  1071. The number of decimal places to place after the point.
  1072. If *None* (the default), the number will be computed automatically.
  1073. symbol : string or None
  1074. A string that will be appended to the label. It may be
  1075. *None* or empty to indicate that no symbol should be used. LaTeX
  1076. special characters are escaped in *symbol* whenever latex mode is
  1077. enabled, unless *is_latex* is *True*.
  1078. is_latex : bool
  1079. If *False*, reserved LaTeX characters in *symbol* will be escaped.
  1080. """
  1081. def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False):
  1082. self.xmax = xmax + 0.0
  1083. self.decimals = decimals
  1084. self._symbol = symbol
  1085. self._is_latex = is_latex
  1086. def __call__(self, x, pos=None):
  1087. """
  1088. Formats the tick as a percentage with the appropriate scaling.
  1089. """
  1090. ax_min, ax_max = self.axis.get_view_interval()
  1091. display_range = abs(ax_max - ax_min)
  1092. return self.fix_minus(self.format_pct(x, display_range))
  1093. def format_pct(self, x, display_range):
  1094. """
  1095. Formats the number as a percentage number with the correct
  1096. number of decimals and adds the percent symbol, if any.
  1097. If `self.decimals` is `None`, the number of digits after the
  1098. decimal point is set based on the `display_range` of the axis
  1099. as follows:
  1100. +---------------+----------+------------------------+
  1101. | display_range | decimals | sample |
  1102. +---------------+----------+------------------------+
  1103. | >50 | 0 | ``x = 34.5`` => 35% |
  1104. +---------------+----------+------------------------+
  1105. | >5 | 1 | ``x = 34.5`` => 34.5% |
  1106. +---------------+----------+------------------------+
  1107. | >0.5 | 2 | ``x = 34.5`` => 34.50% |
  1108. +---------------+----------+------------------------+
  1109. | ... | ... | ... |
  1110. +---------------+----------+------------------------+
  1111. This method will not be very good for tiny axis ranges or
  1112. extremely large ones. It assumes that the values on the chart
  1113. are percentages displayed on a reasonable scale.
  1114. """
  1115. x = self.convert_to_pct(x)
  1116. if self.decimals is None:
  1117. # conversion works because display_range is a difference
  1118. scaled_range = self.convert_to_pct(display_range)
  1119. if scaled_range <= 0:
  1120. decimals = 0
  1121. else:
  1122. # Luckily Python's built-in ceil rounds to +inf, not away from
  1123. # zero. This is very important since the equation for decimals
  1124. # starts out as `scaled_range > 0.5 * 10**(2 - decimals)`
  1125. # and ends up with `decimals > 2 - log10(2 * scaled_range)`.
  1126. decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range))
  1127. if decimals > 5:
  1128. decimals = 5
  1129. elif decimals < 0:
  1130. decimals = 0
  1131. else:
  1132. decimals = self.decimals
  1133. s = '{x:0.{decimals}f}'.format(x=x, decimals=int(decimals))
  1134. return s + self.symbol
  1135. def convert_to_pct(self, x):
  1136. return 100.0 * (x / self.xmax)
  1137. @property
  1138. def symbol(self):
  1139. """
  1140. The configured percent symbol as a string.
  1141. If LaTeX is enabled via :rc:`text.usetex`, the special characters
  1142. ``{'#', '$', '%', '&', '~', '_', '^', '\\', '{', '}'}`` are
  1143. automatically escaped in the string.
  1144. """
  1145. symbol = self._symbol
  1146. if not symbol:
  1147. symbol = ''
  1148. elif rcParams['text.usetex'] and not self._is_latex:
  1149. # Source: http://www.personal.ceu.hu/tex/specchar.htm
  1150. # Backslash must be first for this to work correctly since
  1151. # it keeps getting added in
  1152. for spec in r'\#$%&~_^{}':
  1153. symbol = symbol.replace(spec, '\\' + spec)
  1154. return symbol
  1155. @symbol.setter
  1156. def symbol(self, symbol):
  1157. self._symbol = symbol
  1158. class Locator(TickHelper):
  1159. """
  1160. Determine the tick locations;
  1161. Note, you should not use the same locator between different
  1162. :class:`~matplotlib.axis.Axis` because the locator stores references to
  1163. the Axis data and view limits
  1164. """
  1165. # Some automatic tick locators can generate so many ticks they
  1166. # kill the machine when you try and render them.
  1167. # This parameter is set to cause locators to raise an error if too
  1168. # many ticks are generated.
  1169. MAXTICKS = 1000
  1170. def tick_values(self, vmin, vmax):
  1171. """
  1172. Return the values of the located ticks given **vmin** and **vmax**.
  1173. .. note::
  1174. To get tick locations with the vmin and vmax values defined
  1175. automatically for the associated :attr:`axis` simply call
  1176. the Locator instance::
  1177. >>> print(type(loc))
  1178. <type 'Locator'>
  1179. >>> print(loc())
  1180. [1, 2, 3, 4]
  1181. """
  1182. raise NotImplementedError('Derived must override')
  1183. def set_params(self, **kwargs):
  1184. """
  1185. Do nothing, and rase a warning. Any locator class not supporting the
  1186. set_params() function will call this.
  1187. """
  1188. warnings.warn("'set_params()' not defined for locator of type " +
  1189. str(type(self)))
  1190. def __call__(self):
  1191. """Return the locations of the ticks"""
  1192. # note: some locators return data limits, other return view limits,
  1193. # hence there is no *one* interface to call self.tick_values.
  1194. raise NotImplementedError('Derived must override')
  1195. def raise_if_exceeds(self, locs):
  1196. """raise a RuntimeError if Locator attempts to create more than
  1197. MAXTICKS locs"""
  1198. if len(locs) >= self.MAXTICKS:
  1199. raise RuntimeError("Locator attempting to generate {} ticks from "
  1200. "{} to {}: exceeds Locator.MAXTICKS".format(
  1201. len(locs), locs[0], locs[-1]))
  1202. return locs
  1203. def view_limits(self, vmin, vmax):
  1204. """
  1205. select a scale for the range from vmin to vmax
  1206. Normally this method is overridden by subclasses to
  1207. change locator behaviour.
  1208. """
  1209. return mtransforms.nonsingular(vmin, vmax)
  1210. def autoscale(self):
  1211. """autoscale the view limits"""
  1212. return self.view_limits(*self.axis.get_view_interval())
  1213. def pan(self, numsteps):
  1214. """Pan numticks (can be positive or negative)"""
  1215. ticks = self()
  1216. numticks = len(ticks)
  1217. vmin, vmax = self.axis.get_view_interval()
  1218. vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
  1219. if numticks > 2:
  1220. step = numsteps * abs(ticks[0] - ticks[1])
  1221. else:
  1222. d = abs(vmax - vmin)
  1223. step = numsteps * d / 6.
  1224. vmin += step
  1225. vmax += step
  1226. self.axis.set_view_interval(vmin, vmax, ignore=True)
  1227. def zoom(self, direction):
  1228. "Zoom in/out on axis; if direction is >0 zoom in, else zoom out"
  1229. vmin, vmax = self.axis.get_view_interval()
  1230. vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
  1231. interval = abs(vmax - vmin)
  1232. step = 0.1 * interval * direction
  1233. self.axis.set_view_interval(vmin + step, vmax - step, ignore=True)
  1234. def refresh(self):
  1235. """refresh internal information based on current lim"""
  1236. pass
  1237. class IndexLocator(Locator):
  1238. """
  1239. Place a tick on every multiple of some base number of points
  1240. plotted, e.g., on every 5th point. It is assumed that you are doing
  1241. index plotting; i.e., the axis is 0, len(data). This is mainly
  1242. useful for x ticks.
  1243. """
  1244. def __init__(self, base, offset):
  1245. 'place ticks on the i-th data points where (i-offset)%base==0'
  1246. self._base = base
  1247. self.offset = offset
  1248. def set_params(self, base=None, offset=None):
  1249. """Set parameters within this locator"""
  1250. if base is not None:
  1251. self._base = base
  1252. if offset is not None:
  1253. self.offset = offset
  1254. def __call__(self):
  1255. """Return the locations of the ticks"""
  1256. dmin, dmax = self.axis.get_data_interval()
  1257. return self.tick_values(dmin, dmax)
  1258. def tick_values(self, vmin, vmax):
  1259. return self.raise_if_exceeds(
  1260. np.arange(vmin + self.offset, vmax + 1, self._base))
  1261. class FixedLocator(Locator):
  1262. """
  1263. Tick locations are fixed. If nbins is not None,
  1264. the array of possible positions will be subsampled to
  1265. keep the number of ticks <= nbins +1.
  1266. The subsampling will be done so as to include the smallest
  1267. absolute value; for example, if zero is included in the
  1268. array of possibilities, then it is guaranteed to be one of
  1269. the chosen ticks.
  1270. """
  1271. def __init__(self, locs, nbins=None):
  1272. self.locs = np.asarray(locs)
  1273. self.nbins = max(nbins, 2) if nbins is not None else None
  1274. def set_params(self, nbins=None):
  1275. """Set parameters within this locator."""
  1276. if nbins is not None:
  1277. self.nbins = nbins
  1278. def __call__(self):
  1279. return self.tick_values(None, None)
  1280. def tick_values(self, vmin, vmax):
  1281. """"
  1282. Return the locations of the ticks.
  1283. .. note::
  1284. Because the values are fixed, vmin and vmax are not used in this
  1285. method.
  1286. """
  1287. if self.nbins is None:
  1288. return self.locs
  1289. step = max(int(np.ceil(len(self.locs) / self.nbins)), 1)
  1290. ticks = self.locs[::step]
  1291. for i in range(1, step):
  1292. ticks1 = self.locs[i::step]
  1293. if np.abs(ticks1).min() < np.abs(ticks).min():
  1294. ticks = ticks1
  1295. return self.raise_if_exceeds(ticks)
  1296. class NullLocator(Locator):
  1297. """
  1298. No ticks
  1299. """
  1300. def __call__(self):
  1301. return self.tick_values(None, None)
  1302. def tick_values(self, vmin, vmax):
  1303. """"
  1304. Return the locations of the ticks.
  1305. .. note::
  1306. Because the values are Null, vmin and vmax are not used in this
  1307. method.
  1308. """
  1309. return []
  1310. class LinearLocator(Locator):
  1311. """
  1312. Determine the tick locations
  1313. The first time this function is called it will try to set the
  1314. number of ticks to make a nice tick partitioning. Thereafter the
  1315. number of ticks will be fixed so that interactive navigation will
  1316. be nice
  1317. """
  1318. def __init__(self, numticks=None, presets=None):
  1319. """
  1320. Use presets to set locs based on lom. A dict mapping vmin, vmax->locs
  1321. """
  1322. self.numticks = numticks
  1323. if presets is None:
  1324. self.presets = {}
  1325. else:
  1326. self.presets = presets
  1327. def set_params(self, numticks=None, presets=None):
  1328. """Set parameters within this locator."""
  1329. if presets is not None:
  1330. self.presets = presets
  1331. if numticks is not None:
  1332. self.numticks = numticks
  1333. def __call__(self):
  1334. 'Return the locations of the ticks'
  1335. vmin, vmax = self.axis.get_view_interval()
  1336. return self.tick_values(vmin, vmax)
  1337. def tick_values(self, vmin, vmax):
  1338. vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
  1339. if vmax < vmin:
  1340. vmin, vmax = vmax, vmin
  1341. if (vmin, vmax) in self.presets:
  1342. return self.presets[(vmin, vmax)]
  1343. if self.numticks is None:
  1344. self._set_numticks()
  1345. if self.numticks == 0:
  1346. return []
  1347. ticklocs = np.linspace(vmin, vmax, self.numticks)
  1348. return self.raise_if_exceeds(ticklocs)
  1349. def _set_numticks(self):
  1350. self.numticks = 11 # todo; be smart here; this is just for dev
  1351. def view_limits(self, vmin, vmax):
  1352. 'Try to choose the view limits intelligently'
  1353. if vmax < vmin:
  1354. vmin, vmax = vmax, vmin
  1355. if vmin == vmax:
  1356. vmin -= 1
  1357. vmax += 1
  1358. if rcParams['axes.autolimit_mode'] == 'round_numbers':
  1359. exponent, remainder = _divmod(
  1360. math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1)))
  1361. exponent -= (remainder < .5)
  1362. scale = max(self.numticks - 1, 1) ** (-exponent)
  1363. vmin = math.floor(scale * vmin) / scale
  1364. vmax = math.ceil(scale * vmax) / scale
  1365. return mtransforms.nonsingular(vmin, vmax)
  1366. @cbook.deprecated("3.0")
  1367. def closeto(x, y):
  1368. return abs(x - y) < 1e-10
  1369. @cbook.deprecated("3.0")
  1370. class Base(object):
  1371. 'this solution has some hacks to deal with floating point inaccuracies'
  1372. def __init__(self, base):
  1373. if base <= 0:
  1374. raise ValueError("'base' must be positive")
  1375. self._base = base
  1376. def lt(self, x):
  1377. 'return the largest multiple of base < x'
  1378. d, m = _divmod(x, self._base)
  1379. if closeto(m, 0) and not closeto(m / self._base, 1):
  1380. return (d - 1) * self._base
  1381. return d * self._base
  1382. def le(self, x):
  1383. 'return the largest multiple of base <= x'
  1384. d, m = _divmod(x, self._base)
  1385. if closeto(m / self._base, 1): # was closeto(m, self._base)
  1386. #looks like floating point error
  1387. return (d + 1) * self._base
  1388. return d * self._base
  1389. def gt(self, x):
  1390. 'return the smallest multiple of base > x'
  1391. d, m = _divmod(x, self._base)
  1392. if closeto(m / self._base, 1):
  1393. #looks like floating point error
  1394. return (d + 2) * self._base
  1395. return (d + 1) * self._base
  1396. def ge(self, x):
  1397. 'return the smallest multiple of base >= x'
  1398. d, m = _divmod(x, self._base)
  1399. if closeto(m, 0) and not closeto(m / self._base, 1):
  1400. return d * self._base
  1401. return (d + 1) * self._base
  1402. def get_base(self):
  1403. return self._base
  1404. class MultipleLocator(Locator):
  1405. """
  1406. Set a tick on each integer multiple of a base within the view interval.
  1407. """
  1408. def __init__(self, base=1.0):
  1409. self._edge = _Edge_integer(base, 0)
  1410. def set_params(self, base):
  1411. """Set parameters within this locator."""
  1412. if base is not None:
  1413. self._edge = _Edge_integer(base, 0)
  1414. def __call__(self):
  1415. 'Return the locations of the ticks'
  1416. vmin, vmax = self.axis.get_view_interval()
  1417. return self.tick_values(vmin, vmax)
  1418. def tick_values(self, vmin, vmax):
  1419. if vmax < vmin:
  1420. vmin, vmax = vmax, vmin
  1421. step = self._edge.step
  1422. vmin = self._edge.ge(vmin) * step
  1423. n = (vmax - vmin + 0.001 * step) // step
  1424. locs = vmin - step + np.arange(n + 3) * step
  1425. return self.raise_if_exceeds(locs)
  1426. def view_limits(self, dmin, dmax):
  1427. """
  1428. Set the view limits to the nearest multiples of base that
  1429. contain the data.
  1430. """
  1431. if rcParams['axes.autolimit_mode'] == 'round_numbers':
  1432. vmin = self._edge.le(dmin) * self._edge.step
  1433. vmax = self._edge.ge(dmax) * self._edge.step
  1434. if vmin == vmax:
  1435. vmin -= 1
  1436. vmax += 1
  1437. else:
  1438. vmin = dmin
  1439. vmax = dmax
  1440. return mtransforms.nonsingular(vmin, vmax)
  1441. def scale_range(vmin, vmax, n=1, threshold=100):
  1442. dv = abs(vmax - vmin) # > 0 as nonsingular is called before.
  1443. meanv = (vmax + vmin) / 2
  1444. if abs(meanv) / dv < threshold:
  1445. offset = 0
  1446. else:
  1447. offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv)
  1448. scale = 10 ** (math.log10(dv / n) // 1)
  1449. return scale, offset
  1450. class _Edge_integer:
  1451. """
  1452. Helper for MaxNLocator, MultipleLocator, etc.
  1453. Take floating point precision limitations into account when calculating
  1454. tick locations as integer multiples of a step.
  1455. """
  1456. def __init__(self, step, offset):
  1457. """
  1458. *step* is a positive floating-point interval between ticks.
  1459. *offset* is the offset subtracted from the data limits
  1460. prior to calculating tick locations.
  1461. """
  1462. if step <= 0:
  1463. raise ValueError("'step' must be positive")
  1464. self.step = step
  1465. self._offset = abs(offset)
  1466. def closeto(self, ms, edge):
  1467. # Allow more slop when the offset is large compared to the step.
  1468. if self._offset > 0:
  1469. digits = np.log10(self._offset / self.step)
  1470. tol = max(1e-10, 10 ** (digits - 12))
  1471. tol = min(0.4999, tol)
  1472. else:
  1473. tol = 1e-10
  1474. return abs(ms - edge) < tol
  1475. def le(self, x):
  1476. 'Return the largest n: n*step <= x.'
  1477. d, m = _divmod(x, self.step)
  1478. if self.closeto(m / self.step, 1):
  1479. return (d + 1)
  1480. return d
  1481. def ge(self, x):
  1482. 'Return the smallest n: n*step >= x.'
  1483. d, m = _divmod(x, self.step)
  1484. if self.closeto(m / self.step, 0):
  1485. return d
  1486. return (d + 1)
  1487. class MaxNLocator(Locator):
  1488. """
  1489. Select no more than N intervals at nice locations.
  1490. """
  1491. default_params = dict(nbins=10,
  1492. steps=None,
  1493. integer=False,
  1494. symmetric=False,
  1495. prune=None,
  1496. min_n_ticks=2)
  1497. def __init__(self, *args, **kwargs):
  1498. """
  1499. Keyword args:
  1500. *nbins*
  1501. Maximum number of intervals; one less than max number of
  1502. ticks. If the string `'auto'`, the number of bins will be
  1503. automatically determined based on the length of the axis.
  1504. *steps*
  1505. Sequence of nice numbers starting with 1 and ending with 10;
  1506. e.g., [1, 2, 4, 5, 10], where the values are acceptable
  1507. tick multiples. i.e. for the example, 20, 40, 60 would be
  1508. an acceptable set of ticks, as would 0.4, 0.6, 0.8, because
  1509. they are multiples of 2. However, 30, 60, 90 would not
  1510. be allowed because 3 does not appear in the list of steps.
  1511. *integer*
  1512. If True, ticks will take only integer values, provided
  1513. at least `min_n_ticks` integers are found within the
  1514. view limits.
  1515. *symmetric*
  1516. If True, autoscaling will result in a range symmetric
  1517. about zero.
  1518. *prune*
  1519. ['lower' | 'upper' | 'both' | None]
  1520. Remove edge ticks -- useful for stacked or ganged plots where
  1521. the upper tick of one axes overlaps with the lower tick of the
  1522. axes above it, primarily when :rc:`axes.autolimit_mode` is
  1523. ``'round_numbers'``. If ``prune=='lower'``, the smallest tick will
  1524. be removed. If ``prune == 'upper'``, the largest tick will be
  1525. removed. If ``prune == 'both'``, the largest and smallest ticks
  1526. will be removed. If ``prune == None``, no ticks will be removed.
  1527. *min_n_ticks*
  1528. Relax `nbins` and `integer` constraints if necessary to
  1529. obtain this minimum number of ticks.
  1530. """
  1531. if args:
  1532. kwargs['nbins'] = args[0]
  1533. if len(args) > 1:
  1534. raise ValueError(
  1535. "Keywords are required for all arguments except 'nbins'")
  1536. self.set_params(**self.default_params)
  1537. self.set_params(**kwargs)
  1538. @staticmethod
  1539. def _validate_steps(steps):
  1540. if not np.iterable(steps):
  1541. raise ValueError('steps argument must be a sequence of numbers '
  1542. 'from 1 to 10')
  1543. steps = np.asarray(steps)
  1544. if np.any(np.diff(steps) <= 0):
  1545. raise ValueError('steps argument must be uniformly increasing')
  1546. if steps[-1] > 10 or steps[0] < 1:
  1547. warnings.warn('Steps argument should be a sequence of numbers\n'
  1548. 'increasing from 1 to 10, inclusive. Behavior with\n'
  1549. 'values outside this range is undefined, and will\n'
  1550. 'raise a ValueError in future versions of mpl.')
  1551. if steps[0] != 1:
  1552. steps = np.hstack((1, steps))
  1553. if steps[-1] != 10:
  1554. steps = np.hstack((steps, 10))
  1555. return steps
  1556. @staticmethod
  1557. def _staircase(steps):
  1558. # Make an extended staircase within which the needed
  1559. # step will be found. This is probably much larger
  1560. # than necessary.
  1561. flights = (0.1 * steps[:-1], steps, 10 * steps[1])
  1562. return np.hstack(flights)
  1563. def set_params(self, **kwargs):
  1564. """Set parameters within this locator."""
  1565. if 'nbins' in kwargs:
  1566. self._nbins = kwargs['nbins']
  1567. if self._nbins != 'auto':
  1568. self._nbins = int(self._nbins)
  1569. if 'symmetric' in kwargs:
  1570. self._symmetric = kwargs['symmetric']
  1571. if 'prune' in kwargs:
  1572. prune = kwargs['prune']
  1573. if prune is not None and prune not in ['upper', 'lower', 'both']:
  1574. raise ValueError(
  1575. "prune must be 'upper', 'lower', 'both', or None")
  1576. self._prune = prune
  1577. if 'min_n_ticks' in kwargs:
  1578. self._min_n_ticks = max(1, kwargs['min_n_ticks'])
  1579. if 'steps' in kwargs:
  1580. steps = kwargs['steps']
  1581. if steps is None:
  1582. self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10])
  1583. else:
  1584. self._steps = self._validate_steps(steps)
  1585. self._extended_steps = self._staircase(self._steps)
  1586. if 'integer' in kwargs:
  1587. self._integer = kwargs['integer']
  1588. def _raw_ticks(self, vmin, vmax):
  1589. """
  1590. Generate a list of tick locations including the range *vmin* to
  1591. *vmax*. In some applications, one or both of the end locations
  1592. will not be needed, in which case they are trimmed off
  1593. elsewhere.
  1594. """
  1595. if self._nbins == 'auto':
  1596. if self.axis is not None:
  1597. nbins = np.clip(self.axis.get_tick_space(),
  1598. max(1, self._min_n_ticks - 1), 9)
  1599. else:
  1600. nbins = 9
  1601. else:
  1602. nbins = self._nbins
  1603. scale, offset = scale_range(vmin, vmax, nbins)
  1604. _vmin = vmin - offset
  1605. _vmax = vmax - offset
  1606. raw_step = (_vmax - _vmin) / nbins
  1607. steps = self._extended_steps * scale
  1608. if self._integer:
  1609. # For steps > 1, keep only integer values.
  1610. igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001)
  1611. steps = steps[igood]
  1612. istep = np.nonzero(steps >= raw_step)[0][0]
  1613. # Classic round_numbers mode may require a larger step.
  1614. if rcParams['axes.autolimit_mode'] == 'round_numbers':
  1615. for istep in range(istep, len(steps)):
  1616. step = steps[istep]
  1617. best_vmin = (_vmin // step) * step
  1618. best_vmax = best_vmin + step * nbins
  1619. if best_vmax >= _vmax:
  1620. break
  1621. # This is an upper limit; move to smaller steps if necessary.
  1622. for istep in reversed(range(istep + 1)):
  1623. step = steps[istep]
  1624. if (self._integer and
  1625. np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1):
  1626. step = max(1, step)
  1627. best_vmin = (_vmin // step) * step
  1628. # Find tick locations spanning the vmin-vmax range, taking into
  1629. # account degradation of precision when there is a large offset.
  1630. # The edge ticks beyond vmin and/or vmax are needed for the
  1631. # "round_numbers" autolimit mode.
  1632. edge = _Edge_integer(step, offset)
  1633. low = edge.le(_vmin - best_vmin)
  1634. high = edge.ge(_vmax - best_vmin)
  1635. ticks = np.arange(low, high + 1) * step + best_vmin
  1636. # Count only the ticks that will be displayed.
  1637. nticks = ((ticks <= _vmax) & (ticks >= _vmin)).sum()
  1638. if nticks >= self._min_n_ticks:
  1639. break
  1640. return ticks + offset
  1641. def __call__(self):
  1642. vmin, vmax = self.axis.get_view_interval()
  1643. return self.tick_values(vmin, vmax)
  1644. def tick_values(self, vmin, vmax):
  1645. if self._symmetric:
  1646. vmax = max(abs(vmin), abs(vmax))
  1647. vmin = -vmax
  1648. vmin, vmax = mtransforms.nonsingular(
  1649. vmin, vmax, expander=1e-13, tiny=1e-14)
  1650. locs = self._raw_ticks(vmin, vmax)
  1651. prune = self._prune
  1652. if prune == 'lower':
  1653. locs = locs[1:]
  1654. elif prune == 'upper':
  1655. locs = locs[:-1]
  1656. elif prune == 'both':
  1657. locs = locs[1:-1]
  1658. return self.raise_if_exceeds(locs)
  1659. def view_limits(self, dmin, dmax):
  1660. if self._symmetric:
  1661. dmax = max(abs(dmin), abs(dmax))
  1662. dmin = -dmax
  1663. dmin, dmax = mtransforms.nonsingular(
  1664. dmin, dmax, expander=1e-12, tiny=1e-13)
  1665. if rcParams['axes.autolimit_mode'] == 'round_numbers':
  1666. return self._raw_ticks(dmin, dmax)[[0, -1]]
  1667. else:
  1668. return dmin, dmax
  1669. def decade_down(x, base=10):
  1670. 'floor x to the nearest lower decade'
  1671. if x == 0.0:
  1672. return -base
  1673. lx = np.floor(np.log(x) / np.log(base))
  1674. return base ** lx
  1675. def decade_up(x, base=10):
  1676. 'ceil x to the nearest higher decade'
  1677. if x == 0.0:
  1678. return base
  1679. lx = np.ceil(np.log(x) / np.log(base))
  1680. return base ** lx
  1681. def nearest_long(x):
  1682. cbook.warn_deprecated('3.0', removal='3.1', name='`nearest_long`',
  1683. obj_type='function', alternative='`round`')
  1684. if x >= 0:
  1685. return int(x + 0.5)
  1686. return int(x - 0.5)
  1687. def is_decade(x, base=10):
  1688. if not np.isfinite(x):
  1689. return False
  1690. if x == 0.0:
  1691. return True
  1692. lx = np.log(np.abs(x)) / np.log(base)
  1693. return is_close_to_int(lx)
  1694. def is_close_to_int(x):
  1695. if not np.isfinite(x):
  1696. return False
  1697. return abs(x - round(x)) < 1e-10
  1698. class LogLocator(Locator):
  1699. """
  1700. Determine the tick locations for log axes
  1701. """
  1702. def __init__(self, base=10.0, subs=(1.0,), numdecs=4, numticks=None):
  1703. """
  1704. Place ticks on the locations : subs[j] * base**i
  1705. Parameters
  1706. ----------
  1707. subs : None, string, or sequence of float, optional, default (1.0,)
  1708. Gives the multiples of integer powers of the base at which
  1709. to place ticks. The default places ticks only at
  1710. integer powers of the base.
  1711. The permitted string values are ``'auto'`` and ``'all'``,
  1712. both of which use an algorithm based on the axis view
  1713. limits to determine whether and how to put ticks between
  1714. integer powers of the base. With ``'auto'``, ticks are
  1715. placed only between integer powers; with ``'all'``, the
  1716. integer powers are included. A value of None is
  1717. equivalent to ``'auto'``.
  1718. """
  1719. if numticks is None:
  1720. if rcParams['_internal.classic_mode']:
  1721. numticks = 15
  1722. else:
  1723. numticks = 'auto'
  1724. self.base(base)
  1725. self.subs(subs)
  1726. self.numdecs = numdecs
  1727. self.numticks = numticks
  1728. def set_params(self, base=None, subs=None, numdecs=None, numticks=None):
  1729. """Set parameters within this locator."""
  1730. if base is not None:
  1731. self.base(base)
  1732. if subs is not None:
  1733. self.subs(subs)
  1734. if numdecs is not None:
  1735. self.numdecs = numdecs
  1736. if numticks is not None:
  1737. self.numticks = numticks
  1738. # FIXME: these base and subs functions are contrary to our
  1739. # usual and desired API.
  1740. def base(self, base):
  1741. """
  1742. set the base of the log scaling (major tick every base**i, i integer)
  1743. """
  1744. self._base = float(base)
  1745. def subs(self, subs):
  1746. """
  1747. set the minor ticks for the log scaling every base**i*subs[j]
  1748. """
  1749. if subs is None: # consistency with previous bad API
  1750. self._subs = 'auto'
  1751. elif isinstance(subs, str):
  1752. if subs not in ('all', 'auto'):
  1753. raise ValueError("A subs string must be 'all' or 'auto'; "
  1754. "found '%s'." % subs)
  1755. self._subs = subs
  1756. else:
  1757. self._subs = np.asarray(subs, dtype=float)
  1758. def __call__(self):
  1759. 'Return the locations of the ticks'
  1760. vmin, vmax = self.axis.get_view_interval()
  1761. return self.tick_values(vmin, vmax)
  1762. def tick_values(self, vmin, vmax):
  1763. if self.numticks == 'auto':
  1764. if self.axis is not None:
  1765. numticks = np.clip(self.axis.get_tick_space(), 2, 9)
  1766. else:
  1767. numticks = 9
  1768. else:
  1769. numticks = self.numticks
  1770. b = self._base
  1771. # dummy axis has no axes attribute
  1772. if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar':
  1773. vmax = math.ceil(math.log(vmax) / math.log(b))
  1774. decades = np.arange(vmax - self.numdecs, vmax)
  1775. ticklocs = b ** decades
  1776. return ticklocs
  1777. if vmin <= 0.0:
  1778. if self.axis is not None:
  1779. vmin = self.axis.get_minpos()
  1780. if vmin <= 0.0 or not np.isfinite(vmin):
  1781. raise ValueError(
  1782. "Data has no positive values, and therefore can not be "
  1783. "log-scaled.")
  1784. _log.debug('vmin %s vmax %s', vmin, vmax)
  1785. vmin = math.log(vmin) / math.log(b)
  1786. vmax = math.log(vmax) / math.log(b)
  1787. if vmax < vmin:
  1788. vmin, vmax = vmax, vmin
  1789. numdec = math.floor(vmax) - math.ceil(vmin)
  1790. if isinstance(self._subs, str):
  1791. _first = 2.0 if self._subs == 'auto' else 1.0
  1792. if numdec > 10 or b < 3:
  1793. if self._subs == 'auto':
  1794. return np.array([]) # no minor or major ticks
  1795. else:
  1796. subs = np.array([1.0]) # major ticks
  1797. else:
  1798. subs = np.arange(_first, b)
  1799. else:
  1800. subs = self._subs
  1801. # get decades between major ticks.
  1802. stride = 1
  1803. if rcParams['_internal.classic_mode']:
  1804. # Leave the bug left over from the PY2-PY3 transition.
  1805. while numdec / stride + 1 > numticks:
  1806. stride += 1
  1807. else:
  1808. while numdec // stride + 1 > numticks:
  1809. stride += 1
  1810. # Does subs include anything other than 1?
  1811. have_subs = len(subs) > 1 or (len(subs == 1) and subs[0] != 1.0)
  1812. decades = np.arange(math.floor(vmin) - stride,
  1813. math.ceil(vmax) + 2 * stride, stride)
  1814. if hasattr(self, '_transform'):
  1815. ticklocs = self._transform.inverted().transform(decades)
  1816. if have_subs:
  1817. if stride == 1:
  1818. ticklocs = np.ravel(np.outer(subs, ticklocs))
  1819. else:
  1820. # no ticklocs if we have more than one decade
  1821. # between major ticks.
  1822. ticklocs = []
  1823. else:
  1824. if have_subs:
  1825. ticklocs = []
  1826. if stride == 1:
  1827. for decadeStart in b ** decades:
  1828. ticklocs.extend(subs * decadeStart)
  1829. else:
  1830. ticklocs = b ** decades
  1831. _log.debug('ticklocs %r', ticklocs)
  1832. return self.raise_if_exceeds(np.asarray(ticklocs))
  1833. def view_limits(self, vmin, vmax):
  1834. 'Try to choose the view limits intelligently'
  1835. b = self._base
  1836. vmin, vmax = self.nonsingular(vmin, vmax)
  1837. if self.axis.axes.name == 'polar':
  1838. vmax = math.ceil(math.log(vmax) / math.log(b))
  1839. vmin = b ** (vmax - self.numdecs)
  1840. if rcParams['axes.autolimit_mode'] == 'round_numbers':
  1841. if not is_decade(vmin, self._base):
  1842. vmin = decade_down(vmin, self._base)
  1843. if not is_decade(vmax, self._base):
  1844. vmax = decade_up(vmax, self._base)
  1845. return vmin, vmax
  1846. def nonsingular(self, vmin, vmax):
  1847. if not np.isfinite(vmin) or not np.isfinite(vmax):
  1848. return 1, 10 # initial range, no data plotted yet
  1849. if vmin > vmax:
  1850. vmin, vmax = vmax, vmin
  1851. if vmax <= 0:
  1852. warnings.warn(
  1853. "Data has no positive values, and therefore cannot be "
  1854. "log-scaled.")
  1855. return 1, 10
  1856. minpos = self.axis.get_minpos()
  1857. if not np.isfinite(minpos):
  1858. minpos = 1e-300 # This should never take effect.
  1859. if vmin <= 0:
  1860. vmin = minpos
  1861. if vmin == vmax:
  1862. vmin = decade_down(vmin, self._base)
  1863. vmax = decade_up(vmax, self._base)
  1864. return vmin, vmax
  1865. class SymmetricalLogLocator(Locator):
  1866. """
  1867. Determine the tick locations for symmetric log axes
  1868. """
  1869. def __init__(self, transform=None, subs=None, linthresh=None, base=None):
  1870. """
  1871. place ticks on the location= base**i*subs[j]
  1872. """
  1873. if transform is not None:
  1874. self._base = transform.base
  1875. self._linthresh = transform.linthresh
  1876. elif linthresh is not None and base is not None:
  1877. self._base = base
  1878. self._linthresh = linthresh
  1879. else:
  1880. raise ValueError("Either transform, or both linthresh "
  1881. "and base, must be provided.")
  1882. if subs is None:
  1883. self._subs = [1.0]
  1884. else:
  1885. self._subs = subs
  1886. self.numticks = 15
  1887. def set_params(self, subs=None, numticks=None):
  1888. """Set parameters within this locator."""
  1889. if numticks is not None:
  1890. self.numticks = numticks
  1891. if subs is not None:
  1892. self._subs = subs
  1893. def __call__(self):
  1894. 'Return the locations of the ticks'
  1895. # Note, these are untransformed coordinates
  1896. vmin, vmax = self.axis.get_view_interval()
  1897. return self.tick_values(vmin, vmax)
  1898. def tick_values(self, vmin, vmax):
  1899. b = self._base
  1900. t = self._linthresh
  1901. if vmax < vmin:
  1902. vmin, vmax = vmax, vmin
  1903. # The domain is divided into three sections, only some of
  1904. # which may actually be present.
  1905. #
  1906. # <======== -t ==0== t ========>
  1907. # aaaaaaaaa bbbbb ccccccccc
  1908. #
  1909. # a) and c) will have ticks at integral log positions. The
  1910. # number of ticks needs to be reduced if there are more
  1911. # than self.numticks of them.
  1912. #
  1913. # b) has a tick at 0 and only 0 (we assume t is a small
  1914. # number, and the linear segment is just an implementation
  1915. # detail and not interesting.)
  1916. #
  1917. # We could also add ticks at t, but that seems to usually be
  1918. # uninteresting.
  1919. #
  1920. # "simple" mode is when the range falls entirely within (-t,
  1921. # t) -- it should just display (vmin, 0, vmax)
  1922. has_a = has_b = has_c = False
  1923. if vmin < -t:
  1924. has_a = True
  1925. if vmax > -t:
  1926. has_b = True
  1927. if vmax > t:
  1928. has_c = True
  1929. elif vmin < 0:
  1930. if vmax > 0:
  1931. has_b = True
  1932. if vmax > t:
  1933. has_c = True
  1934. else:
  1935. return [vmin, vmax]
  1936. elif vmin < t:
  1937. if vmax > t:
  1938. has_b = True
  1939. has_c = True
  1940. else:
  1941. return [vmin, vmax]
  1942. else:
  1943. has_c = True
  1944. def get_log_range(lo, hi):
  1945. lo = np.floor(np.log(lo) / np.log(b))
  1946. hi = np.ceil(np.log(hi) / np.log(b))
  1947. return lo, hi
  1948. # First, calculate all the ranges, so we can determine striding
  1949. if has_a:
  1950. if has_b:
  1951. a_range = get_log_range(t, -vmin + 1)
  1952. else:
  1953. a_range = get_log_range(-vmax, -vmin + 1)
  1954. else:
  1955. a_range = (0, 0)
  1956. if has_c:
  1957. if has_b:
  1958. c_range = get_log_range(t, vmax + 1)
  1959. else:
  1960. c_range = get_log_range(vmin, vmax + 1)
  1961. else:
  1962. c_range = (0, 0)
  1963. total_ticks = (a_range[1] - a_range[0]) + (c_range[1] - c_range[0])
  1964. if has_b:
  1965. total_ticks += 1
  1966. stride = max(total_ticks // (self.numticks - 1), 1)
  1967. decades = []
  1968. if has_a:
  1969. decades.extend(-1 * (b ** (np.arange(a_range[0], a_range[1],
  1970. stride)[::-1])))
  1971. if has_b:
  1972. decades.append(0.0)
  1973. if has_c:
  1974. decades.extend(b ** (np.arange(c_range[0], c_range[1], stride)))
  1975. # Add the subticks if requested
  1976. if self._subs is None:
  1977. subs = np.arange(2.0, b)
  1978. else:
  1979. subs = np.asarray(self._subs)
  1980. if len(subs) > 1 or subs[0] != 1.0:
  1981. ticklocs = []
  1982. for decade in decades:
  1983. if decade == 0:
  1984. ticklocs.append(decade)
  1985. else:
  1986. ticklocs.extend(subs * decade)
  1987. else:
  1988. ticklocs = decades
  1989. return self.raise_if_exceeds(np.array(ticklocs))
  1990. def view_limits(self, vmin, vmax):
  1991. 'Try to choose the view limits intelligently'
  1992. b = self._base
  1993. if vmax < vmin:
  1994. vmin, vmax = vmax, vmin
  1995. if rcParams['axes.autolimit_mode'] == 'round_numbers':
  1996. if not is_decade(abs(vmin), b):
  1997. if vmin < 0:
  1998. vmin = -decade_up(-vmin, b)
  1999. else:
  2000. vmin = decade_down(vmin, b)
  2001. if not is_decade(abs(vmax), b):
  2002. if vmax < 0:
  2003. vmax = -decade_down(-vmax, b)
  2004. else:
  2005. vmax = decade_up(vmax, b)
  2006. if vmin == vmax:
  2007. if vmin < 0:
  2008. vmin = -decade_up(-vmin, b)
  2009. vmax = -decade_down(-vmax, b)
  2010. else:
  2011. vmin = decade_down(vmin, b)
  2012. vmax = decade_up(vmax, b)
  2013. result = mtransforms.nonsingular(vmin, vmax)
  2014. return result
  2015. class LogitLocator(Locator):
  2016. """
  2017. Determine the tick locations for logit axes
  2018. """
  2019. def __init__(self, minor=False):
  2020. """
  2021. place ticks on the logit locations
  2022. """
  2023. self.minor = minor
  2024. def set_params(self, minor=None):
  2025. """Set parameters within this locator."""
  2026. if minor is not None:
  2027. self.minor = minor
  2028. def __call__(self):
  2029. 'Return the locations of the ticks'
  2030. vmin, vmax = self.axis.get_view_interval()
  2031. return self.tick_values(vmin, vmax)
  2032. def tick_values(self, vmin, vmax):
  2033. # dummy axis has no axes attribute
  2034. if hasattr(self.axis, 'axes') and self.axis.axes.name == 'polar':
  2035. raise NotImplementedError('Polar axis cannot be logit scaled yet')
  2036. vmin, vmax = self.nonsingular(vmin, vmax)
  2037. vmin = np.log10(vmin / (1 - vmin))
  2038. vmax = np.log10(vmax / (1 - vmax))
  2039. decade_min = np.floor(vmin)
  2040. decade_max = np.ceil(vmax)
  2041. # major ticks
  2042. if not self.minor:
  2043. ticklocs = []
  2044. if decade_min <= -1:
  2045. expo = np.arange(decade_min, min(0, decade_max + 1))
  2046. ticklocs.extend(10**expo)
  2047. if decade_min <= 0 <= decade_max:
  2048. ticklocs.append(0.5)
  2049. if decade_max >= 1:
  2050. expo = -np.arange(max(1, decade_min), decade_max + 1)
  2051. ticklocs.extend(1 - 10**expo)
  2052. # minor ticks
  2053. else:
  2054. ticklocs = []
  2055. if decade_min <= -2:
  2056. expo = np.arange(decade_min, min(-1, decade_max))
  2057. newticks = np.outer(np.arange(2, 10), 10**expo).ravel()
  2058. ticklocs.extend(newticks)
  2059. if decade_min <= 0 <= decade_max:
  2060. ticklocs.extend([0.2, 0.3, 0.4, 0.6, 0.7, 0.8])
  2061. if decade_max >= 2:
  2062. expo = -np.arange(max(2, decade_min), decade_max + 1)
  2063. newticks = 1 - np.outer(np.arange(2, 10), 10**expo).ravel()
  2064. ticklocs.extend(newticks)
  2065. return self.raise_if_exceeds(np.array(ticklocs))
  2066. def nonsingular(self, vmin, vmax):
  2067. initial_range = (1e-7, 1 - 1e-7)
  2068. if not np.isfinite(vmin) or not np.isfinite(vmax):
  2069. return initial_range # no data plotted yet
  2070. if vmin > vmax:
  2071. vmin, vmax = vmax, vmin
  2072. # what to do if a window beyond ]0, 1[ is chosen
  2073. if self.axis is not None:
  2074. minpos = self.axis.get_minpos()
  2075. if not np.isfinite(minpos):
  2076. return initial_range # again, no data plotted
  2077. else:
  2078. minpos = 1e-7 # should not occur in normal use
  2079. # NOTE: for vmax, we should query a property similar to get_minpos, but
  2080. # related to the maximal, less-than-one data point. Unfortunately,
  2081. # Bbox._minpos is defined very deep in the BBox and updated with data,
  2082. # so for now we use 1 - minpos as a substitute.
  2083. if vmin <= 0:
  2084. vmin = minpos
  2085. if vmax >= 1:
  2086. vmax = 1 - minpos
  2087. if vmin == vmax:
  2088. return 0.1 * vmin, 1 - 0.1 * vmin
  2089. return vmin, vmax
  2090. class AutoLocator(MaxNLocator):
  2091. """
  2092. Dynamically find major tick positions. This is actually a subclass
  2093. of `~matplotlib.ticker.MaxNLocator`, with parameters *nbins = 'auto'*
  2094. and *steps = [1, 2, 2.5, 5, 10]*.
  2095. """
  2096. def __init__(self):
  2097. """
  2098. To know the values of the non-public parameters, please have a
  2099. look to the defaults of `~matplotlib.ticker.MaxNLocator`.
  2100. """
  2101. if rcParams['_internal.classic_mode']:
  2102. nbins = 9
  2103. steps = [1, 2, 5, 10]
  2104. else:
  2105. nbins = 'auto'
  2106. steps = [1, 2, 2.5, 5, 10]
  2107. MaxNLocator.__init__(self, nbins=nbins, steps=steps)
  2108. class AutoMinorLocator(Locator):
  2109. """
  2110. Dynamically find minor tick positions based on the positions of
  2111. major ticks. The scale must be linear with major ticks evenly spaced.
  2112. """
  2113. def __init__(self, n=None):
  2114. """
  2115. *n* is the number of subdivisions of the interval between
  2116. major ticks; e.g., n=2 will place a single minor tick midway
  2117. between major ticks.
  2118. If *n* is omitted or None, it will be set to 5 or 4.
  2119. """
  2120. self.ndivs = n
  2121. def __call__(self):
  2122. 'Return the locations of the ticks'
  2123. if self.axis.get_scale() == 'log':
  2124. warnings.warn('AutoMinorLocator does not work with logarithmic '
  2125. 'scale')
  2126. return []
  2127. majorlocs = self.axis.get_majorticklocs()
  2128. try:
  2129. majorstep = majorlocs[1] - majorlocs[0]
  2130. except IndexError:
  2131. # Need at least two major ticks to find minor tick locations
  2132. # TODO: Figure out a way to still be able to display minor
  2133. # ticks without two major ticks visible. For now, just display
  2134. # no ticks at all.
  2135. return []
  2136. if self.ndivs is None:
  2137. x = int(np.round(10 ** (np.log10(majorstep) % 1)))
  2138. if x in [1, 5, 10]:
  2139. ndivs = 5
  2140. else:
  2141. ndivs = 4
  2142. else:
  2143. ndivs = self.ndivs
  2144. minorstep = majorstep / ndivs
  2145. vmin, vmax = self.axis.get_view_interval()
  2146. if vmin > vmax:
  2147. vmin, vmax = vmax, vmin
  2148. t0 = majorlocs[0]
  2149. tmin = ((vmin - t0) // minorstep + 1) * minorstep
  2150. tmax = ((vmax - t0) // minorstep + 1) * minorstep
  2151. locs = np.arange(tmin, tmax, minorstep) + t0
  2152. mod = np.abs((locs - t0) % majorstep)
  2153. cond1 = mod > minorstep / 10.0
  2154. cond2 = ~np.isclose(mod, majorstep, atol=0)
  2155. locs = locs.compress(cond1 & cond2)
  2156. return self.raise_if_exceeds(np.array(locs))
  2157. def tick_values(self, vmin, vmax):
  2158. raise NotImplementedError('Cannot get tick locations for a '
  2159. '%s type.' % type(self))
  2160. class OldAutoLocator(Locator):
  2161. """
  2162. On autoscale this class picks the best MultipleLocator to set the
  2163. view limits and the tick locs.
  2164. """
  2165. def __init__(self):
  2166. self._locator = LinearLocator()
  2167. def __call__(self):
  2168. 'Return the locations of the ticks'
  2169. self.refresh()
  2170. return self.raise_if_exceeds(self._locator())
  2171. def tick_values(self, vmin, vmax):
  2172. raise NotImplementedError('Cannot get tick locations for a '
  2173. '%s type.' % type(self))
  2174. def refresh(self):
  2175. 'refresh internal information based on current lim'
  2176. vmin, vmax = self.axis.get_view_interval()
  2177. vmin, vmax = mtransforms.nonsingular(vmin, vmax, expander=0.05)
  2178. d = abs(vmax - vmin)
  2179. self._locator = self.get_locator(d)
  2180. def view_limits(self, vmin, vmax):
  2181. 'Try to choose the view limits intelligently'
  2182. d = abs(vmax - vmin)
  2183. self._locator = self.get_locator(d)
  2184. return self._locator.view_limits(vmin, vmax)
  2185. def get_locator(self, d):
  2186. 'pick the best locator based on a distance'
  2187. d = abs(d)
  2188. if d <= 0:
  2189. locator = MultipleLocator(0.2)
  2190. else:
  2191. try:
  2192. ld = math.log10(d)
  2193. except OverflowError:
  2194. raise RuntimeError('AutoLocator illegal data interval range')
  2195. fld = math.floor(ld)
  2196. base = 10 ** fld
  2197. #if ld==fld: base = 10**(fld-1)
  2198. #else: base = 10**fld
  2199. if d >= 5 * base:
  2200. ticksize = base
  2201. elif d >= 2 * base:
  2202. ticksize = base / 2.0
  2203. else:
  2204. ticksize = base / 5.0
  2205. locator = MultipleLocator(ticksize)
  2206. return locator