ticker.py 102 KB

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