test_ticker.py 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. from contextlib import nullcontext
  2. import itertools
  3. import locale
  4. import logging
  5. import re
  6. import numpy as np
  7. from numpy.testing import assert_almost_equal, assert_array_equal
  8. import pytest
  9. import matplotlib as mpl
  10. import matplotlib.pyplot as plt
  11. import matplotlib.ticker as mticker
  12. class TestMaxNLocator:
  13. basic_data = [
  14. (20, 100, np.array([20., 40., 60., 80., 100.])),
  15. (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])),
  16. (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])),
  17. (0, 0.85e-50, np.arange(6) * 2e-51),
  18. (-0.85e-50, 0, np.arange(-5, 1) * 2e-51),
  19. ]
  20. integer_data = [
  21. (-0.1, 1.1, None, np.array([-1, 0, 1, 2])),
  22. (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])),
  23. (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])),
  24. ]
  25. @pytest.mark.parametrize('vmin, vmax, expected', basic_data)
  26. def test_basic(self, vmin, vmax, expected):
  27. loc = mticker.MaxNLocator(nbins=5)
  28. assert_almost_equal(loc.tick_values(vmin, vmax), expected)
  29. @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data)
  30. def test_integer(self, vmin, vmax, steps, expected):
  31. loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps)
  32. assert_almost_equal(loc.tick_values(vmin, vmax), expected)
  33. @pytest.mark.parametrize('kwargs, errortype, match', [
  34. ({'foo': 0}, TypeError,
  35. re.escape("set_params() got an unexpected keyword argument 'foo'")),
  36. ({'steps': [2, 1]}, ValueError, "steps argument must be an increasing"),
  37. ({'steps': 2}, ValueError, "steps argument must be an increasing"),
  38. ({'steps': [2, 11]}, ValueError, "steps argument must be an increasing"),
  39. ])
  40. def test_errors(self, kwargs, errortype, match):
  41. with pytest.raises(errortype, match=match):
  42. mticker.MaxNLocator(**kwargs)
  43. @pytest.mark.parametrize('steps, result', [
  44. ([1, 2, 10], [1, 2, 10]),
  45. ([2, 10], [1, 2, 10]),
  46. ([1, 2], [1, 2, 10]),
  47. ([2], [1, 2, 10]),
  48. ])
  49. def test_padding(self, steps, result):
  50. loc = mticker.MaxNLocator(steps=steps)
  51. assert (loc._steps == result).all()
  52. class TestLinearLocator:
  53. def test_basic(self):
  54. loc = mticker.LinearLocator(numticks=3)
  55. test_value = np.array([-0.8, -0.3, 0.2])
  56. assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value)
  57. def test_zero_numticks(self):
  58. loc = mticker.LinearLocator(numticks=0)
  59. loc.tick_values(-0.8, 0.2) == []
  60. def test_set_params(self):
  61. """
  62. Create linear locator with presets={}, numticks=2 and change it to
  63. something else. See if change was successful. Should not exception.
  64. """
  65. loc = mticker.LinearLocator(numticks=2)
  66. loc.set_params(numticks=8, presets={(0, 1): []})
  67. assert loc.numticks == 8
  68. assert loc.presets == {(0, 1): []}
  69. def test_presets(self):
  70. loc = mticker.LinearLocator(presets={(1, 2): [1, 1.25, 1.75],
  71. (0, 2): [0.5, 1.5]})
  72. assert loc.tick_values(1, 2) == [1, 1.25, 1.75]
  73. assert loc.tick_values(2, 1) == [1, 1.25, 1.75]
  74. assert loc.tick_values(0, 2) == [0.5, 1.5]
  75. assert loc.tick_values(0.0, 2.0) == [0.5, 1.5]
  76. assert (loc.tick_values(0, 1) == np.linspace(0, 1, 11)).all()
  77. class TestMultipleLocator:
  78. def test_basic(self):
  79. loc = mticker.MultipleLocator(base=3.147)
  80. test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294,
  81. 9.441, 12.588])
  82. assert_almost_equal(loc.tick_values(-7, 10), test_value)
  83. def test_basic_with_offset(self):
  84. loc = mticker.MultipleLocator(base=3.147, offset=1.2)
  85. test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494,
  86. 10.641])
  87. assert_almost_equal(loc.tick_values(-7, 10), test_value)
  88. def test_view_limits(self):
  89. """
  90. Test basic behavior of view limits.
  91. """
  92. with mpl.rc_context({'axes.autolimit_mode': 'data'}):
  93. loc = mticker.MultipleLocator(base=3.147)
  94. assert_almost_equal(loc.view_limits(-5, 5), (-5, 5))
  95. def test_view_limits_round_numbers(self):
  96. """
  97. Test that everything works properly with 'round_numbers' for auto
  98. limit.
  99. """
  100. with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
  101. loc = mticker.MultipleLocator(base=3.147)
  102. assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294))
  103. def test_view_limits_round_numbers_with_offset(self):
  104. """
  105. Test that everything works properly with 'round_numbers' for auto
  106. limit.
  107. """
  108. with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
  109. loc = mticker.MultipleLocator(base=3.147, offset=1.3)
  110. assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447))
  111. def test_set_params(self):
  112. """
  113. Create multiple locator with 0.7 base, and change it to something else.
  114. See if change was successful.
  115. """
  116. mult = mticker.MultipleLocator(base=0.7)
  117. mult.set_params(base=1.7)
  118. assert mult._edge.step == 1.7
  119. mult.set_params(offset=3)
  120. assert mult._offset == 3
  121. class TestAutoMinorLocator:
  122. def test_basic(self):
  123. fig, ax = plt.subplots()
  124. ax.set_xlim(0, 1.39)
  125. ax.minorticks_on()
  126. test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45,
  127. 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9,
  128. 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35])
  129. assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
  130. # NB: the following values are assuming that *xlim* is [0, 5]
  131. params = [
  132. (0, 0), # no major tick => no minor tick either
  133. (1, 0) # a single major tick => no minor tick
  134. ]
  135. def test_first_and_last_minorticks(self):
  136. """
  137. Test that first and last minor tick appear as expected.
  138. """
  139. # This test is related to issue #22331
  140. fig, ax = plt.subplots()
  141. ax.set_xlim(-1.9, 1.9)
  142. ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
  143. test_value = np.array([-1.9, -1.8, -1.7, -1.6, -1.4, -1.3, -1.2, -1.1,
  144. -0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1,
  145. 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1,
  146. 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9])
  147. assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
  148. ax.set_xlim(-5, 5)
  149. test_value = np.array([-5.0, -4.5, -3.5, -3.0, -2.5, -1.5, -1.0, -0.5,
  150. 0.5, 1.0, 1.5, 2.5, 3.0, 3.5, 4.5, 5.0])
  151. assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
  152. @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params)
  153. def test_low_number_of_majorticks(
  154. self, nb_majorticks, expected_nb_minorticks):
  155. # This test is related to issue #8804
  156. fig, ax = plt.subplots()
  157. xlims = (0, 5) # easier to test the different code paths
  158. ax.set_xlim(*xlims)
  159. ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))
  160. ax.minorticks_on()
  161. ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
  162. assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks
  163. majorstep_minordivisions = [(1, 5),
  164. (2, 4),
  165. (2.5, 5),
  166. (5, 5),
  167. (10, 5)]
  168. # This test is meant to verify the parameterization for
  169. # test_number_of_minor_ticks
  170. def test_using_all_default_major_steps(self):
  171. with mpl.rc_context({'_internal.classic_mode': False}):
  172. majorsteps = [x[0] for x in self.majorstep_minordivisions]
  173. np.testing.assert_allclose(majorsteps,
  174. mticker.AutoLocator()._steps)
  175. @pytest.mark.parametrize('major_step, expected_nb_minordivisions',
  176. majorstep_minordivisions)
  177. def test_number_of_minor_ticks(
  178. self, major_step, expected_nb_minordivisions):
  179. fig, ax = plt.subplots()
  180. xlims = (0, major_step)
  181. ax.set_xlim(*xlims)
  182. ax.set_xticks(xlims)
  183. ax.minorticks_on()
  184. ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
  185. nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1
  186. assert nb_minor_divisions == expected_nb_minordivisions
  187. limits = [(0, 1.39), (0, 0.139),
  188. (0, 0.11e-19), (0, 0.112e-12),
  189. (-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06),
  190. (-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)]
  191. reference = [
  192. [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,
  193. 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35],
  194. [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065,
  195. 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13,
  196. 0.135],
  197. [5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21,
  198. 5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21,
  199. 9.50e-21, 1.05e-20, 1.10e-20],
  200. [5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14,
  201. 5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14,
  202. 9.50e-14, 1.05e-13, 1.10e-13],
  203. [-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07,
  204. -1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07,
  205. -1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08,
  206. -7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08,
  207. -3.50e-08],
  208. [1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06,
  209. 1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06,
  210. 1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06],
  211. [-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06,
  212. -1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06,
  213. -1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06],
  214. [-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06,
  215. -1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06,
  216. -1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06,
  217. -1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07,
  218. -8.80e-07]]
  219. additional_data = list(zip(limits, reference))
  220. @pytest.mark.parametrize('lim, ref', additional_data)
  221. def test_additional(self, lim, ref):
  222. fig, ax = plt.subplots()
  223. ax.minorticks_on()
  224. ax.grid(True, 'minor', 'y', linewidth=1)
  225. ax.grid(True, 'major', color='k', linewidth=1)
  226. ax.set_ylim(lim)
  227. assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
  228. @pytest.mark.parametrize('use_rcparam', [False, True])
  229. @pytest.mark.parametrize(
  230. 'lim, ref', [
  231. ((0, 1.39),
  232. [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,
  233. 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]),
  234. ((0, 0.139),
  235. [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055,
  236. 0.065, 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115,
  237. 0.125, 0.13, 0.135]),
  238. ])
  239. def test_number_of_minor_ticks_auto(self, lim, ref, use_rcparam):
  240. if use_rcparam:
  241. context = {'xtick.minor.ndivs': 'auto', 'ytick.minor.ndivs': 'auto'}
  242. kwargs = {}
  243. else:
  244. context = {}
  245. kwargs = {'n': 'auto'}
  246. with mpl.rc_context(context):
  247. fig, ax = plt.subplots()
  248. ax.set_xlim(*lim)
  249. ax.set_ylim(*lim)
  250. ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
  251. ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
  252. assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)
  253. assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
  254. @pytest.mark.parametrize('use_rcparam', [False, True])
  255. @pytest.mark.parametrize(
  256. 'n, lim, ref', [
  257. (2, (0, 4), [0.5, 1.5, 2.5, 3.5]),
  258. (4, (0, 2), [0.25, 0.5, 0.75, 1.25, 1.5, 1.75]),
  259. (10, (0, 1), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]),
  260. ])
  261. def test_number_of_minor_ticks_int(self, n, lim, ref, use_rcparam):
  262. if use_rcparam:
  263. context = {'xtick.minor.ndivs': n, 'ytick.minor.ndivs': n}
  264. kwargs = {}
  265. else:
  266. context = {}
  267. kwargs = {'n': n}
  268. with mpl.rc_context(context):
  269. fig, ax = plt.subplots()
  270. ax.set_xlim(*lim)
  271. ax.set_ylim(*lim)
  272. ax.xaxis.set_major_locator(mticker.MultipleLocator(1))
  273. ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
  274. ax.yaxis.set_major_locator(mticker.MultipleLocator(1))
  275. ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
  276. assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)
  277. assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
  278. class TestLogLocator:
  279. def test_basic(self):
  280. loc = mticker.LogLocator(numticks=5)
  281. with pytest.raises(ValueError):
  282. loc.tick_values(0, 1000)
  283. test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01,
  284. 1.00000000e+01, 1.00000000e+03, 1.00000000e+05,
  285. 1.00000000e+07, 1.000000000e+09])
  286. assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value)
  287. loc = mticker.LogLocator(base=2)
  288. test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.])
  289. assert_almost_equal(loc.tick_values(1, 100), test_value)
  290. def test_polar_axes(self):
  291. """
  292. Polar axes have a different ticking logic.
  293. """
  294. fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
  295. ax.set_yscale('log')
  296. ax.set_ylim(1, 100)
  297. assert_array_equal(ax.get_yticks(), [10, 100, 1000])
  298. def test_switch_to_autolocator(self):
  299. loc = mticker.LogLocator(subs="all")
  300. assert_array_equal(loc.tick_values(0.45, 0.55),
  301. [0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56])
  302. # check that we *skip* 1.0, and 10, because this is a minor locator
  303. loc = mticker.LogLocator(subs=np.arange(2, 10))
  304. assert 1.0 not in loc.tick_values(0.9, 20.)
  305. assert 10.0 not in loc.tick_values(0.9, 20.)
  306. def test_set_params(self):
  307. """
  308. Create log locator with default value, base=10.0, subs=[1.0],
  309. numdecs=4, numticks=15 and change it to something else.
  310. See if change was successful. Should not raise exception.
  311. """
  312. loc = mticker.LogLocator()
  313. with pytest.warns(mpl.MatplotlibDeprecationWarning, match="numdecs"):
  314. loc.set_params(numticks=7, numdecs=8, subs=[2.0], base=4)
  315. assert loc.numticks == 7
  316. with pytest.warns(mpl.MatplotlibDeprecationWarning, match="numdecs"):
  317. assert loc.numdecs == 8
  318. assert loc._base == 4
  319. assert list(loc._subs) == [2.0]
  320. def test_tick_values_correct(self):
  321. ll = mticker.LogLocator(subs=(1, 2, 5))
  322. test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,
  323. 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,
  324. 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,
  325. 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,
  326. 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08])
  327. assert_almost_equal(ll.tick_values(1, 1e7), test_value)
  328. def test_tick_values_not_empty(self):
  329. mpl.rcParams['_internal.classic_mode'] = False
  330. ll = mticker.LogLocator(subs=(1, 2, 5))
  331. test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,
  332. 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,
  333. 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,
  334. 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,
  335. 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08,
  336. 1.e+09, 2.e+09, 5.e+09])
  337. assert_almost_equal(ll.tick_values(1, 1e8), test_value)
  338. def test_multiple_shared_axes(self):
  339. rng = np.random.default_rng(19680801)
  340. dummy_data = [rng.normal(size=100), [], []]
  341. fig, axes = plt.subplots(len(dummy_data), sharex=True, sharey=True)
  342. for ax, data in zip(axes.flatten(), dummy_data):
  343. ax.hist(data, bins=10)
  344. ax.set_yscale('log', nonpositive='clip')
  345. for ax in axes.flatten():
  346. assert all(ax.get_yticks() == axes[0].get_yticks())
  347. assert ax.get_ylim() == axes[0].get_ylim()
  348. class TestNullLocator:
  349. def test_set_params(self):
  350. """
  351. Create null locator, and attempt to call set_params() on it.
  352. Should not exception, and should raise a warning.
  353. """
  354. loc = mticker.NullLocator()
  355. with pytest.warns(UserWarning):
  356. loc.set_params()
  357. class _LogitHelper:
  358. @staticmethod
  359. def isclose(x, y):
  360. return (np.isclose(-np.log(1/x-1), -np.log(1/y-1))
  361. if 0 < x < 1 and 0 < y < 1 else False)
  362. @staticmethod
  363. def assert_almost_equal(x, y):
  364. ax = np.array(x)
  365. ay = np.array(y)
  366. assert np.all(ax > 0) and np.all(ax < 1)
  367. assert np.all(ay > 0) and np.all(ay < 1)
  368. lx = -np.log(1/ax-1)
  369. ly = -np.log(1/ay-1)
  370. assert_almost_equal(lx, ly)
  371. class TestLogitLocator:
  372. ref_basic_limits = [
  373. (5e-2, 1 - 5e-2),
  374. (5e-3, 1 - 5e-3),
  375. (5e-4, 1 - 5e-4),
  376. (5e-5, 1 - 5e-5),
  377. (5e-6, 1 - 5e-6),
  378. (5e-7, 1 - 5e-7),
  379. (5e-8, 1 - 5e-8),
  380. (5e-9, 1 - 5e-9),
  381. ]
  382. ref_basic_major_ticks = [
  383. 1 / (10 ** np.arange(1, 3)),
  384. 1 / (10 ** np.arange(1, 4)),
  385. 1 / (10 ** np.arange(1, 5)),
  386. 1 / (10 ** np.arange(1, 6)),
  387. 1 / (10 ** np.arange(1, 7)),
  388. 1 / (10 ** np.arange(1, 8)),
  389. 1 / (10 ** np.arange(1, 9)),
  390. 1 / (10 ** np.arange(1, 10)),
  391. ]
  392. ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)]
  393. @pytest.mark.parametrize(
  394. "lims, expected_low_ticks",
  395. zip(ref_basic_limits, ref_basic_major_ticks),
  396. )
  397. def test_basic_major(self, lims, expected_low_ticks):
  398. """
  399. Create logit locator with huge number of major, and tests ticks.
  400. """
  401. expected_ticks = sorted(
  402. [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]
  403. )
  404. loc = mticker.LogitLocator(nbins=100)
  405. _LogitHelper.assert_almost_equal(
  406. loc.tick_values(*lims),
  407. expected_ticks
  408. )
  409. @pytest.mark.parametrize("lims", ref_maxn_limits)
  410. def test_maxn_major(self, lims):
  411. """
  412. When the axis is zoomed, the locator must have the same behavior as
  413. MaxNLocator.
  414. """
  415. loc = mticker.LogitLocator(nbins=100)
  416. maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10])
  417. for nbins in (4, 8, 16):
  418. loc.set_params(nbins=nbins)
  419. maxn_loc.set_params(nbins=nbins)
  420. ticks = loc.tick_values(*lims)
  421. maxn_ticks = maxn_loc.tick_values(*lims)
  422. assert ticks.shape == maxn_ticks.shape
  423. assert (ticks == maxn_ticks).all()
  424. @pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits)
  425. def test_nbins_major(self, lims):
  426. """
  427. Assert logit locator for respecting nbins param.
  428. """
  429. basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1
  430. loc = mticker.LogitLocator(nbins=100)
  431. for nbins in range(basic_needed, 2, -1):
  432. loc.set_params(nbins=nbins)
  433. assert len(loc.tick_values(*lims)) <= nbins + 2
  434. @pytest.mark.parametrize(
  435. "lims, expected_low_ticks",
  436. zip(ref_basic_limits, ref_basic_major_ticks),
  437. )
  438. def test_minor(self, lims, expected_low_ticks):
  439. """
  440. In large scale, test the presence of minor,
  441. and assert no minor when major are subsampled.
  442. """
  443. expected_ticks = sorted(
  444. [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]
  445. )
  446. basic_needed = len(expected_ticks)
  447. loc = mticker.LogitLocator(nbins=100)
  448. minor_loc = mticker.LogitLocator(nbins=100, minor=True)
  449. for nbins in range(basic_needed, 2, -1):
  450. loc.set_params(nbins=nbins)
  451. minor_loc.set_params(nbins=nbins)
  452. major_ticks = loc.tick_values(*lims)
  453. minor_ticks = minor_loc.tick_values(*lims)
  454. if len(major_ticks) >= len(expected_ticks):
  455. # no subsample, we must have a lot of minors ticks
  456. assert (len(major_ticks) - 1) * 5 < len(minor_ticks)
  457. else:
  458. # subsample
  459. _LogitHelper.assert_almost_equal(
  460. sorted([*major_ticks, *minor_ticks]), expected_ticks)
  461. def test_minor_attr(self):
  462. loc = mticker.LogitLocator(nbins=100)
  463. assert not loc.minor
  464. loc.minor = True
  465. assert loc.minor
  466. loc.set_params(minor=False)
  467. assert not loc.minor
  468. acceptable_vmin_vmax = [
  469. *(2.5 ** np.arange(-3, 0)),
  470. *(1 - 2.5 ** np.arange(-3, 0)),
  471. ]
  472. @pytest.mark.parametrize(
  473. "lims",
  474. [
  475. (a, b)
  476. for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2)
  477. if a != b
  478. ],
  479. )
  480. def test_nonsingular_ok(self, lims):
  481. """
  482. Create logit locator, and test the nonsingular method for acceptable
  483. value
  484. """
  485. loc = mticker.LogitLocator()
  486. lims2 = loc.nonsingular(*lims)
  487. assert sorted(lims) == sorted(lims2)
  488. @pytest.mark.parametrize("okval", acceptable_vmin_vmax)
  489. def test_nonsingular_nok(self, okval):
  490. """
  491. Create logit locator, and test the nonsingular method for non
  492. acceptable value
  493. """
  494. loc = mticker.LogitLocator()
  495. vmin, vmax = (-1, okval)
  496. vmin2, vmax2 = loc.nonsingular(vmin, vmax)
  497. assert vmax2 == vmax
  498. assert 0 < vmin2 < vmax2
  499. vmin, vmax = (okval, 2)
  500. vmin2, vmax2 = loc.nonsingular(vmin, vmax)
  501. assert vmin2 == vmin
  502. assert vmin2 < vmax2 < 1
  503. class TestFixedLocator:
  504. def test_set_params(self):
  505. """
  506. Create fixed locator with 5 nbins, and change it to something else.
  507. See if change was successful.
  508. Should not exception.
  509. """
  510. fixed = mticker.FixedLocator(range(0, 24), nbins=5)
  511. fixed.set_params(nbins=7)
  512. assert fixed.nbins == 7
  513. class TestIndexLocator:
  514. def test_set_params(self):
  515. """
  516. Create index locator with 3 base, 4 offset. and change it to something
  517. else. See if change was successful.
  518. Should not exception.
  519. """
  520. index = mticker.IndexLocator(base=3, offset=4)
  521. index.set_params(base=7, offset=7)
  522. assert index._base == 7
  523. assert index.offset == 7
  524. class TestSymmetricalLogLocator:
  525. def test_set_params(self):
  526. """
  527. Create symmetrical log locator with default subs =[1.0] numticks = 15,
  528. and change it to something else.
  529. See if change was successful.
  530. Should not exception.
  531. """
  532. sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
  533. sym.set_params(subs=[2.0], numticks=8)
  534. assert sym._subs == [2.0]
  535. assert sym.numticks == 8
  536. @pytest.mark.parametrize(
  537. 'vmin, vmax, expected',
  538. [
  539. (0, 1, [0, 1]),
  540. (-1, 1, [-1, 0, 1]),
  541. ],
  542. )
  543. def test_values(self, vmin, vmax, expected):
  544. # https://github.com/matplotlib/matplotlib/issues/25945
  545. sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
  546. ticks = sym.tick_values(vmin=vmin, vmax=vmax)
  547. assert_array_equal(ticks, expected)
  548. def test_subs(self):
  549. sym = mticker.SymmetricalLogLocator(base=10, linthresh=1, subs=[2.0, 4.0])
  550. sym.create_dummy_axis()
  551. sym.axis.set_view_interval(-10, 10)
  552. assert (sym() == [-20., -40., -2., -4., 0., 2., 4., 20., 40.]).all()
  553. def test_extending(self):
  554. sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
  555. sym.create_dummy_axis()
  556. sym.axis.set_view_interval(8, 9)
  557. assert (sym() == [1.0]).all()
  558. sym.axis.set_view_interval(8, 12)
  559. assert (sym() == [1.0, 10.0]).all()
  560. assert sym.view_limits(10, 10) == (1, 100)
  561. assert sym.view_limits(-10, -10) == (-100, -1)
  562. assert sym.view_limits(0, 0) == (-0.001, 0.001)
  563. class TestAsinhLocator:
  564. def test_init(self):
  565. lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19)
  566. assert lctr.linear_width == 2.718
  567. assert lctr.numticks == 19
  568. assert lctr.base == 10
  569. def test_set_params(self):
  570. lctr = mticker.AsinhLocator(linear_width=5,
  571. numticks=17, symthresh=0.125,
  572. base=4, subs=(2.5, 3.25))
  573. assert lctr.numticks == 17
  574. assert lctr.symthresh == 0.125
  575. assert lctr.base == 4
  576. assert lctr.subs == (2.5, 3.25)
  577. lctr.set_params(numticks=23)
  578. assert lctr.numticks == 23
  579. lctr.set_params(None)
  580. assert lctr.numticks == 23
  581. lctr.set_params(symthresh=0.5)
  582. assert lctr.symthresh == 0.5
  583. lctr.set_params(symthresh=None)
  584. assert lctr.symthresh == 0.5
  585. lctr.set_params(base=7)
  586. assert lctr.base == 7
  587. lctr.set_params(base=None)
  588. assert lctr.base == 7
  589. lctr.set_params(subs=(2, 4.125))
  590. assert lctr.subs == (2, 4.125)
  591. lctr.set_params(subs=None)
  592. assert lctr.subs == (2, 4.125)
  593. lctr.set_params(subs=[])
  594. assert lctr.subs is None
  595. def test_linear_values(self):
  596. lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0)
  597. assert_almost_equal(lctr.tick_values(-1, 1),
  598. np.arange(-1, 1.01, 0.2))
  599. assert_almost_equal(lctr.tick_values(-0.1, 0.1),
  600. np.arange(-0.1, 0.101, 0.02))
  601. assert_almost_equal(lctr.tick_values(-0.01, 0.01),
  602. np.arange(-0.01, 0.0101, 0.002))
  603. def test_wide_values(self):
  604. lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0)
  605. assert_almost_equal(lctr.tick_values(-100, 100),
  606. [-100, -20, -5, -1, -0.2,
  607. 0, 0.2, 1, 5, 20, 100])
  608. assert_almost_equal(lctr.tick_values(-1000, 1000),
  609. [-1000, -100, -20, -3, -0.4,
  610. 0, 0.4, 3, 20, 100, 1000])
  611. def test_near_zero(self):
  612. """Check that manually injected zero will supersede nearby tick"""
  613. lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0)
  614. assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9])
  615. def test_fallback(self):
  616. lctr = mticker.AsinhLocator(1.0, numticks=11)
  617. assert_almost_equal(lctr.tick_values(101, 102),
  618. np.arange(101, 102.01, 0.1))
  619. def test_symmetrizing(self):
  620. lctr = mticker.AsinhLocator(linear_width=1, numticks=3,
  621. symthresh=0.25, base=0)
  622. lctr.create_dummy_axis()
  623. lctr.axis.set_view_interval(-1, 2)
  624. assert_almost_equal(lctr(), [-1, 0, 2])
  625. lctr.axis.set_view_interval(-1, 0.9)
  626. assert_almost_equal(lctr(), [-1, 0, 1])
  627. lctr.axis.set_view_interval(-0.85, 1.05)
  628. assert_almost_equal(lctr(), [-1, 0, 1])
  629. lctr.axis.set_view_interval(1, 1.1)
  630. assert_almost_equal(lctr(), [1, 1.05, 1.1])
  631. def test_base_rounding(self):
  632. lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8,
  633. base=10, subs=(1, 3, 5))
  634. assert_almost_equal(lctr10.tick_values(-110, 110),
  635. [-500, -300, -100, -50, -30, -10, -5, -3, -1,
  636. -0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5,
  637. 1, 3, 5, 10, 30, 50, 100, 300, 500])
  638. lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5)
  639. assert_almost_equal(lctr5.tick_values(-1050, 1050),
  640. [-625, -125, -25, -5, -1, -0.2, 0,
  641. 0.2, 1, 5, 25, 125, 625])
  642. class TestScalarFormatter:
  643. offset_data = [
  644. (123, 189, 0),
  645. (-189, -123, 0),
  646. (12341, 12349, 12340),
  647. (-12349, -12341, -12340),
  648. (99999.5, 100010.5, 100000),
  649. (-100010.5, -99999.5, -100000),
  650. (99990.5, 100000.5, 100000),
  651. (-100000.5, -99990.5, -100000),
  652. (1233999, 1234001, 1234000),
  653. (-1234001, -1233999, -1234000),
  654. (1, 1, 1),
  655. (123, 123, 0),
  656. # Test cases courtesy of @WeatherGod
  657. (.4538, .4578, .45),
  658. (3789.12, 3783.1, 3780),
  659. (45124.3, 45831.75, 45000),
  660. (0.000721, 0.0007243, 0.00072),
  661. (12592.82, 12591.43, 12590),
  662. (9., 12., 0),
  663. (900., 1200., 0),
  664. (1900., 1200., 0),
  665. (0.99, 1.01, 1),
  666. (9.99, 10.01, 10),
  667. (99.99, 100.01, 100),
  668. (5.99, 6.01, 6),
  669. (15.99, 16.01, 16),
  670. (-0.452, 0.492, 0),
  671. (-0.492, 0.492, 0),
  672. (12331.4, 12350.5, 12300),
  673. (-12335.3, 12335.3, 0),
  674. ]
  675. use_offset_data = [True, False]
  676. useMathText_data = [True, False]
  677. # (sci_type, scilimits, lim, orderOfMag, fewticks)
  678. scilimits_data = [
  679. (False, (0, 0), (10.0, 20.0), 0, False),
  680. (True, (-2, 2), (-10, 20), 0, False),
  681. (True, (-2, 2), (-20, 10), 0, False),
  682. (True, (-2, 2), (-110, 120), 2, False),
  683. (True, (-2, 2), (-120, 110), 2, False),
  684. (True, (-2, 2), (-.001, 0.002), -3, False),
  685. (True, (-7, 7), (0.18e10, 0.83e10), 9, True),
  686. (True, (0, 0), (-1e5, 1e5), 5, False),
  687. (True, (6, 6), (-1e5, 1e5), 6, False),
  688. ]
  689. cursor_data = [
  690. [0., "0.000"],
  691. [0.0123, "0.012"],
  692. [0.123, "0.123"],
  693. [1.23, "1.230"],
  694. [12.3, "12.300"],
  695. ]
  696. format_data = [
  697. (.1, "1e-1"),
  698. (.11, "1.1e-1"),
  699. (1e8, "1e8"),
  700. (1.1e8, "1.1e8"),
  701. ]
  702. @pytest.mark.parametrize('unicode_minus, result',
  703. [(True, "\N{MINUS SIGN}1"), (False, "-1")])
  704. def test_unicode_minus(self, unicode_minus, result):
  705. mpl.rcParams['axes.unicode_minus'] = unicode_minus
  706. assert (
  707. plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip()
  708. == result)
  709. @pytest.mark.parametrize('left, right, offset', offset_data)
  710. def test_offset_value(self, left, right, offset):
  711. fig, ax = plt.subplots()
  712. formatter = ax.xaxis.get_major_formatter()
  713. with (pytest.warns(UserWarning, match='Attempting to set identical')
  714. if left == right else nullcontext()):
  715. ax.set_xlim(left, right)
  716. ax.xaxis._update_ticks()
  717. assert formatter.offset == offset
  718. with (pytest.warns(UserWarning, match='Attempting to set identical')
  719. if left == right else nullcontext()):
  720. ax.set_xlim(right, left)
  721. ax.xaxis._update_ticks()
  722. assert formatter.offset == offset
  723. @pytest.mark.parametrize('use_offset', use_offset_data)
  724. def test_use_offset(self, use_offset):
  725. with mpl.rc_context({'axes.formatter.useoffset': use_offset}):
  726. tmp_form = mticker.ScalarFormatter()
  727. assert use_offset == tmp_form.get_useOffset()
  728. assert tmp_form.offset == 0
  729. @pytest.mark.parametrize('use_math_text', useMathText_data)
  730. def test_useMathText(self, use_math_text):
  731. with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}):
  732. tmp_form = mticker.ScalarFormatter()
  733. assert use_math_text == tmp_form.get_useMathText()
  734. def test_set_use_offset_float(self):
  735. tmp_form = mticker.ScalarFormatter()
  736. tmp_form.set_useOffset(0.5)
  737. assert not tmp_form.get_useOffset()
  738. assert tmp_form.offset == 0.5
  739. def test_use_locale(self):
  740. conv = locale.localeconv()
  741. sep = conv['thousands_sep']
  742. if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]):
  743. pytest.skip('Locale does not apply grouping') # pragma: no cover
  744. with mpl.rc_context({'axes.formatter.use_locale': True}):
  745. tmp_form = mticker.ScalarFormatter()
  746. assert tmp_form.get_useLocale()
  747. tmp_form.create_dummy_axis()
  748. tmp_form.axis.set_data_interval(0, 10)
  749. tmp_form.set_locs([1, 2, 3])
  750. assert sep in tmp_form(1e9)
  751. @pytest.mark.parametrize(
  752. 'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data)
  753. def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks):
  754. tmp_form = mticker.ScalarFormatter()
  755. tmp_form.set_scientific(sci_type)
  756. tmp_form.set_powerlimits(scilimits)
  757. fig, ax = plt.subplots()
  758. ax.yaxis.set_major_formatter(tmp_form)
  759. ax.set_ylim(*lim)
  760. if fewticks:
  761. ax.yaxis.set_major_locator(mticker.MaxNLocator(4))
  762. tmp_form.set_locs(ax.yaxis.get_majorticklocs())
  763. assert orderOfMag == tmp_form.orderOfMagnitude
  764. @pytest.mark.parametrize('value, expected', format_data)
  765. def test_format_data(self, value, expected):
  766. mpl.rcParams['axes.unicode_minus'] = False
  767. sf = mticker.ScalarFormatter()
  768. assert sf.format_data(value) == expected
  769. @pytest.mark.parametrize('data, expected', cursor_data)
  770. def test_cursor_precision(self, data, expected):
  771. fig, ax = plt.subplots()
  772. ax.set_xlim(-1, 1) # Pointing precision of 0.001.
  773. fmt = ax.xaxis.get_major_formatter().format_data_short
  774. assert fmt(data) == expected
  775. @pytest.mark.parametrize('data, expected', cursor_data)
  776. def test_cursor_dummy_axis(self, data, expected):
  777. # Issue #17624
  778. sf = mticker.ScalarFormatter()
  779. sf.create_dummy_axis()
  780. sf.axis.set_view_interval(0, 10)
  781. fmt = sf.format_data_short
  782. assert fmt(data) == expected
  783. assert sf.axis.get_tick_space() == 9
  784. assert sf.axis.get_minpos() == 0
  785. def test_mathtext_ticks(self):
  786. mpl.rcParams.update({
  787. 'font.family': 'serif',
  788. 'font.serif': 'cmr10',
  789. 'axes.formatter.use_mathtext': False
  790. })
  791. with pytest.warns(UserWarning, match='cmr10 font should ideally'):
  792. fig, ax = plt.subplots()
  793. ax.set_xticks([-1, 0, 1])
  794. fig.canvas.draw()
  795. def test_cmr10_substitutions(self, caplog):
  796. mpl.rcParams.update({
  797. 'font.family': 'cmr10',
  798. 'mathtext.fontset': 'cm',
  799. 'axes.formatter.use_mathtext': True,
  800. })
  801. # Test that it does not log a warning about missing glyphs.
  802. with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'):
  803. fig, ax = plt.subplots()
  804. ax.plot([-0.03, 0.05], [40, 0.05])
  805. ax.set_yscale('log')
  806. yticks = [0.02, 0.3, 4, 50]
  807. formatter = mticker.LogFormatterSciNotation()
  808. ax.set_yticks(yticks, map(formatter, yticks))
  809. fig.canvas.draw()
  810. assert not caplog.text
  811. def test_empty_locs(self):
  812. sf = mticker.ScalarFormatter()
  813. sf.set_locs([])
  814. assert sf(0.5) == ''
  815. class TestLogFormatterExponent:
  816. param_data = [
  817. (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0),
  818. ['-3', '-2', '-1', '0', '1', '2', '3']),
  819. # With labelOnlyBase=False, non-integer powers should be nicely
  820. # formatted.
  821. (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]),
  822. range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']),
  823. (False, 50, np.array([3, 5, 12, 42], dtype=float), range(6),
  824. ['3', '5', '12', '42']),
  825. ]
  826. base_data = [2.0, 5.0, 10.0, np.pi, np.e]
  827. @pytest.mark.parametrize(
  828. 'labelOnlyBase, exponent, locs, positions, expected', param_data)
  829. @pytest.mark.parametrize('base', base_data)
  830. def test_basic(self, labelOnlyBase, base, exponent, locs, positions,
  831. expected):
  832. formatter = mticker.LogFormatterExponent(base=base,
  833. labelOnlyBase=labelOnlyBase)
  834. formatter.create_dummy_axis()
  835. formatter.axis.set_view_interval(1, base**exponent)
  836. vals = base**locs
  837. labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)]
  838. expected = [label.replace('-', '\N{Minus Sign}') for label in expected]
  839. assert labels == expected
  840. def test_blank(self):
  841. # Should be a blank string for non-integer powers if labelOnlyBase=True
  842. formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)
  843. formatter.create_dummy_axis()
  844. formatter.axis.set_view_interval(1, 10)
  845. assert formatter(10**0.1) == ''
  846. class TestLogFormatterMathtext:
  847. fmt = mticker.LogFormatterMathtext()
  848. test_data = [
  849. (0, 1, '$\\mathdefault{10^{0}}$'),
  850. (0, 1e-2, '$\\mathdefault{10^{-2}}$'),
  851. (0, 1e2, '$\\mathdefault{10^{2}}$'),
  852. (3, 1, '$\\mathdefault{1}$'),
  853. (3, 1e-2, '$\\mathdefault{0.01}$'),
  854. (3, 1e2, '$\\mathdefault{100}$'),
  855. (3, 1e-3, '$\\mathdefault{10^{-3}}$'),
  856. (3, 1e3, '$\\mathdefault{10^{3}}$'),
  857. ]
  858. @pytest.mark.parametrize('min_exponent, value, expected', test_data)
  859. def test_min_exponent(self, min_exponent, value, expected):
  860. with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}):
  861. assert self.fmt(value) == expected
  862. class TestLogFormatterSciNotation:
  863. test_data = [
  864. (2, 0.03125, '$\\mathdefault{2^{-5}}$'),
  865. (2, 1, '$\\mathdefault{2^{0}}$'),
  866. (2, 32, '$\\mathdefault{2^{5}}$'),
  867. (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'),
  868. (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'),
  869. (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'),
  870. (10, -1, '$\\mathdefault{-10^{0}}$'),
  871. (10, 1e-05, '$\\mathdefault{10^{-5}}$'),
  872. (10, 1, '$\\mathdefault{10^{0}}$'),
  873. (10, 100000, '$\\mathdefault{10^{5}}$'),
  874. (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'),
  875. (10, 2, '$\\mathdefault{2\\times10^{0}}$'),
  876. (10, 200000, '$\\mathdefault{2\\times10^{5}}$'),
  877. (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'),
  878. (10, 5, '$\\mathdefault{5\\times10^{0}}$'),
  879. (10, 500000, '$\\mathdefault{5\\times10^{5}}$'),
  880. ]
  881. @mpl.style.context('default')
  882. @pytest.mark.parametrize('base, value, expected', test_data)
  883. def test_basic(self, base, value, expected):
  884. formatter = mticker.LogFormatterSciNotation(base=base)
  885. with mpl.rc_context({'text.usetex': False}):
  886. assert formatter(value) == expected
  887. class TestLogFormatter:
  888. pprint_data = [
  889. (3.141592654e-05, 0.001, '3.142e-5'),
  890. (0.0003141592654, 0.001, '3.142e-4'),
  891. (0.003141592654, 0.001, '3.142e-3'),
  892. (0.03141592654, 0.001, '3.142e-2'),
  893. (0.3141592654, 0.001, '3.142e-1'),
  894. (3.141592654, 0.001, '3.142'),
  895. (31.41592654, 0.001, '3.142e1'),
  896. (314.1592654, 0.001, '3.142e2'),
  897. (3141.592654, 0.001, '3.142e3'),
  898. (31415.92654, 0.001, '3.142e4'),
  899. (314159.2654, 0.001, '3.142e5'),
  900. (1e-05, 0.001, '1e-5'),
  901. (0.0001, 0.001, '1e-4'),
  902. (0.001, 0.001, '1e-3'),
  903. (0.01, 0.001, '1e-2'),
  904. (0.1, 0.001, '1e-1'),
  905. (1, 0.001, '1'),
  906. (10, 0.001, '10'),
  907. (100, 0.001, '100'),
  908. (1000, 0.001, '1000'),
  909. (10000, 0.001, '1e4'),
  910. (100000, 0.001, '1e5'),
  911. (3.141592654e-05, 0.015, '0'),
  912. (0.0003141592654, 0.015, '0'),
  913. (0.003141592654, 0.015, '0.003'),
  914. (0.03141592654, 0.015, '0.031'),
  915. (0.3141592654, 0.015, '0.314'),
  916. (3.141592654, 0.015, '3.142'),
  917. (31.41592654, 0.015, '31.416'),
  918. (314.1592654, 0.015, '314.159'),
  919. (3141.592654, 0.015, '3141.593'),
  920. (31415.92654, 0.015, '31415.927'),
  921. (314159.2654, 0.015, '314159.265'),
  922. (1e-05, 0.015, '0'),
  923. (0.0001, 0.015, '0'),
  924. (0.001, 0.015, '0.001'),
  925. (0.01, 0.015, '0.01'),
  926. (0.1, 0.015, '0.1'),
  927. (1, 0.015, '1'),
  928. (10, 0.015, '10'),
  929. (100, 0.015, '100'),
  930. (1000, 0.015, '1000'),
  931. (10000, 0.015, '10000'),
  932. (100000, 0.015, '100000'),
  933. (3.141592654e-05, 0.5, '0'),
  934. (0.0003141592654, 0.5, '0'),
  935. (0.003141592654, 0.5, '0.003'),
  936. (0.03141592654, 0.5, '0.031'),
  937. (0.3141592654, 0.5, '0.314'),
  938. (3.141592654, 0.5, '3.142'),
  939. (31.41592654, 0.5, '31.416'),
  940. (314.1592654, 0.5, '314.159'),
  941. (3141.592654, 0.5, '3141.593'),
  942. (31415.92654, 0.5, '31415.927'),
  943. (314159.2654, 0.5, '314159.265'),
  944. (1e-05, 0.5, '0'),
  945. (0.0001, 0.5, '0'),
  946. (0.001, 0.5, '0.001'),
  947. (0.01, 0.5, '0.01'),
  948. (0.1, 0.5, '0.1'),
  949. (1, 0.5, '1'),
  950. (10, 0.5, '10'),
  951. (100, 0.5, '100'),
  952. (1000, 0.5, '1000'),
  953. (10000, 0.5, '10000'),
  954. (100000, 0.5, '100000'),
  955. (3.141592654e-05, 5, '0'),
  956. (0.0003141592654, 5, '0'),
  957. (0.003141592654, 5, '0'),
  958. (0.03141592654, 5, '0.03'),
  959. (0.3141592654, 5, '0.31'),
  960. (3.141592654, 5, '3.14'),
  961. (31.41592654, 5, '31.42'),
  962. (314.1592654, 5, '314.16'),
  963. (3141.592654, 5, '3141.59'),
  964. (31415.92654, 5, '31415.93'),
  965. (314159.2654, 5, '314159.27'),
  966. (1e-05, 5, '0'),
  967. (0.0001, 5, '0'),
  968. (0.001, 5, '0'),
  969. (0.01, 5, '0.01'),
  970. (0.1, 5, '0.1'),
  971. (1, 5, '1'),
  972. (10, 5, '10'),
  973. (100, 5, '100'),
  974. (1000, 5, '1000'),
  975. (10000, 5, '10000'),
  976. (100000, 5, '100000'),
  977. (3.141592654e-05, 100, '0'),
  978. (0.0003141592654, 100, '0'),
  979. (0.003141592654, 100, '0'),
  980. (0.03141592654, 100, '0'),
  981. (0.3141592654, 100, '0.3'),
  982. (3.141592654, 100, '3.1'),
  983. (31.41592654, 100, '31.4'),
  984. (314.1592654, 100, '314.2'),
  985. (3141.592654, 100, '3141.6'),
  986. (31415.92654, 100, '31415.9'),
  987. (314159.2654, 100, '314159.3'),
  988. (1e-05, 100, '0'),
  989. (0.0001, 100, '0'),
  990. (0.001, 100, '0'),
  991. (0.01, 100, '0'),
  992. (0.1, 100, '0.1'),
  993. (1, 100, '1'),
  994. (10, 100, '10'),
  995. (100, 100, '100'),
  996. (1000, 100, '1000'),
  997. (10000, 100, '10000'),
  998. (100000, 100, '100000'),
  999. (3.141592654e-05, 1000000.0, '3.1e-5'),
  1000. (0.0003141592654, 1000000.0, '3.1e-4'),
  1001. (0.003141592654, 1000000.0, '3.1e-3'),
  1002. (0.03141592654, 1000000.0, '3.1e-2'),
  1003. (0.3141592654, 1000000.0, '3.1e-1'),
  1004. (3.141592654, 1000000.0, '3.1'),
  1005. (31.41592654, 1000000.0, '3.1e1'),
  1006. (314.1592654, 1000000.0, '3.1e2'),
  1007. (3141.592654, 1000000.0, '3.1e3'),
  1008. (31415.92654, 1000000.0, '3.1e4'),
  1009. (314159.2654, 1000000.0, '3.1e5'),
  1010. (1e-05, 1000000.0, '1e-5'),
  1011. (0.0001, 1000000.0, '1e-4'),
  1012. (0.001, 1000000.0, '1e-3'),
  1013. (0.01, 1000000.0, '1e-2'),
  1014. (0.1, 1000000.0, '1e-1'),
  1015. (1, 1000000.0, '1'),
  1016. (10, 1000000.0, '10'),
  1017. (100, 1000000.0, '100'),
  1018. (1000, 1000000.0, '1000'),
  1019. (10000, 1000000.0, '1e4'),
  1020. (100000, 1000000.0, '1e5'),
  1021. ]
  1022. @pytest.mark.parametrize('value, domain, expected', pprint_data)
  1023. def test_pprint(self, value, domain, expected):
  1024. fmt = mticker.LogFormatter()
  1025. label = fmt._pprint_val(value, domain)
  1026. assert label == expected
  1027. @pytest.mark.parametrize('value, long, short', [
  1028. (0.0, "0", "0 "),
  1029. (0, "0", "0 "),
  1030. (-1.0, "-10^0", "-1 "),
  1031. (2e-10, "2x10^-10", "2e-10 "),
  1032. (1e10, "10^10", "1e+10 "),
  1033. ])
  1034. def test_format_data(self, value, long, short):
  1035. fig, ax = plt.subplots()
  1036. ax.set_xscale('log')
  1037. fmt = ax.xaxis.get_major_formatter()
  1038. assert fmt.format_data(value) == long
  1039. assert fmt.format_data_short(value) == short
  1040. def _sub_labels(self, axis, subs=()):
  1041. """Test whether locator marks subs to be labeled."""
  1042. fmt = axis.get_minor_formatter()
  1043. minor_tlocs = axis.get_minorticklocs()
  1044. fmt.set_locs(minor_tlocs)
  1045. coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs)))
  1046. label_expected = [round(c) in subs for c in coefs]
  1047. label_test = [fmt(x) != '' for x in minor_tlocs]
  1048. assert label_test == label_expected
  1049. @mpl.style.context('default')
  1050. def test_sublabel(self):
  1051. # test label locator
  1052. fig, ax = plt.subplots()
  1053. ax.set_xscale('log')
  1054. ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[]))
  1055. ax.xaxis.set_minor_locator(mticker.LogLocator(base=10,
  1056. subs=np.arange(2, 10)))
  1057. ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True))
  1058. ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False))
  1059. # axis range above 3 decades, only bases are labeled
  1060. ax.set_xlim(1, 1e4)
  1061. fmt = ax.xaxis.get_major_formatter()
  1062. fmt.set_locs(ax.xaxis.get_majorticklocs())
  1063. show_major_labels = [fmt(x) != ''
  1064. for x in ax.xaxis.get_majorticklocs()]
  1065. assert np.all(show_major_labels)
  1066. self._sub_labels(ax.xaxis, subs=[])
  1067. # For the next two, if the numdec threshold in LogFormatter.set_locs
  1068. # were 3, then the label sub would be 3 for 2-3 decades and (2, 5)
  1069. # for 1-2 decades. With a threshold of 1, subs are not labeled.
  1070. # axis range at 2 to 3 decades
  1071. ax.set_xlim(1, 800)
  1072. self._sub_labels(ax.xaxis, subs=[])
  1073. # axis range at 1 to 2 decades
  1074. ax.set_xlim(1, 80)
  1075. self._sub_labels(ax.xaxis, subs=[])
  1076. # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6
  1077. ax.set_xlim(1, 8)
  1078. self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6])
  1079. # axis range at 0 to 0.4 decades, label all
  1080. ax.set_xlim(0.5, 0.9)
  1081. self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int))
  1082. @pytest.mark.parametrize('val', [1, 10, 100, 1000])
  1083. def test_LogFormatter_call(self, val):
  1084. # test _num_to_string method used in __call__
  1085. temp_lf = mticker.LogFormatter()
  1086. temp_lf.create_dummy_axis()
  1087. temp_lf.axis.set_view_interval(1, 10)
  1088. assert temp_lf(val) == str(val)
  1089. @pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323])
  1090. def test_LogFormatter_call_tiny(self, val):
  1091. # test coeff computation in __call__
  1092. temp_lf = mticker.LogFormatter()
  1093. temp_lf.create_dummy_axis()
  1094. temp_lf.axis.set_view_interval(1, 10)
  1095. temp_lf(val)
  1096. class TestLogitFormatter:
  1097. @staticmethod
  1098. def logit_deformatter(string):
  1099. r"""
  1100. Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in
  1101. float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float
  1102. 0.5,
  1103. """
  1104. match = re.match(
  1105. r"[^\d]*"
  1106. r"(?P<comp>1-)?"
  1107. r"(?P<mant>\d*\.?\d*)?"
  1108. r"(?:\\cdot)?"
  1109. r"(?:10\^\{(?P<expo>-?\d*)})?"
  1110. r"[^\d]*$",
  1111. string,
  1112. )
  1113. if match:
  1114. comp = match["comp"] is not None
  1115. mantissa = float(match["mant"]) if match["mant"] else 1
  1116. expo = int(match["expo"]) if match["expo"] is not None else 0
  1117. value = mantissa * 10 ** expo
  1118. if match["mant"] or match["expo"] is not None:
  1119. if comp:
  1120. return 1 - value
  1121. return value
  1122. match = re.match(
  1123. r"[^\d]*\\frac\{(?P<num>\d+)\}\{(?P<deno>\d+)\}[^\d]*$", string
  1124. )
  1125. if match:
  1126. num, deno = float(match["num"]), float(match["deno"])
  1127. return num / deno
  1128. raise ValueError("Not formatted by LogitFormatter")
  1129. @pytest.mark.parametrize(
  1130. "fx, x",
  1131. [
  1132. (r"STUFF0.41OTHERSTUFF", 0.41),
  1133. (r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2),
  1134. (r"STUFF1-0.41OTHERSTUFF", 1 - 0.41),
  1135. (r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2),
  1136. (r"STUFF", None),
  1137. (r"STUFF12.4e-3OTHERSTUFF", None),
  1138. ],
  1139. )
  1140. def test_logit_deformater(self, fx, x):
  1141. if x is None:
  1142. with pytest.raises(ValueError):
  1143. TestLogitFormatter.logit_deformatter(fx)
  1144. else:
  1145. y = TestLogitFormatter.logit_deformatter(fx)
  1146. assert _LogitHelper.isclose(x, y)
  1147. decade_test = sorted(
  1148. [10 ** (-i) for i in range(1, 10)]
  1149. + [1 - 10 ** (-i) for i in range(1, 10)]
  1150. + [1 / 2]
  1151. )
  1152. @pytest.mark.parametrize("x", decade_test)
  1153. def test_basic(self, x):
  1154. """
  1155. Test the formatted value correspond to the value for ideal ticks in
  1156. logit space.
  1157. """
  1158. formatter = mticker.LogitFormatter(use_overline=False)
  1159. formatter.set_locs(self.decade_test)
  1160. s = formatter(x)
  1161. x2 = TestLogitFormatter.logit_deformatter(s)
  1162. assert _LogitHelper.isclose(x, x2)
  1163. @pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2))
  1164. def test_invalid(self, x):
  1165. """
  1166. Test that invalid value are formatted with empty string without
  1167. raising exception.
  1168. """
  1169. formatter = mticker.LogitFormatter(use_overline=False)
  1170. formatter.set_locs(self.decade_test)
  1171. s = formatter(x)
  1172. assert s == ""
  1173. @pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10))))
  1174. def test_variablelength(self, x):
  1175. """
  1176. The format length should change depending on the neighbor labels.
  1177. """
  1178. formatter = mticker.LogitFormatter(use_overline=False)
  1179. for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000):
  1180. if x + 1 / N < 1:
  1181. formatter.set_locs([x - 1 / N, x, x + 1 / N])
  1182. sx = formatter(x)
  1183. sx1 = formatter(x + 1 / N)
  1184. d = (
  1185. TestLogitFormatter.logit_deformatter(sx1)
  1186. - TestLogitFormatter.logit_deformatter(sx)
  1187. )
  1188. assert 0 < d < 2 / N
  1189. lims_minor_major = [
  1190. (True, (5e-8, 1 - 5e-8), ((25, False), (75, False))),
  1191. (True, (5e-5, 1 - 5e-5), ((25, False), (75, True))),
  1192. (True, (5e-2, 1 - 5e-2), ((25, True), (75, True))),
  1193. (False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))),
  1194. ]
  1195. @pytest.mark.parametrize("method, lims, cases", lims_minor_major)
  1196. def test_minor_vs_major(self, method, lims, cases):
  1197. """
  1198. Test minor/major displays.
  1199. """
  1200. if method:
  1201. min_loc = mticker.LogitLocator(minor=True)
  1202. ticks = min_loc.tick_values(*lims)
  1203. else:
  1204. ticks = np.array(lims)
  1205. min_form = mticker.LogitFormatter(minor=True)
  1206. for threshold, has_minor in cases:
  1207. min_form.set_minor_threshold(threshold)
  1208. formatted = min_form.format_ticks(ticks)
  1209. labelled = [f for f in formatted if len(f) > 0]
  1210. if has_minor:
  1211. assert len(labelled) > 0, (threshold, has_minor)
  1212. else:
  1213. assert len(labelled) == 0, (threshold, has_minor)
  1214. def test_minor_number(self):
  1215. """
  1216. Test the parameter minor_number
  1217. """
  1218. min_loc = mticker.LogitLocator(minor=True)
  1219. min_form = mticker.LogitFormatter(minor=True)
  1220. ticks = min_loc.tick_values(5e-2, 1 - 5e-2)
  1221. for minor_number in (2, 4, 8, 16):
  1222. min_form.set_minor_number(minor_number)
  1223. formatted = min_form.format_ticks(ticks)
  1224. labelled = [f for f in formatted if len(f) > 0]
  1225. assert len(labelled) == minor_number
  1226. def test_use_overline(self):
  1227. """
  1228. Test the parameter use_overline
  1229. """
  1230. x = 1 - 1e-2
  1231. fx1 = r"$\mathdefault{1-10^{-2}}$"
  1232. fx2 = r"$\mathdefault{\overline{10^{-2}}}$"
  1233. form = mticker.LogitFormatter(use_overline=False)
  1234. assert form(x) == fx1
  1235. form.use_overline(True)
  1236. assert form(x) == fx2
  1237. form.use_overline(False)
  1238. assert form(x) == fx1
  1239. def test_one_half(self):
  1240. """
  1241. Test the parameter one_half
  1242. """
  1243. form = mticker.LogitFormatter()
  1244. assert r"\frac{1}{2}" in form(1/2)
  1245. form.set_one_half("1/2")
  1246. assert "1/2" in form(1/2)
  1247. form.set_one_half("one half")
  1248. assert "one half" in form(1/2)
  1249. @pytest.mark.parametrize("N", (100, 253, 754))
  1250. def test_format_data_short(self, N):
  1251. locs = np.linspace(0, 1, N)[1:-1]
  1252. form = mticker.LogitFormatter()
  1253. for x in locs:
  1254. fx = form.format_data_short(x)
  1255. if fx.startswith("1-"):
  1256. x2 = 1 - float(fx[2:])
  1257. else:
  1258. x2 = float(fx)
  1259. assert abs(x - x2) < 1 / N
  1260. class TestFormatStrFormatter:
  1261. def test_basic(self):
  1262. # test % style formatter
  1263. tmp_form = mticker.FormatStrFormatter('%05d')
  1264. assert '00002' == tmp_form(2)
  1265. class TestStrMethodFormatter:
  1266. test_data = [
  1267. ('{x:05d}', (2,), '00002'),
  1268. ('{x:03d}-{pos:02d}', (2, 1), '002-01'),
  1269. ]
  1270. @pytest.mark.parametrize('format, input, expected', test_data)
  1271. def test_basic(self, format, input, expected):
  1272. fmt = mticker.StrMethodFormatter(format)
  1273. assert fmt(*input) == expected
  1274. class TestEngFormatter:
  1275. # (unicode_minus, input, expected) where ''expected'' corresponds to the
  1276. # outputs respectively returned when (places=None, places=0, places=2)
  1277. # unicode_minus is a boolean value for the rcParam['axes.unicode_minus']
  1278. raw_format_data = [
  1279. (False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')),
  1280. (True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k',
  1281. '\N{MINUS SIGN}1.23 k')),
  1282. (False, -1.23456789, ('-1.23457', '-1', '-1.23')),
  1283. (True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1',
  1284. '\N{MINUS SIGN}1.23')),
  1285. (False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')),
  1286. (True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m',
  1287. '\N{MINUS SIGN}123.46 m')),
  1288. (False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')),
  1289. (True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m',
  1290. '\N{MINUS SIGN}1.23 m')),
  1291. (True, -0.0, ('0', '0', '0.00')),
  1292. (True, -0, ('0', '0', '0.00')),
  1293. (True, 0, ('0', '0', '0.00')),
  1294. (True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')),
  1295. (True, 0.123456789, ('123.457 m', '123 m', '123.46 m')),
  1296. (True, 0.1, ('100 m', '100 m', '100.00 m')),
  1297. (True, 1, ('1', '1', '1.00')),
  1298. (True, 1.23456789, ('1.23457', '1', '1.23')),
  1299. # places=0: corner-case rounding
  1300. (True, 999.9, ('999.9', '1 k', '999.90')),
  1301. # corner-case rounding for all
  1302. (True, 999.9999, ('1 k', '1 k', '1.00 k')),
  1303. # negative corner-case
  1304. (False, -999.9999, ('-1 k', '-1 k', '-1.00 k')),
  1305. (True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k',
  1306. '\N{MINUS SIGN}1.00 k')),
  1307. (True, 1000, ('1 k', '1 k', '1.00 k')),
  1308. (True, 1001, ('1.001 k', '1 k', '1.00 k')),
  1309. (True, 100001, ('100.001 k', '100 k', '100.00 k')),
  1310. (True, 987654.321, ('987.654 k', '988 k', '987.65 k')),
  1311. # OoR value (> 1000 Q)
  1312. (True, 1.23e33, ('1230 Q', '1230 Q', '1230.00 Q'))
  1313. ]
  1314. @pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data)
  1315. def test_params(self, unicode_minus, input, expected):
  1316. """
  1317. Test the formatting of EngFormatter for various values of the 'places'
  1318. argument, in several cases:
  1319. 0. without a unit symbol but with a (default) space separator;
  1320. 1. with both a unit symbol and a (default) space separator;
  1321. 2. with both a unit symbol and some non default separators;
  1322. 3. without a unit symbol but with some non default separators.
  1323. Note that cases 2. and 3. are looped over several separator strings.
  1324. """
  1325. plt.rcParams['axes.unicode_minus'] = unicode_minus
  1326. UNIT = 's' # seconds
  1327. DIGITS = '0123456789' # %timeit showed 10-20% faster search than set
  1328. # Case 0: unit='' (default) and sep=' ' (default).
  1329. # 'expected' already corresponds to this reference case.
  1330. exp_outputs = expected
  1331. formatters = (
  1332. mticker.EngFormatter(), # places=None (default)
  1333. mticker.EngFormatter(places=0),
  1334. mticker.EngFormatter(places=2)
  1335. )
  1336. for _formatter, _exp_output in zip(formatters, exp_outputs):
  1337. assert _formatter(input) == _exp_output
  1338. # Case 1: unit=UNIT and sep=' ' (default).
  1339. # Append a unit symbol to the reference case.
  1340. # Beware of the values in [1, 1000), where there is no prefix!
  1341. exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix
  1342. else _s + UNIT for _s in expected)
  1343. formatters = (
  1344. mticker.EngFormatter(unit=UNIT), # places=None (default)
  1345. mticker.EngFormatter(unit=UNIT, places=0),
  1346. mticker.EngFormatter(unit=UNIT, places=2)
  1347. )
  1348. for _formatter, _exp_output in zip(formatters, exp_outputs):
  1349. assert _formatter(input) == _exp_output
  1350. # Test several non default separators: no separator, a narrow
  1351. # no-break space (Unicode character) and an extravagant string.
  1352. for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"):
  1353. # Case 2: unit=UNIT and sep=_sep.
  1354. # Replace the default space separator from the reference case
  1355. # with the tested one `_sep` and append a unit symbol to it.
  1356. exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix
  1357. else _s.replace(" ", _sep) + UNIT
  1358. for _s in expected)
  1359. formatters = (
  1360. mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None
  1361. mticker.EngFormatter(unit=UNIT, places=0, sep=_sep),
  1362. mticker.EngFormatter(unit=UNIT, places=2, sep=_sep)
  1363. )
  1364. for _formatter, _exp_output in zip(formatters, exp_outputs):
  1365. assert _formatter(input) == _exp_output
  1366. # Case 3: unit='' (default) and sep=_sep.
  1367. # Replace the default space separator from the reference case
  1368. # with the tested one `_sep`. Reference case is already unitless.
  1369. exp_outputs = (_s.replace(" ", _sep) for _s in expected)
  1370. formatters = (
  1371. mticker.EngFormatter(sep=_sep), # places=None (default)
  1372. mticker.EngFormatter(places=0, sep=_sep),
  1373. mticker.EngFormatter(places=2, sep=_sep)
  1374. )
  1375. for _formatter, _exp_output in zip(formatters, exp_outputs):
  1376. assert _formatter(input) == _exp_output
  1377. def test_engformatter_usetex_useMathText():
  1378. fig, ax = plt.subplots()
  1379. ax.plot([0, 500, 1000], [0, 500, 1000])
  1380. ax.set_xticks([0, 500, 1000])
  1381. for formatter in (mticker.EngFormatter(usetex=True),
  1382. mticker.EngFormatter(useMathText=True)):
  1383. ax.xaxis.set_major_formatter(formatter)
  1384. fig.canvas.draw()
  1385. x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()]
  1386. # Checking if the dollar `$` signs have been inserted around numbers
  1387. # in tick labels.
  1388. assert x_tick_label_text == ['$0$', '$500$', '$1$ k']
  1389. class TestPercentFormatter:
  1390. percent_data = [
  1391. # Check explicitly set decimals over different intervals and values
  1392. (100, 0, '%', 120, 100, '120%'),
  1393. (100, 0, '%', 100, 90, '100%'),
  1394. (100, 0, '%', 90, 50, '90%'),
  1395. (100, 0, '%', -1.7, 40, '-2%'),
  1396. (100, 1, '%', 90.0, 100, '90.0%'),
  1397. (100, 1, '%', 80.1, 90, '80.1%'),
  1398. (100, 1, '%', 70.23, 50, '70.2%'),
  1399. # 60.554 instead of 60.55: see https://bugs.python.org/issue5118
  1400. (100, 1, '%', -60.554, 40, '-60.6%'),
  1401. # Check auto decimals over different intervals and values
  1402. (100, None, '%', 95, 1, '95.00%'),
  1403. (1.0, None, '%', 3, 6, '300%'),
  1404. (17.0, None, '%', 1, 8.5, '6%'),
  1405. (17.0, None, '%', 1, 8.4, '5.9%'),
  1406. (5, None, '%', -100, 0.000001, '-2000.00000%'),
  1407. # Check percent symbol
  1408. (1.0, 2, None, 1.2, 100, '120.00'),
  1409. (75, 3, '', 50, 100, '66.667'),
  1410. (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'),
  1411. ]
  1412. percent_ids = [
  1413. # Check explicitly set decimals over different intervals and values
  1414. 'decimals=0, x>100%',
  1415. 'decimals=0, x=100%',
  1416. 'decimals=0, x<100%',
  1417. 'decimals=0, x<0%',
  1418. 'decimals=1, x>100%',
  1419. 'decimals=1, x=100%',
  1420. 'decimals=1, x<100%',
  1421. 'decimals=1, x<0%',
  1422. # Check auto decimals over different intervals and values
  1423. 'autodecimal, x<100%, display_range=1',
  1424. 'autodecimal, x>100%, display_range=6 (custom xmax test)',
  1425. 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)',
  1426. 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)',
  1427. 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)',
  1428. # Check percent symbol
  1429. 'None as percent symbol',
  1430. 'Empty percent symbol',
  1431. 'Custom percent symbol',
  1432. ]
  1433. latex_data = [
  1434. (False, False, r'50\{t}%'),
  1435. (False, True, r'50\\\{t\}\%'),
  1436. (True, False, r'50\{t}%'),
  1437. (True, True, r'50\{t}%'),
  1438. ]
  1439. @pytest.mark.parametrize(
  1440. 'xmax, decimals, symbol, x, display_range, expected',
  1441. percent_data, ids=percent_ids)
  1442. def test_basic(self, xmax, decimals, symbol,
  1443. x, display_range, expected):
  1444. formatter = mticker.PercentFormatter(xmax, decimals, symbol)
  1445. with mpl.rc_context(rc={'text.usetex': False}):
  1446. assert formatter.format_pct(x, display_range) == expected
  1447. @pytest.mark.parametrize('is_latex, usetex, expected', latex_data)
  1448. def test_latex(self, is_latex, usetex, expected):
  1449. fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex)
  1450. with mpl.rc_context(rc={'text.usetex': usetex}):
  1451. assert fmt.format_pct(50, 100) == expected
  1452. def _impl_locale_comma():
  1453. try:
  1454. locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
  1455. except locale.Error:
  1456. print('SKIP: Locale de_DE.UTF-8 is not supported on this machine')
  1457. return
  1458. ticks = mticker.ScalarFormatter(useMathText=True, useLocale=True)
  1459. fmt = '$\\mathdefault{%1.1f}$'
  1460. x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
  1461. assert x == '$\\mathdefault{0{,}5}$'
  1462. # Do not change , in the format string
  1463. fmt = ',$\\mathdefault{,%1.1f},$'
  1464. x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
  1465. assert x == ',$\\mathdefault{,0{,}5},$'
  1466. # Make sure no brackets are added if not using math text
  1467. ticks = mticker.ScalarFormatter(useMathText=False, useLocale=True)
  1468. fmt = '%1.1f'
  1469. x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
  1470. assert x == '0,5'
  1471. def test_locale_comma():
  1472. # On some systems/pytest versions, `pytest.skip` in an exception handler
  1473. # does not skip, but is treated as an exception, so directly running this
  1474. # test can incorrectly fail instead of skip.
  1475. # Instead, run this test in a subprocess, which avoids the problem, and the
  1476. # need to fix the locale after.
  1477. proc = mpl.testing.subprocess_run_helper(_impl_locale_comma, timeout=60,
  1478. extra_env={'MPLBACKEND': 'Agg'})
  1479. skip_msg = next((line[len('SKIP:'):].strip()
  1480. for line in proc.stdout.splitlines()
  1481. if line.startswith('SKIP:')),
  1482. '')
  1483. if skip_msg:
  1484. pytest.skip(skip_msg)
  1485. def test_majformatter_type():
  1486. fig, ax = plt.subplots()
  1487. with pytest.raises(TypeError):
  1488. ax.xaxis.set_major_formatter(mticker.LogLocator())
  1489. def test_minformatter_type():
  1490. fig, ax = plt.subplots()
  1491. with pytest.raises(TypeError):
  1492. ax.xaxis.set_minor_formatter(mticker.LogLocator())
  1493. def test_majlocator_type():
  1494. fig, ax = plt.subplots()
  1495. with pytest.raises(TypeError):
  1496. ax.xaxis.set_major_locator(mticker.LogFormatter())
  1497. def test_minlocator_type():
  1498. fig, ax = plt.subplots()
  1499. with pytest.raises(TypeError):
  1500. ax.xaxis.set_minor_locator(mticker.LogFormatter())
  1501. def test_minorticks_rc():
  1502. fig = plt.figure()
  1503. def minorticksubplot(xminor, yminor, i):
  1504. rc = {'xtick.minor.visible': xminor,
  1505. 'ytick.minor.visible': yminor}
  1506. with plt.rc_context(rc=rc):
  1507. ax = fig.add_subplot(2, 2, i)
  1508. assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor
  1509. assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor
  1510. minorticksubplot(False, False, 1)
  1511. minorticksubplot(True, False, 2)
  1512. minorticksubplot(False, True, 3)
  1513. minorticksubplot(True, True, 4)
  1514. @pytest.mark.parametrize('remove_overlapping_locs, expected_num',
  1515. ((True, 6),
  1516. (None, 6), # this tests the default
  1517. (False, 9)))
  1518. def test_remove_overlap(remove_overlapping_locs, expected_num):
  1519. t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64")
  1520. x = np.ones(len(t))
  1521. fig, ax = plt.subplots()
  1522. ax.plot(t, x)
  1523. ax.xaxis.set_major_locator(mpl.dates.DayLocator())
  1524. ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a'))
  1525. ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18)))
  1526. ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M'))
  1527. # force there to be extra ticks
  1528. ax.xaxis.get_minor_ticks(15)
  1529. if remove_overlapping_locs is not None:
  1530. ax.xaxis.remove_overlapping_locs = remove_overlapping_locs
  1531. # check that getter/setter exists
  1532. current = ax.xaxis.remove_overlapping_locs
  1533. assert (current == ax.xaxis.get_remove_overlapping_locs())
  1534. plt.setp(ax.xaxis, remove_overlapping_locs=current)
  1535. new = ax.xaxis.remove_overlapping_locs
  1536. assert (new == ax.xaxis.remove_overlapping_locs)
  1537. # check that the accessors filter correctly
  1538. # this is the method that does the actual filtering
  1539. assert len(ax.xaxis.get_minorticklocs()) == expected_num
  1540. # these three are derivative
  1541. assert len(ax.xaxis.get_minor_ticks()) == expected_num
  1542. assert len(ax.xaxis.get_minorticklabels()) == expected_num
  1543. assert len(ax.xaxis.get_minorticklines()) == expected_num*2
  1544. @pytest.mark.parametrize('sub', [
  1545. ['hi', 'aardvark'],
  1546. np.zeros((2, 2))])
  1547. def test_bad_locator_subs(sub):
  1548. ll = mticker.LogLocator()
  1549. with pytest.raises(ValueError):
  1550. ll.set_params(subs=sub)
  1551. @pytest.mark.parametrize('numticks', [1, 2, 3, 9])
  1552. @mpl.style.context('default')
  1553. def test_small_range_loglocator(numticks):
  1554. ll = mticker.LogLocator()
  1555. ll.set_params(numticks=numticks)
  1556. for top in [5, 7, 9, 11, 15, 50, 100, 1000]:
  1557. ticks = ll.tick_values(.5, top)
  1558. assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all()
  1559. def test_NullFormatter():
  1560. formatter = mticker.NullFormatter()
  1561. assert formatter(1.0) == ''
  1562. assert formatter.format_data(1.0) == ''
  1563. assert formatter.format_data_short(1.0) == ''
  1564. @pytest.mark.parametrize('formatter', (
  1565. mticker.FuncFormatter(lambda a: f'val: {a}'),
  1566. mticker.FixedFormatter(('foo', 'bar'))))
  1567. def test_set_offset_string(formatter):
  1568. assert formatter.get_offset() == ''
  1569. formatter.set_offset_string('mpl')
  1570. assert formatter.get_offset() == 'mpl'