ticker.py 99 KB

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