matplotlib-rs 0.0.8__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. docs/releases/0.0.1.md +268 -0
  2. docs/releases/0.0.2.md +69 -0
  3. docs/releases/0.0.3.md +80 -0
  4. docs/releases/0.0.4.md +73 -0
  5. docs/releases/0.0.5.md +24 -0
  6. docs/releases/0.0.6.md +24 -0
  7. docs/releases/0.0.7.md +24 -0
  8. docs/releases/0.0.8.md +16 -0
  9. licenses/LICENSE_CONTOURPY +29 -0
  10. licenses/LICENSE_CYCLER +27 -0
  11. licenses/LICENSE_DATEUTIL +54 -0
  12. licenses/LICENSE_KIWISOLVER +71 -0
  13. licenses/LICENSE_LIBWEBP +56 -0
  14. licenses/LICENSE_MATPLOTLIB +1253 -0
  15. licenses/LICENSE_PYPARSING +20 -0
  16. licenses/LICENSE_QHULL +39 -0
  17. licenses/LICENSE_SIX +18 -0
  18. matplotlib_rs/__init__.py +1683 -0
  19. matplotlib_rs/__main__.py +27 -0
  20. matplotlib_rs/_afm.py +500 -0
  21. matplotlib_rs/_animation_data.py +263 -0
  22. matplotlib_rs/_api/__init__.py +495 -0
  23. matplotlib_rs/_api/deprecation.py +534 -0
  24. matplotlib_rs/_axis_py.py +2991 -0
  25. matplotlib_rs/_blocking_input.py +31 -0
  26. matplotlib_rs/_cm.py +1500 -0
  27. matplotlib_rs/_cm_bivar.py +1289 -0
  28. matplotlib_rs/_cm_listed.py +2848 -0
  29. matplotlib_rs/_cm_multivar.py +167 -0
  30. matplotlib_rs/_color_data.py +1142 -0
  31. matplotlib_rs/_colormap.py +132 -0
  32. matplotlib_rs/_constrained_layout.py +825 -0
  33. matplotlib_rs/_contour.py +108 -0
  34. matplotlib_rs/_doc_cache.py +12214 -0
  35. matplotlib_rs/_docstring.py +142 -0
  36. matplotlib_rs/_enums.py +178 -0
  37. matplotlib_rs/_figure_rs.py +294 -0
  38. matplotlib_rs/_fontconfig_pattern.py +129 -0
  39. matplotlib_rs/_foreign.py +220 -0
  40. matplotlib_rs/_hook.py +94 -0
  41. matplotlib_rs/_image.py +160 -0
  42. matplotlib_rs/_imageio.py +229 -0
  43. matplotlib_rs/_internal_utils.py +65 -0
  44. matplotlib_rs/_kiwi.py +484 -0
  45. matplotlib_rs/_layoutgrid.py +549 -0
  46. matplotlib_rs/_live.py +192 -0
  47. matplotlib_rs/_mathtext.py +3103 -0
  48. matplotlib_rs/_mathtext_data.py +1811 -0
  49. matplotlib_rs/_mplrs.cp315-win_amd64.pyd +0 -0
  50. matplotlib_rs/_path.py +25 -0
  51. matplotlib_rs/_png.py +162 -0
  52. matplotlib_rs/_pylab_helpers.py +137 -0
  53. matplotlib_rs/_qhull.py +66 -0
  54. matplotlib_rs/_rcpush.py +84 -0
  55. matplotlib_rs/_spines_rs.py +108 -0
  56. matplotlib_rs/_style_helpers.py +52 -0
  57. matplotlib_rs/_text_helpers.py +51 -0
  58. matplotlib_rs/_tight_bbox.py +85 -0
  59. matplotlib_rs/_tight_layout.py +302 -0
  60. matplotlib_rs/_tri.py +140 -0
  61. matplotlib_rs/_type1font.py +1228 -0
  62. matplotlib_rs/_vendor/__init__.py +8 -0
  63. matplotlib_rs/_vendor/cycler.py +574 -0
  64. matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
  65. matplotlib_rs/_vendor/dateutil/_common.py +44 -0
  66. matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
  67. matplotlib_rs/_vendor/dateutil/_version.py +5 -0
  68. matplotlib_rs/_vendor/dateutil/easter.py +90 -0
  69. matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
  70. matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
  71. matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
  72. matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
  73. matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
  74. matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
  75. matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
  76. matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
  77. matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
  78. matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
  79. matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
  80. matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
  81. matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
  82. matplotlib_rs/_vendor/dateutil/utils.py +72 -0
  83. matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
  84. matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
  85. matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
  86. matplotlib_rs/_vendor/pyparsing/common.py +571 -0
  87. matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
  88. matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
  89. matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
  90. matplotlib_rs/_vendor/pyparsing/results.py +929 -0
  91. matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
  92. matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
  93. matplotlib_rs/_vendor/pyparsing/util.py +515 -0
  94. matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
  95. matplotlib_rs/_vendor/six.py +1004 -0
  96. matplotlib_rs/animation.py +1843 -0
  97. matplotlib_rs/artist.py +2302 -0
  98. matplotlib_rs/axes/__init__.py +19 -0
  99. matplotlib_rs/axes/_axes.py +9402 -0
  100. matplotlib_rs/axes/_bar.py +185 -0
  101. matplotlib_rs/axes/_base.py +5236 -0
  102. matplotlib_rs/axes/_base_rs.py +727 -0
  103. matplotlib_rs/axes/_boxplot.py +391 -0
  104. matplotlib_rs/axes/_hist.py +99 -0
  105. matplotlib_rs/axes/_secondary_axes.py +357 -0
  106. matplotlib_rs/axis.py +1963 -0
  107. matplotlib_rs/backend_bases.py +3760 -0
  108. matplotlib_rs/backend_managers.py +388 -0
  109. matplotlib_rs/backend_tools.py +1002 -0
  110. matplotlib_rs/backends/__init__.py +6 -0
  111. matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
  112. matplotlib_rs/backends/backend_agg.py +552 -0
  113. matplotlib_rs/backends/backend_mixed.py +123 -0
  114. matplotlib_rs/backends/backend_pdf.py +2711 -0
  115. matplotlib_rs/backends/backend_pgf.py +1031 -0
  116. matplotlib_rs/backends/backend_ps.py +1491 -0
  117. matplotlib_rs/backends/backend_svg.py +1395 -0
  118. matplotlib_rs/backends/backend_template.py +214 -0
  119. matplotlib_rs/backends/registry.py +423 -0
  120. matplotlib_rs/bezier.py +691 -0
  121. matplotlib_rs/category.py +236 -0
  122. matplotlib_rs/cbook.py +2762 -0
  123. matplotlib_rs/cm.py +251 -0
  124. matplotlib_rs/collections.py +2711 -0
  125. matplotlib_rs/colorbar.py +1586 -0
  126. matplotlib_rs/colorizer.py +909 -0
  127. matplotlib_rs/colors.py +4278 -0
  128. matplotlib_rs/container.py +256 -0
  129. matplotlib_rs/contour.py +1756 -0
  130. matplotlib_rs/dates.py +1847 -0
  131. matplotlib_rs/dviread.py +1386 -0
  132. matplotlib_rs/figure.py +3815 -0
  133. matplotlib_rs/font_manager.py +1855 -0
  134. matplotlib_rs/ft2font.py +515 -0
  135. matplotlib_rs/gridspec.py +808 -0
  136. matplotlib_rs/hatch.py +244 -0
  137. matplotlib_rs/image.py +1863 -0
  138. matplotlib_rs/inset.py +291 -0
  139. matplotlib_rs/layout_engine.py +310 -0
  140. matplotlib_rs/legend.py +1480 -0
  141. matplotlib_rs/legend_handler.py +812 -0
  142. matplotlib_rs/lines.py +1886 -0
  143. matplotlib_rs/markers.py +908 -0
  144. matplotlib_rs/mathtext.py +141 -0
  145. matplotlib_rs/mlab.py +959 -0
  146. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
  147. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
  148. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
  149. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
  150. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
  151. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
  152. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
  153. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
  154. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
  155. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
  156. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
  157. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
  158. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
  159. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
  160. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
  161. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
  162. matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
  163. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
  164. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
  165. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
  166. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
  167. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
  168. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
  169. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
  170. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
  171. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
  172. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
  173. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
  174. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
  175. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
  176. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
  177. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
  178. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
  179. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
  180. matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
  181. matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
  182. matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
  183. matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
  184. matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
  185. matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
  186. matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
  187. matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
  188. matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
  189. matplotlib_rs/mpl-data/images/back.pdf +0 -0
  190. matplotlib_rs/mpl-data/images/back.png +0 -0
  191. matplotlib_rs/mpl-data/images/back.svg +46 -0
  192. matplotlib_rs/mpl-data/images/back_large.png +0 -0
  193. matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
  194. matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
  195. matplotlib_rs/mpl-data/images/filesave.png +0 -0
  196. matplotlib_rs/mpl-data/images/filesave.svg +68 -0
  197. matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
  198. matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
  199. matplotlib_rs/mpl-data/images/forward.pdf +0 -0
  200. matplotlib_rs/mpl-data/images/forward.png +0 -0
  201. matplotlib_rs/mpl-data/images/forward.svg +46 -0
  202. matplotlib_rs/mpl-data/images/forward_large.png +0 -0
  203. matplotlib_rs/mpl-data/images/hand.pdf +0 -0
  204. matplotlib_rs/mpl-data/images/hand.png +0 -0
  205. matplotlib_rs/mpl-data/images/hand.svg +130 -0
  206. matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
  207. matplotlib_rs/mpl-data/images/help.pdf +71 -0
  208. matplotlib_rs/mpl-data/images/help.png +0 -0
  209. matplotlib_rs/mpl-data/images/help.svg +52 -0
  210. matplotlib_rs/mpl-data/images/help_large.png +0 -0
  211. matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
  212. matplotlib_rs/mpl-data/images/home.pdf +0 -0
  213. matplotlib_rs/mpl-data/images/home.png +0 -0
  214. matplotlib_rs/mpl-data/images/home.svg +59 -0
  215. matplotlib_rs/mpl-data/images/home_large.png +0 -0
  216. matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
  217. matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
  218. matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
  219. matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
  220. matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
  221. matplotlib_rs/mpl-data/images/move.pdf +0 -0
  222. matplotlib_rs/mpl-data/images/move.png +0 -0
  223. matplotlib_rs/mpl-data/images/move.svg +73 -0
  224. matplotlib_rs/mpl-data/images/move_large.png +0 -0
  225. matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
  226. matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
  227. matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
  228. matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
  229. matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
  230. matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
  231. matplotlib_rs/mpl-data/images/subplots.png +0 -0
  232. matplotlib_rs/mpl-data/images/subplots.svg +81 -0
  233. matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
  234. matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
  235. matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
  236. matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
  237. matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
  238. matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
  239. matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
  240. matplotlib_rs/mpl-data/matplotlibrc +849 -0
  241. matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
  242. matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
  243. matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
  244. matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
  245. matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
  246. matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
  247. matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
  248. matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
  249. matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
  250. matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
  251. matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
  252. matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
  253. matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
  254. matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
  255. matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
  256. matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
  257. matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
  258. matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
  259. matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
  260. matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
  261. matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
  262. matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
  263. matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
  264. matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
  265. matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
  266. matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
  267. matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
  268. matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
  269. matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
  270. matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
  271. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
  272. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
  273. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
  274. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
  275. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
  276. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
  277. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
  278. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
  279. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
  280. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
  281. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
  282. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
  283. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
  284. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
  285. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
  286. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
  287. matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
  288. matplotlib_rs/mpl_toolkits/__init__.py +3 -0
  289. matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
  290. matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
  291. matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
  292. matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
  293. matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
  294. matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
  295. matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
  296. matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
  297. matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
  298. matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
  299. matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
  300. matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
  301. matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
  302. matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
  303. matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
  304. matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
  305. matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
  306. matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
  307. matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
  308. matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
  309. matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
  310. matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
  311. matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
  312. matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
  313. matplotlib_rs/offsetbox.py +1726 -0
  314. matplotlib_rs/patches.py +5049 -0
  315. matplotlib_rs/path.py +1147 -0
  316. matplotlib_rs/patheffects.py +512 -0
  317. matplotlib_rs/projections/__init__.py +126 -0
  318. matplotlib_rs/projections/geo.py +512 -0
  319. matplotlib_rs/projections/polar.py +1518 -0
  320. matplotlib_rs/pylab.py +68 -0
  321. matplotlib_rs/pyplot.py +4834 -0
  322. matplotlib_rs/quiver.py +1236 -0
  323. matplotlib_rs/rcsetup.py +3435 -0
  324. matplotlib_rs/sankey.py +815 -0
  325. matplotlib_rs/scale.py +1002 -0
  326. matplotlib_rs/spines.py +618 -0
  327. matplotlib_rs/stackplot.py +144 -0
  328. matplotlib_rs/streamplot.py +768 -0
  329. matplotlib_rs/style/__init__.py +269 -0
  330. matplotlib_rs/style/core.py +28 -0
  331. matplotlib_rs/table.py +860 -0
  332. matplotlib_rs/texmanager.py +375 -0
  333. matplotlib_rs/text.py +2412 -0
  334. matplotlib_rs/textpath.py +377 -0
  335. matplotlib_rs/ticker.py +3111 -0
  336. matplotlib_rs/transforms.py +3069 -0
  337. matplotlib_rs/tri/__init__.py +24 -0
  338. matplotlib_rs/tri/_triangulation.py +248 -0
  339. matplotlib_rs/tri/_tricontour.py +271 -0
  340. matplotlib_rs/tri/_trifinder.py +97 -0
  341. matplotlib_rs/tri/_triinterpolate.py +1575 -0
  342. matplotlib_rs/tri/_tripcolor.py +170 -0
  343. matplotlib_rs/tri/_triplot.py +87 -0
  344. matplotlib_rs/tri/_trirefine.py +308 -0
  345. matplotlib_rs/tri/_tritools.py +264 -0
  346. matplotlib_rs/typing.py +597 -0
  347. matplotlib_rs/units.py +196 -0
  348. matplotlib_rs/widgets.py +4455 -0
  349. matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
  350. matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
  351. matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
  352. matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
@@ -0,0 +1,3111 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ Tick locating and formatting
4
+ ============================
5
+
6
+ This module contains classes for configuring tick locating and formatting.
7
+ Generic tick locators and formatters are provided, as well as domain specific
8
+ custom ones.
9
+
10
+ Although the locators know nothing about major or minor ticks, they are used
11
+ by the Axis class to support major and minor tick locating and formatting.
12
+
13
+ .. _tick_locating:
14
+ .. _locators:
15
+
16
+ Tick locating
17
+ -------------
18
+
19
+ The Locator class is the base class for all tick locators. The locators
20
+ handle autoscaling of the view limits based on the data limits, and the
21
+ choosing of tick locations. A useful semi-automatic tick locator is
22
+ `MultipleLocator`. It is initialized with a base, e.g., 10, and it picks
23
+ axis limits and ticks that are multiples of that base.
24
+
25
+ The Locator subclasses defined here are:
26
+
27
+ ======================= =======================================================
28
+ `AutoLocator` `MaxNLocator` with simple defaults. This is the default
29
+ tick locator for most plotting.
30
+ `MaxNLocator` Finds up to a max number of intervals with ticks at
31
+ nice locations.
32
+ `LinearLocator` Space ticks evenly from min to max.
33
+ `LogLocator` Space ticks logarithmically from min to max.
34
+ `MultipleLocator` Ticks and range are a multiple of base; either integer
35
+ or float.
36
+ `FixedLocator` Tick locations are fixed.
37
+ `IndexLocator` Locator for index plots (e.g., where
38
+ ``x = range(len(y))``).
39
+ `NullLocator` No ticks.
40
+ `SymmetricalLogLocator` Locator for use with the symlog norm; works like
41
+ `LogLocator` for the part outside of the threshold and
42
+ adds 0 if inside the limits.
43
+ `AsinhLocator` Locator for use with the asinh norm, attempting to
44
+ space ticks approximately uniformly.
45
+ `LogitLocator` Locator for logit scaling.
46
+ `AutoMinorLocator` Locator for minor ticks when the axis is linear and the
47
+ major ticks are uniformly spaced. Subdivides the major
48
+ tick interval into a specified number of minor
49
+ intervals, defaulting to 4 or 5 depending on the major
50
+ interval.
51
+ ======================= =======================================================
52
+
53
+ There are a number of locators specialized for date locations - see
54
+ the :mod:`.dates` module.
55
+
56
+ You can define your own locator by deriving from Locator. You must
57
+ override the ``__call__`` method, which returns a sequence of locations,
58
+ and you will probably want to override the autoscale method to set the
59
+ view limits from the data limits.
60
+
61
+ If you want to override the default locator, use one of the above or a custom
62
+ locator and pass it to the x- or y-axis instance. The relevant methods are::
63
+
64
+ ax.xaxis.set_major_locator(xmajor_locator)
65
+ ax.xaxis.set_minor_locator(xminor_locator)
66
+ ax.yaxis.set_major_locator(ymajor_locator)
67
+ ax.yaxis.set_minor_locator(yminor_locator)
68
+
69
+ The default minor locator is `NullLocator`, i.e., no minor ticks on by default.
70
+
71
+ .. note::
72
+ `Locator` instances should not be used with more than one
73
+ `~matplotlib.axis.Axis` or `~matplotlib.axes.Axes`. So instead of::
74
+
75
+ locator = MultipleLocator(5)
76
+ ax.xaxis.set_major_locator(locator)
77
+ ax2.xaxis.set_major_locator(locator)
78
+
79
+ do the following instead::
80
+
81
+ ax.xaxis.set_major_locator(MultipleLocator(5))
82
+ ax2.xaxis.set_major_locator(MultipleLocator(5))
83
+
84
+ .. _formatters:
85
+
86
+ Tick formatting
87
+ ---------------
88
+
89
+ Tick formatting is controlled by classes derived from Formatter. The formatter
90
+ operates on a single tick value and returns a string to the axis.
91
+
92
+ ========================= =====================================================
93
+ `NullFormatter` No labels on the ticks.
94
+ `FixedFormatter` Set the strings manually for the labels.
95
+ `FuncFormatter` User defined function sets the labels.
96
+ `StrMethodFormatter` Use string `format` method.
97
+ `FormatStrFormatter` Use an old-style sprintf format string.
98
+ `ScalarFormatter` Default formatter for scalars: autopick the format
99
+ string.
100
+ `LogFormatter` Formatter for log axes.
101
+ `LogFormatterExponent` Format values for log axis using
102
+ ``exponent = log_base(value)``.
103
+ `LogFormatterMathtext` Format values for log axis using
104
+ ``exponent = log_base(value)`` using Math text.
105
+ `LogFormatterSciNotation` Format values for log axis using scientific notation.
106
+ `LogitFormatter` Probability formatter.
107
+ `EngFormatter` Format labels in engineering notation.
108
+ `PercentFormatter` Format labels as a percentage.
109
+ ========================= =====================================================
110
+
111
+ You can derive your own formatter from the Formatter base class by
112
+ simply overriding the ``__call__`` method. The formatter class has
113
+ access to the axis view and data limits.
114
+
115
+ To control the major and minor tick label formats, use one of the
116
+ following methods::
117
+
118
+ ax.xaxis.set_major_formatter(xmajor_formatter)
119
+ ax.xaxis.set_minor_formatter(xminor_formatter)
120
+ ax.yaxis.set_major_formatter(ymajor_formatter)
121
+ ax.yaxis.set_minor_formatter(yminor_formatter)
122
+
123
+ In addition to a `.Formatter` instance, `~.Axis.set_major_formatter` and
124
+ `~.Axis.set_minor_formatter` also accept a ``str`` or function. ``str`` input
125
+ will be internally replaced with an autogenerated `.StrMethodFormatter` with
126
+ the input ``str``. For function input, a `.FuncFormatter` with the input
127
+ function will be generated and used.
128
+
129
+ See :doc:`/gallery/ticks/major_minor_demo` for an example of setting major
130
+ and minor ticks. See the :mod:`matplotlib.dates` module for more information
131
+ and examples of using date locators and formatters.
132
+ """
133
+
134
+ import itertools
135
+ import logging
136
+ import locale
137
+ import math
138
+ from numbers import Integral
139
+ import string
140
+
141
+ import numpy as np
142
+
143
+ import matplotlib_rs as mpl
144
+ from . import _api, cbook
145
+ from . import transforms as mtransforms
146
+
147
+ _log = logging.getLogger(__name__)
148
+
149
+ __all__ = ('TickHelper', 'Formatter', 'FixedFormatter',
150
+ 'NullFormatter', 'FuncFormatter', 'FormatStrFormatter',
151
+ 'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter',
152
+ 'LogFormatterExponent', 'LogFormatterMathtext',
153
+ 'LogFormatterSciNotation',
154
+ 'LogitFormatter', 'EngFormatter', 'PercentFormatter',
155
+ 'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator',
156
+ 'LinearLocator', 'LogLocator', 'AutoLocator',
157
+ 'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator',
158
+ 'SymmetricalLogLocator', 'AsinhLocator', 'LogitLocator')
159
+
160
+
161
+ class _DummyAxis:
162
+ __name__ = "dummy"
163
+
164
+ def __init__(self, minpos=0):
165
+ self._data_interval = (0, 1)
166
+ self._view_interval = (0, 1)
167
+ self._minpos = minpos
168
+
169
+ def get_view_interval(self):
170
+ return self._view_interval
171
+
172
+ def set_view_interval(self, vmin, vmax):
173
+ self._view_interval = (vmin, vmax)
174
+
175
+ def get_minpos(self):
176
+ return self._minpos
177
+
178
+ def get_data_interval(self):
179
+ return self._data_interval
180
+
181
+ def set_data_interval(self, vmin, vmax):
182
+ self._data_interval = (vmin, vmax)
183
+
184
+ def get_tick_space(self):
185
+ # Just use the long-standing default of nbins==9
186
+ return 9
187
+
188
+
189
+ class TickHelper:
190
+ axis = None
191
+
192
+ def set_axis(self, axis):
193
+ self.axis = axis
194
+
195
+ def create_dummy_axis(self, **kwargs):
196
+ if self.axis is None:
197
+ self.axis = _DummyAxis(**kwargs)
198
+
199
+
200
+ class Formatter(TickHelper):
201
+ """
202
+ Create a string based on a tick value and location.
203
+
204
+ The Formatter provides four formatting methods for different use cases:
205
+
206
+ - `format_ticks`: The public API for generating tick labels from a set of
207
+ tick values.
208
+ - `__call__`: The low-level primitive for formatting a single tick value,
209
+ potentially in the context of multiple values.
210
+ - `format_data`: Context-independent representation of a single value.
211
+ Used internally, e.g. for offset and scientific-notation strings.
212
+ - `format_data_short`: Concise plain-text representation of a single value
213
+ for the interactive mouseover tooltip.
214
+ """
215
+ # some classes want to see all the locs to help format
216
+ # individual ones
217
+ _locs = []
218
+
219
+ locs = _api.deprecate_privatize_attribute("3.11")
220
+
221
+ def __call__(self, x, pos=None):
222
+ """
223
+ Return the tick label strings for value *x* at tick index *pos*.
224
+
225
+ This is the low-level formatting primitive for a single tick in
226
+ the context of multiple ticks. Any context-dependent state
227
+ (e.g. locs, offset, order of magnitude) must already be configured,
228
+ typically by a prior call to ``format_ticks`` or ``set_locs``.
229
+
230
+ *pos* defines the index into ``self.locs`` so that the format can
231
+ depend on the location. ``pos=None`` indicates an unspecified
232
+ location.
233
+
234
+ The output may contain mathtext or LaTeX markup.
235
+
236
+ Subclasses must override this method.
237
+ """
238
+ raise NotImplementedError('Derived must override')
239
+
240
+ def format_ticks(self, values):
241
+ """
242
+ Return the tick label strings for all *values*.
243
+
244
+ This is the public API for generating tick labels. It calls
245
+ ``set_locs`` to configure context-dependent formatting state before
246
+ delegating to ``__call__`` for each individual value.
247
+
248
+ The output may contain mathtext or LaTeX markup.
249
+
250
+ Use this method (rather than ``__call__``) whenever formatting a
251
+ complete set of tick values, so that formatters which need to see
252
+ all tick locations (e.g. to determine precision, offsets, or which
253
+ date components to display) can work correctly.
254
+ """
255
+ self.set_locs(values)
256
+ return [self(value, i) for i, value in enumerate(values)]
257
+
258
+ def format_data(self, value):
259
+ """
260
+ Return the context-independent string representation of a single *value*.
261
+
262
+ This is used internally, e.g. for constructing offset and
263
+ scientific-notation strings. It always formats with ``pos=None``
264
+ and should return a context-independent representation
265
+ rather than a concise tick label.
266
+
267
+ The output may contain mathtext or LaTeX markup.
268
+ """
269
+ return self.__call__(value)
270
+
271
+ def format_data_short(self, value):
272
+ """
273
+ Return a short string representation of *value* for the mouseover
274
+ tooltip (the coordinate display in the interactive figure window).
275
+
276
+ This should return concise, plain text (no mathtext / LaTeX).
277
+ The precision is typically adapted to the current axis resolution
278
+ so that neighbouring pixels produce distinguishable labels.
279
+
280
+ Defaults to `.Formatter.format_data`; subclasses should override
281
+ this to provide a plain-text representation that is independent
282
+ of the current tick locations.
283
+
284
+ Note: The mouseover text can be customized by setting the
285
+ ``Axes.fmt_xdata`` and ``Axes.fmt_ydata`` attributes.
286
+ """
287
+ return self.format_data(value)
288
+
289
+ def get_offset(self):
290
+ return ''
291
+
292
+ def set_locs(self, locs):
293
+ """
294
+ Set the locations of the ticks.
295
+
296
+ This method is called before computing the tick labels because some
297
+ formatters need to know all tick locations to do so.
298
+ """
299
+ self._locs = locs
300
+
301
+ @staticmethod
302
+ def fix_minus(s):
303
+ """
304
+ Some classes may want to replace a hyphen for minus with the proper
305
+ Unicode symbol (U+2212) for typographical correctness. This is a
306
+ helper method to perform such a replacement when it is enabled via
307
+ :rc:`axes.unicode_minus`.
308
+ """
309
+ return (s.replace('-', '\N{MINUS SIGN}')
310
+ if mpl.rcParams['axes.unicode_minus']
311
+ else s)
312
+
313
+ def _set_locator(self, locator):
314
+ """Subclasses may want to override this to set a locator."""
315
+ pass
316
+
317
+
318
+ class NullFormatter(Formatter):
319
+ """Always return the empty string."""
320
+
321
+ def __call__(self, x, pos=None):
322
+ # docstring inherited
323
+ return ''
324
+
325
+
326
+ class FixedFormatter(Formatter):
327
+ """
328
+ Return fixed strings for tick labels based only on position, not value.
329
+
330
+ .. note::
331
+ `.FixedFormatter` should only be used together with `.FixedLocator`.
332
+ Otherwise, the labels may end up in unexpected positions.
333
+ """
334
+
335
+ def __init__(self, seq):
336
+ """Set the sequence *seq* of strings that will be used for labels."""
337
+ self.seq = seq
338
+ self.offset_string = ''
339
+
340
+ def __call__(self, x, pos=None):
341
+ """
342
+ Return the label that matches the position, regardless of the value.
343
+
344
+ For positions ``pos < len(seq)``, return ``seq[i]`` regardless of
345
+ *x*. Otherwise return empty string. ``seq`` is the sequence of
346
+ strings that this object was initialized with.
347
+ """
348
+ if pos is None or pos >= len(self.seq):
349
+ return ''
350
+ else:
351
+ return self.seq[pos]
352
+
353
+ def get_offset(self):
354
+ return self.offset_string
355
+
356
+ def set_offset_string(self, ofs):
357
+ self.offset_string = ofs
358
+
359
+
360
+ class FuncFormatter(Formatter):
361
+ """
362
+ Use a user-defined function for formatting.
363
+
364
+ The function should take in two inputs (a tick value ``x`` and a
365
+ position ``pos``), and return a string containing the corresponding
366
+ tick label.
367
+ """
368
+
369
+ def __init__(self, func):
370
+ self.func = func
371
+ self.offset_string = ""
372
+
373
+ def __call__(self, x, pos=None):
374
+ """
375
+ Return the value of the user defined function.
376
+
377
+ *x* and *pos* are passed through as-is.
378
+ """
379
+ return self.func(x, pos)
380
+
381
+ def get_offset(self):
382
+ return self.offset_string
383
+
384
+ def set_offset_string(self, ofs):
385
+ self.offset_string = ofs
386
+
387
+
388
+ class FormatStrFormatter(Formatter):
389
+ """
390
+ Use an old-style ('%' operator) format string to format the tick.
391
+
392
+ The format string should have a single variable format (%) in it.
393
+ It will be applied to the value (not the position) of the tick.
394
+
395
+ Negative numeric values (e.g., -1) will use a dash, not a Unicode minus;
396
+ use mathtext to get a Unicode minus by wrapping the format specifier with $
397
+ (e.g. "$%g$").
398
+ """
399
+
400
+ def __init__(self, fmt):
401
+ self.fmt = fmt
402
+
403
+ def __call__(self, x, pos=None):
404
+ """
405
+ Return the formatted label string.
406
+
407
+ Only the value *x* is formatted. The position is ignored.
408
+ """
409
+ return self.fmt % x
410
+
411
+
412
+ class _UnicodeMinusFormat(string.Formatter):
413
+ """
414
+ A specialized string formatter so that `.StrMethodFormatter` respects
415
+ :rc:`axes.unicode_minus`. This implementation relies on the fact that the
416
+ format string is only ever called with kwargs *x* and *pos*, so it blindly
417
+ replaces dashes by unicode minuses without further checking.
418
+ """
419
+
420
+ def format_field(self, value, format_spec):
421
+ return Formatter.fix_minus(super().format_field(value, format_spec))
422
+
423
+
424
+ class StrMethodFormatter(Formatter):
425
+ """
426
+ Use a new-style format string (as used by `str.format`) to format the tick.
427
+
428
+ The field used for the tick value must be labeled *x* and the field used
429
+ for the tick position must be labeled *pos*.
430
+
431
+ The formatter will respect :rc:`axes.unicode_minus` when formatting
432
+ negative numeric values.
433
+
434
+ It is typically unnecessary to explicitly construct `.StrMethodFormatter`
435
+ objects, as `~.Axis.set_major_formatter` directly accepts the format string
436
+ itself.
437
+
438
+ Examples
439
+ --------
440
+ >>> formatter = StrMethodFormatter("{x} km")
441
+ >>> formatter(10)
442
+ "10 km"
443
+ """
444
+
445
+ def __init__(self, fmt):
446
+ self.fmt = fmt
447
+
448
+ def __call__(self, x, pos=None):
449
+ """
450
+ Return the formatted label string.
451
+
452
+ *x* and *pos* are passed to `str.format` as keyword arguments
453
+ with those exact names.
454
+ """
455
+ return _UnicodeMinusFormat().format(self.fmt, x=x, pos=pos)
456
+
457
+
458
+ class ScalarFormatter(Formatter):
459
+ """
460
+ Format tick values as a number.
461
+
462
+ Parameters
463
+ ----------
464
+ useOffset : bool or float, default: :rc:`axes.formatter.useoffset`
465
+ Whether to use offset notation. See `.set_useOffset`.
466
+ useMathText : bool, default: :rc:`axes.formatter.use_mathtext`
467
+ Whether to use fancy math formatting. See `.set_useMathText`.
468
+ useLocale : bool, default: :rc:`axes.formatter.use_locale`.
469
+ Whether to use locale settings for decimal sign and positive sign.
470
+ See `.set_useLocale`.
471
+ usetex : bool, default: :rc:`text.usetex`
472
+ To enable/disable the use of TeX's math mode for rendering the
473
+ numbers in the formatter.
474
+
475
+ .. versionadded:: 3.10
476
+
477
+ Notes
478
+ -----
479
+ In addition to the parameters above, the formatting of scientific vs.
480
+ floating point representation can be configured via `.set_scientific`
481
+ and `.set_powerlimits`).
482
+
483
+ **Offset notation and scientific notation**
484
+
485
+ Offset notation and scientific notation look quite similar at first sight.
486
+ Both split some information from the formatted tick values and display it
487
+ at the end of the axis.
488
+
489
+ - The scientific notation splits up the order of magnitude, i.e. a
490
+ multiplicative scaling factor, e.g. ``1e6``.
491
+
492
+ - The offset notation separates an additive constant, e.g. ``+1e6``. The
493
+ offset notation label is always prefixed with a ``+`` or ``-`` sign
494
+ and is thus distinguishable from the order of magnitude label.
495
+
496
+ The following plot with x limits ``1_000_000`` to ``1_000_010`` illustrates
497
+ the different formatting. Note the labels at the right edge of the x axis.
498
+
499
+ .. plot::
500
+
501
+ lim = (1_000_000, 1_000_010)
502
+
503
+ fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw={'hspace': 2})
504
+ ax1.set(title='offset notation', xlim=lim)
505
+ ax2.set(title='scientific notation', xlim=lim)
506
+ ax2.xaxis.get_major_formatter().set_useOffset(False)
507
+ ax3.set(title='floating-point notation', xlim=lim)
508
+ ax3.xaxis.get_major_formatter().set_useOffset(False)
509
+ ax3.xaxis.get_major_formatter().set_scientific(False)
510
+
511
+ """
512
+
513
+ orderOfMagnitude = _api.deprecate_privatize_attribute("3.11")
514
+ format = _api.deprecate_privatize_attribute("3.11")
515
+
516
+ def __init__(self, useOffset=None, useMathText=None, useLocale=None, *,
517
+ usetex=None):
518
+ useOffset = mpl._val_or_rc(useOffset, 'axes.formatter.useoffset')
519
+ self._offset_threshold = mpl.rcParams['axes.formatter.offset_threshold']
520
+ self.set_useOffset(useOffset)
521
+ self.set_usetex(usetex)
522
+ self.set_useMathText(useMathText)
523
+ self._orderOfMagnitude = 0
524
+ self._format = ''
525
+ self._scientific = True
526
+ self._powerlimits = mpl.rcParams['axes.formatter.limits']
527
+ self.set_useLocale(useLocale)
528
+
529
+ def get_usetex(self):
530
+ """Return whether TeX's math mode is enabled for rendering."""
531
+ return self._usetex
532
+
533
+ def set_usetex(self, val):
534
+ """Set whether to use TeX's math mode for rendering numbers in the formatter."""
535
+ self._usetex = mpl._val_or_rc(val, 'text.usetex')
536
+
537
+ usetex = property(fget=get_usetex, fset=set_usetex)
538
+
539
+ def get_useOffset(self):
540
+ """
541
+ Return whether automatic mode for offset notation is active.
542
+
543
+ This returns True if ``set_useOffset(True)``; it returns False if an
544
+ explicit offset was set, e.g. ``set_useOffset(1000)``.
545
+
546
+ See Also
547
+ --------
548
+ ScalarFormatter.set_useOffset
549
+ """
550
+ return self._useOffset
551
+
552
+ def set_useOffset(self, val):
553
+ """
554
+ Set whether to use offset notation.
555
+
556
+ When formatting a set numbers whose value is large compared to their
557
+ range, the formatter can separate an additive constant. This can
558
+ shorten the formatted numbers so that they are less likely to overlap
559
+ when drawn on an axis.
560
+
561
+ Parameters
562
+ ----------
563
+ val : bool or float
564
+ - If False, do not use offset notation.
565
+ - If True (=automatic mode), use offset notation if it can make
566
+ the residual numbers significantly shorter. The exact behavior
567
+ is controlled by :rc:`axes.formatter.offset_threshold`.
568
+ - If a number, force an offset of the given value.
569
+
570
+ Examples
571
+ --------
572
+ With active offset notation, the values
573
+
574
+ ``100_000, 100_002, 100_004, 100_006, 100_008``
575
+
576
+ will be formatted as ``0, 2, 4, 6, 8`` plus an offset ``+1e5``, which
577
+ is written to the edge of the axis.
578
+ """
579
+ if isinstance(val, bool):
580
+ self.offset = 0
581
+ self._useOffset = val
582
+ else:
583
+ self._useOffset = False
584
+ self.offset = val
585
+
586
+ useOffset = property(fget=get_useOffset, fset=set_useOffset)
587
+
588
+ def get_useLocale(self):
589
+ """
590
+ Return whether locale settings are used for formatting.
591
+
592
+ See Also
593
+ --------
594
+ ScalarFormatter.set_useLocale
595
+ """
596
+ return self._useLocale
597
+
598
+ def set_useLocale(self, val):
599
+ """
600
+ Set whether to use locale settings for decimal sign and positive sign.
601
+
602
+ Parameters
603
+ ----------
604
+ val : bool or None
605
+ *None* resets to :rc:`axes.formatter.use_locale`.
606
+ """
607
+ self._useLocale = mpl._val_or_rc(val, 'axes.formatter.use_locale')
608
+
609
+ useLocale = property(fget=get_useLocale, fset=set_useLocale)
610
+
611
+ def _format_maybe_minus_and_locale(self, fmt, arg):
612
+ """
613
+ Format *arg* with *fmt*, applying Unicode minus and locale if desired.
614
+ """
615
+ return self.fix_minus(
616
+ # Escape commas introduced by locale.format_string if using math text,
617
+ # but not those present from the beginning in fmt.
618
+ (",".join(locale.format_string(part, (arg,), True).replace(",", "{,}")
619
+ for part in fmt.split(",")) if self._useMathText
620
+ else locale.format_string(fmt, (arg,), True))
621
+ if self._useLocale
622
+ else fmt % arg)
623
+
624
+ def get_useMathText(self):
625
+ """
626
+ Return whether to use fancy math formatting.
627
+
628
+ See Also
629
+ --------
630
+ ScalarFormatter.set_useMathText
631
+ """
632
+ return self._useMathText
633
+
634
+ def set_useMathText(self, val):
635
+ r"""
636
+ Set whether to use fancy math formatting.
637
+
638
+ If active, scientific notation is formatted as :math:`1.2 \times 10^3`.
639
+
640
+ Parameters
641
+ ----------
642
+ val : bool or None
643
+ *None* resets to :rc:`axes.formatter.use_mathtext`.
644
+ """
645
+ if val is None:
646
+ self._useMathText = mpl.rcParams['axes.formatter.use_mathtext']
647
+ if self._useMathText is False:
648
+ try:
649
+ from matplotlib_rs import font_manager
650
+ ufont = font_manager.findfont(
651
+ font_manager.FontProperties(
652
+ family=mpl.rcParams["font.family"]
653
+ ),
654
+ fallback_to_default=False,
655
+ )
656
+ except ValueError:
657
+ ufont = None
658
+
659
+ if ufont == str(cbook._get_data_path("fonts/ttf/cmr10.ttf")):
660
+ _api.warn_external(
661
+ "cmr10 font should ideally be used with "
662
+ "mathtext, set axes.formatter.use_mathtext to True"
663
+ )
664
+ else:
665
+ self._useMathText = val
666
+
667
+ useMathText = property(fget=get_useMathText, fset=set_useMathText)
668
+
669
+ def __call__(self, x, pos=None):
670
+ """
671
+ Return the format for tick value *x* at position *pos*.
672
+ """
673
+ if len(self._locs) == 0:
674
+ return ''
675
+ else:
676
+ xp = (x - self.offset) / (10. ** self._orderOfMagnitude)
677
+ if abs(xp) < 1e-8:
678
+ xp = 0
679
+ return self._format_maybe_minus_and_locale(self._format, xp)
680
+
681
+ def set_scientific(self, b):
682
+ """
683
+ Turn scientific notation on or off.
684
+
685
+ See Also
686
+ --------
687
+ ScalarFormatter.set_powerlimits
688
+ """
689
+ self._scientific = bool(b)
690
+
691
+ def set_powerlimits(self, lims):
692
+ r"""
693
+ Set size thresholds for scientific notation.
694
+
695
+ Parameters
696
+ ----------
697
+ lims : (int, int)
698
+ A tuple *(min_exp, max_exp)* containing the powers of 10 that
699
+ determine the switchover threshold. For a number representable as
700
+ :math:`a \times 10^\mathrm{exp}` with :math:`1 <= |a| < 10`,
701
+ scientific notation will be used if ``exp <= min_exp`` or
702
+ ``exp >= max_exp``.
703
+
704
+ The default limits are controlled by :rc:`axes.formatter.limits`.
705
+
706
+ In particular numbers with *exp* equal to the thresholds are
707
+ written in scientific notation.
708
+
709
+ Typically, *min_exp* will be negative and *max_exp* will be
710
+ positive.
711
+
712
+ For example, ``formatter.set_powerlimits((-3, 4))`` will provide
713
+ the following formatting:
714
+ :math:`1 \times 10^{-3}, 9.9 \times 10^{-3}, 0.01,`
715
+ :math:`9999, 1 \times 10^4`.
716
+
717
+ See Also
718
+ --------
719
+ ScalarFormatter.set_scientific
720
+ """
721
+ if len(lims) != 2:
722
+ raise ValueError("'lims' must be a sequence of length 2")
723
+ self._powerlimits = lims
724
+
725
+ def format_data_short(self, value):
726
+ # docstring inherited
727
+ if value is np.ma.masked:
728
+ return ""
729
+ if isinstance(value, Integral):
730
+ fmt = "%d"
731
+ else:
732
+ if getattr(self.axis, "__name__", "") in ["xaxis", "yaxis"]:
733
+ if self.axis.__name__ == "xaxis":
734
+ axis_trf = self.axis.axes.get_xaxis_transform()
735
+ axis_inv_trf = axis_trf.inverted()
736
+ screen_xy = axis_trf.transform((value, 0))
737
+ neighbor_values = axis_inv_trf.transform(
738
+ screen_xy + [[-1, 0], [+1, 0]])[:, 0]
739
+ else: # yaxis:
740
+ axis_trf = self.axis.axes.get_yaxis_transform()
741
+ axis_inv_trf = axis_trf.inverted()
742
+ screen_xy = axis_trf.transform((0, value))
743
+ neighbor_values = axis_inv_trf.transform(
744
+ screen_xy + [[0, -1], [0, +1]])[:, 1]
745
+ delta = abs(neighbor_values - value).max()
746
+ else:
747
+ # Rough approximation: no more than 1e4 divisions.
748
+ a, b = self.axis.get_view_interval()
749
+ delta = (b - a) / 1e4
750
+ fmt = f"%-#.{cbook._g_sig_digits(value, delta)}g"
751
+ return self._format_maybe_minus_and_locale(fmt, value)
752
+
753
+ def format_data(self, value):
754
+ # docstring inherited
755
+ e = math.floor(math.log10(abs(value)))
756
+ s = round(value / 10**e, 10)
757
+ significand = self._format_maybe_minus_and_locale(
758
+ "%d" if s % 1 == 0 else "%1.10g", s)
759
+ if e == 0:
760
+ return significand
761
+ exponent = self._format_maybe_minus_and_locale("%d", e)
762
+ if self._useMathText or self._usetex:
763
+ exponent = "10^{%s}" % exponent
764
+ return (exponent if s == 1 # reformat 1x10^y as 10^y
765
+ else rf"{significand} \times {exponent}")
766
+ else:
767
+ return f"{significand}e{exponent}"
768
+
769
+ def get_offset(self):
770
+ """
771
+ Return scientific notation, plus offset.
772
+ """
773
+ if len(self._locs) == 0:
774
+ return ''
775
+ if self._orderOfMagnitude or self.offset:
776
+ offsetStr = ''
777
+ sciNotStr = ''
778
+ if self.offset:
779
+ offsetStr = self.format_data(self.offset)
780
+ if self.offset > 0:
781
+ offsetStr = '+' + offsetStr
782
+ if self._orderOfMagnitude:
783
+ if self._usetex or self._useMathText:
784
+ sciNotStr = self.format_data(10 ** self._orderOfMagnitude)
785
+ else:
786
+ sciNotStr = '1e%d' % self._orderOfMagnitude
787
+ if self._useMathText or self._usetex:
788
+ if sciNotStr != '':
789
+ sciNotStr = r'\times\mathdefault{%s}' % sciNotStr
790
+ s = fr'${sciNotStr}\mathdefault{{{offsetStr}}}$'
791
+ else:
792
+ s = ''.join((sciNotStr, offsetStr))
793
+ return self.fix_minus(s)
794
+ return ''
795
+
796
+ def set_locs(self, locs):
797
+ # docstring inherited
798
+ self._locs = locs
799
+ if len(self._locs) > 0:
800
+ if self._useOffset:
801
+ self._compute_offset()
802
+ self._set_order_of_magnitude()
803
+ self._set_format()
804
+
805
+ def _compute_offset(self):
806
+ locs = self._locs
807
+ # Restrict to visible ticks.
808
+ vmin, vmax = sorted(self.axis.get_view_interval())
809
+ locs = np.asarray(locs)
810
+ locs = locs[(vmin <= locs) & (locs <= vmax)]
811
+ if not len(locs):
812
+ self.offset = 0
813
+ return
814
+ lmin, lmax = locs.min(), locs.max()
815
+ # Only use offset if there are at least two ticks and every tick has
816
+ # the same sign.
817
+ if lmin == lmax or lmin <= 0 <= lmax:
818
+ self.offset = 0
819
+ return
820
+ # min, max comparing absolute values (we want division to round towards
821
+ # zero so we work on absolute values).
822
+ abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))])
823
+ sign = math.copysign(1, lmin)
824
+ # What is the smallest power of ten such that abs_min and abs_max are
825
+ # equal up to that precision?
826
+ # Note: Internally using oom instead of 10 ** oom avoids some numerical
827
+ # accuracy issues.
828
+ oom_max = np.ceil(math.log10(abs_max))
829
+ oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
830
+ if abs_min // 10 ** oom != abs_max // 10 ** oom)
831
+ if (abs_max - abs_min) / 10 ** oom <= 1e-2:
832
+ # Handle the case of straddling a multiple of a large power of ten
833
+ # (relative to the span).
834
+ # What is the smallest power of ten such that abs_min and abs_max
835
+ # are no more than 1 apart at that precision?
836
+ oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
837
+ if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)
838
+ # Only use offset if it saves at least _offset_threshold digits.
839
+ n = self._offset_threshold - 1
840
+ self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom
841
+ if abs_max // 10 ** oom >= 10**n
842
+ else 0)
843
+
844
+ def _set_order_of_magnitude(self):
845
+ # if scientific notation is to be used, find the appropriate exponent
846
+ # if using a numerical offset, find the exponent after applying the
847
+ # offset. When lower power limit = upper <> 0, use provided exponent.
848
+ if not self._scientific:
849
+ self._orderOfMagnitude = 0
850
+ return
851
+ if self._powerlimits[0] == self._powerlimits[1] != 0:
852
+ # fixed scaling when lower power limit = upper <> 0.
853
+ self._orderOfMagnitude = self._powerlimits[0]
854
+ return
855
+ # restrict to visible ticks
856
+ vmin, vmax = sorted(self.axis.get_view_interval())
857
+ locs = np.asarray(self._locs)
858
+ locs = locs[(vmin <= locs) & (locs <= vmax)]
859
+ locs = np.abs(locs)
860
+ if not len(locs):
861
+ self._orderOfMagnitude = 0
862
+ return
863
+ if self.offset:
864
+ oom = math.floor(math.log10(vmax - vmin))
865
+ else:
866
+ val = locs.max()
867
+ if val == 0:
868
+ oom = 0
869
+ else:
870
+ oom = math.floor(math.log10(val))
871
+ if oom <= self._powerlimits[0]:
872
+ self._orderOfMagnitude = oom
873
+ elif oom >= self._powerlimits[1]:
874
+ self._orderOfMagnitude = oom
875
+ else:
876
+ self._orderOfMagnitude = 0
877
+
878
+ def _set_format(self):
879
+ # set the format string to format all the ticklabels
880
+ if len(self._locs) < 2:
881
+ # Temporarily augment the locations with the axis end points.
882
+ _locs = [*self._locs, *self.axis.get_view_interval()]
883
+ else:
884
+ _locs = self._locs
885
+ locs = (np.asarray(_locs) - self.offset) / 10. ** self._orderOfMagnitude
886
+ loc_range = np.ptp(locs)
887
+ # Curvilinear coordinates can yield two identical points.
888
+ if loc_range == 0:
889
+ loc_range = np.max(np.abs(locs))
890
+ # Both points might be zero.
891
+ if loc_range == 0:
892
+ loc_range = 1
893
+ if len(self._locs) < 2:
894
+ # We needed the end points only for the loc_range calculation.
895
+ locs = locs[:-2]
896
+ loc_range_oom = int(math.floor(math.log10(loc_range)))
897
+ # first estimate:
898
+ sigfigs = max(0, 3 - loc_range_oom)
899
+ # refined estimate:
900
+ thresh = 1e-3 * 10 ** loc_range_oom
901
+ while sigfigs >= 0:
902
+ if np.abs(locs - np.round(locs, decimals=sigfigs)).max() < thresh:
903
+ sigfigs -= 1
904
+ else:
905
+ break
906
+ sigfigs += 1
907
+ self._format = f'%1.{sigfigs}f'
908
+ if self._usetex or self._useMathText:
909
+ self._format = r'$\mathdefault{%s}$' % self._format
910
+
911
+
912
+ class LogFormatter(Formatter):
913
+ """
914
+ Base class for formatting ticks on a log or symlog scale.
915
+
916
+ It may be instantiated directly, or subclassed.
917
+
918
+ Parameters
919
+ ----------
920
+ base : float, default: 10.
921
+ Base of the logarithm used in all calculations.
922
+
923
+ labelOnlyBase : bool, default: False
924
+ If True, label ticks only at integer powers of base.
925
+ This is normally True for major ticks and False for minor ticks.
926
+
927
+ minor_thresholds : (subset, all), default: (1, 0.4)
928
+ If labelOnlyBase is False, these two numbers control
929
+ the labeling of ticks that are not at integer powers of
930
+ base; normally these are the minor ticks.
931
+
932
+ The first number (*subset*) is the largest number of major ticks for
933
+ which minor ticks are labeled; e.g., the default, 1, means that minor
934
+ ticks are labeled as long as there is no more than 1 major tick. (It
935
+ is assumed that major ticks are at integer powers of *base*.)
936
+
937
+ The second number (*all*) is a threshold, in log-units of the axis
938
+ limit range, over which only a subset of the minor ticks are labeled,
939
+ so as to avoid crowding; e.g., with the default value (0.4) and the
940
+ usual ``base=10``, all minor ticks are shown only if the axis limit
941
+ range spans less than 0.4 decades.
942
+
943
+ linthresh : None or float, default: None
944
+ If a symmetric log scale is in use, its ``linthresh``
945
+ parameter must be supplied here.
946
+
947
+ Notes
948
+ -----
949
+ The `set_locs` method must be called to enable the subsetting
950
+ logic controlled by the ``minor_thresholds`` parameter.
951
+
952
+ In some cases such as the colorbar, there is no distinction between
953
+ major and minor ticks; the tick locations might be set manually,
954
+ or by a locator that puts ticks at integer powers of base and
955
+ at intermediate locations. For this situation, disable the
956
+ minor_thresholds logic by using ``minor_thresholds=(np.inf, np.inf)``,
957
+ so that all ticks will be labeled.
958
+
959
+ To disable labeling of minor ticks when 'labelOnlyBase' is False,
960
+ use ``minor_thresholds=(0, 0)``. This is the default for the
961
+ "classic" style.
962
+
963
+ Examples
964
+ --------
965
+ To label a subset of minor ticks when there are up to 2 major ticks,
966
+ and all of the ticks when zoomed in to 0.5 decades or less, use
967
+ ``minor_thresholds=(2, 0.5)``.
968
+ """
969
+
970
+ def __init__(self, base=10.0, labelOnlyBase=False,
971
+ minor_thresholds=None,
972
+ linthresh=None):
973
+
974
+ self.set_base(base)
975
+ self.set_label_minor(labelOnlyBase)
976
+ if minor_thresholds is None:
977
+ if mpl.rcParams['_internal.classic_mode']:
978
+ minor_thresholds = (0, 0)
979
+ else:
980
+ minor_thresholds = (1, 0.4)
981
+ self.minor_thresholds = minor_thresholds
982
+ self._sublabels = None
983
+ self._linthresh = linthresh
984
+
985
+ def set_base(self, base):
986
+ """
987
+ Change the *base* for labeling.
988
+
989
+ .. warning::
990
+ Should always match the base used for :class:`LogLocator`
991
+ """
992
+ self._base = float(base)
993
+
994
+ def set_label_minor(self, labelOnlyBase):
995
+ """
996
+ Switch minor tick labeling on or off.
997
+
998
+ Parameters
999
+ ----------
1000
+ labelOnlyBase : bool
1001
+ If True, label ticks only at integer powers of base.
1002
+ """
1003
+ self.labelOnlyBase = labelOnlyBase
1004
+
1005
+ def set_locs(self, locs=None):
1006
+ """
1007
+ Use axis view limits to control which ticks are labeled.
1008
+
1009
+ The *locs* parameter is ignored in the present algorithm.
1010
+ """
1011
+ if np.isinf(self.minor_thresholds[0]):
1012
+ self._sublabels = None
1013
+ return
1014
+
1015
+ # Handle symlog case:
1016
+ linthresh = self._linthresh
1017
+ if linthresh is None:
1018
+ try:
1019
+ linthresh = self.axis.get_transform().linthresh
1020
+ except AttributeError:
1021
+ pass
1022
+
1023
+ vmin, vmax = self.axis.get_view_interval()
1024
+ if vmin > vmax:
1025
+ vmin, vmax = vmax, vmin
1026
+
1027
+ if linthresh is None and vmin <= 0:
1028
+ # It's probably a colorbar with
1029
+ # a format kwarg setting a LogFormatter in the manner
1030
+ # that worked with 1.5.x, but that doesn't work now.
1031
+ self._sublabels = {1} # label powers of base
1032
+ return
1033
+
1034
+ b = self._base
1035
+
1036
+ if linthresh is not None: # symlog
1037
+ # Only count ticks and decades in the logarithmic part of the axis.
1038
+ numdec = numticks = 0
1039
+ if vmin < -linthresh:
1040
+ rhs = min(vmax, -linthresh)
1041
+ numticks += (
1042
+ math.floor(math.log(abs(rhs), b))
1043
+ - math.floor(math.nextafter(math.log(abs(vmin), b), -math.inf)))
1044
+ numdec += math.log(vmin / rhs, b)
1045
+ if vmax > linthresh:
1046
+ lhs = max(vmin, linthresh)
1047
+ numticks += (
1048
+ math.floor(math.log(vmax, b))
1049
+ - math.floor(math.nextafter(math.log(lhs, b), -math.inf)))
1050
+ numdec += math.log(vmax / lhs, b)
1051
+ else:
1052
+ lmin = math.log(vmin, b)
1053
+ lmax = math.log(vmax, b)
1054
+ # The nextafter call handles the case where vmin is exactly at a
1055
+ # decade (e.g. there's one major tick between 1 and 5).
1056
+ numticks = (math.floor(lmax)
1057
+ - math.floor(math.nextafter(lmin, -math.inf)))
1058
+ numdec = abs(lmax - lmin)
1059
+
1060
+ if numticks > self.minor_thresholds[0]:
1061
+ # Label only bases
1062
+ self._sublabels = {1}
1063
+ elif numdec > self.minor_thresholds[1]:
1064
+ # Add labels between bases at log-spaced coefficients;
1065
+ # include base powers in case the locations include
1066
+ # "major" and "minor" points, as in colorbar.
1067
+ c = np.geomspace(1, b, int(b)//2 + 1)
1068
+ self._sublabels = set(np.round(c))
1069
+ # For base 10, this yields (1, 2, 3, 4, 6, 10).
1070
+ else:
1071
+ # Label all integer multiples of base**n.
1072
+ self._sublabels = set(np.arange(1, b + 1))
1073
+
1074
+ def _num_to_string(self, x, vmin, vmax):
1075
+ return self._pprint_val(x, vmax - vmin) if 1 <= x <= 10000 else f"{x:1.0e}"
1076
+
1077
+ def __call__(self, x, pos=None):
1078
+ # docstring inherited
1079
+ if x == 0.0: # Symlog
1080
+ return '0'
1081
+
1082
+ x = abs(x)
1083
+ b = self._base
1084
+ # only label the decades
1085
+ fx = math.log(x) / math.log(b)
1086
+ is_x_decade = _is_close_to_int(fx)
1087
+ exponent = round(fx) if is_x_decade else np.floor(fx)
1088
+ coeff = round(b ** (fx - exponent))
1089
+
1090
+ if self.labelOnlyBase and not is_x_decade:
1091
+ return ''
1092
+ if self._sublabels is not None and coeff not in self._sublabels:
1093
+ return ''
1094
+
1095
+ vmin, vmax = self.axis.get_view_interval()
1096
+ vmin, vmax = mtransforms._nonsingular(vmin, vmax, expander=0.05)
1097
+ s = self._num_to_string(x, vmin, vmax)
1098
+ return self.fix_minus(s)
1099
+
1100
+ def format_data(self, value):
1101
+ with cbook._setattr_cm(self, labelOnlyBase=False):
1102
+ return cbook.strip_math(self.__call__(value))
1103
+
1104
+ def format_data_short(self, value):
1105
+ # docstring inherited
1106
+ return ('%-12g' % value).rstrip()
1107
+
1108
+ def _pprint_val(self, x, d):
1109
+ # If the number is not too big and it's an int, format it as an int.
1110
+ if abs(x) < 1e4 and x == int(x):
1111
+ return '%d' % x
1112
+ fmt = ('%1.3e' if d < 1e-2 else
1113
+ '%1.3f' if d <= 1 else
1114
+ '%1.2f' if d <= 10 else
1115
+ '%1.1f' if d <= 1e5 else
1116
+ '%1.1e')
1117
+ s = fmt % x
1118
+ tup = s.split('e')
1119
+ if len(tup) == 2:
1120
+ mantissa = tup[0].rstrip('0').rstrip('.')
1121
+ exponent = int(tup[1])
1122
+ if exponent:
1123
+ s = '%se%d' % (mantissa, exponent)
1124
+ else:
1125
+ s = mantissa
1126
+ else:
1127
+ s = s.rstrip('0').rstrip('.')
1128
+ return s
1129
+
1130
+
1131
+ class LogFormatterExponent(LogFormatter):
1132
+ """
1133
+ Format values for log axis using ``exponent = log_base(value)``.
1134
+ """
1135
+
1136
+ def _num_to_string(self, x, vmin, vmax):
1137
+ fx = math.log(x) / math.log(self._base)
1138
+ if 1 <= abs(fx) <= 10000:
1139
+ fd = math.log(vmax - vmin) / math.log(self._base)
1140
+ s = self._pprint_val(fx, fd)
1141
+ else:
1142
+ s = f"{fx:1.0g}"
1143
+ return s
1144
+
1145
+
1146
+ class LogFormatterMathtext(LogFormatter):
1147
+ """
1148
+ Format values for log axis using ``exponent = log_base(value)``.
1149
+ """
1150
+
1151
+ def _non_decade_format(self, sign_string, base, fx, usetex):
1152
+ """Return string for non-decade locations."""
1153
+ return r'$\mathdefault{%s%s^{%.2f}}$' % (sign_string, base, fx)
1154
+
1155
+ def __call__(self, x, pos=None):
1156
+ # docstring inherited
1157
+ if x == 0: # Symlog
1158
+ return r'$\mathdefault{0}$'
1159
+
1160
+ sign_string = '-' if x < 0 else ''
1161
+ x = abs(x)
1162
+ b = self._base
1163
+
1164
+ # only label the decades
1165
+ fx = math.log(x) / math.log(b)
1166
+ is_x_decade = _is_close_to_int(fx)
1167
+ exponent = round(fx) if is_x_decade else np.floor(fx)
1168
+ coeff = round(b ** (fx - exponent))
1169
+
1170
+ if self.labelOnlyBase and not is_x_decade:
1171
+ return ''
1172
+ if self._sublabels is not None and coeff not in self._sublabels:
1173
+ return ''
1174
+
1175
+ if is_x_decade:
1176
+ fx = round(fx)
1177
+
1178
+ # use string formatting of the base if it is not an integer
1179
+ if b % 1 == 0.0:
1180
+ base = '%d' % b
1181
+ else:
1182
+ base = '%s' % b
1183
+
1184
+ if abs(fx) < mpl.rcParams['axes.formatter.min_exponent']:
1185
+ return r'$\mathdefault{%s%g}$' % (sign_string, x)
1186
+ elif not is_x_decade:
1187
+ usetex = mpl.rcParams['text.usetex']
1188
+ return self._non_decade_format(sign_string, base, fx, usetex)
1189
+ else:
1190
+ return r'$\mathdefault{%s%s^{%d}}$' % (sign_string, base, fx)
1191
+
1192
+
1193
+ class LogFormatterSciNotation(LogFormatterMathtext):
1194
+ """
1195
+ Format values following scientific notation in a logarithmic axis.
1196
+ """
1197
+
1198
+ def _non_decade_format(self, sign_string, base, fx, usetex):
1199
+ """Return string for non-decade locations."""
1200
+ b = float(base)
1201
+ exponent = math.floor(fx)
1202
+ coeff = b ** (fx - exponent)
1203
+ if _is_close_to_int(coeff):
1204
+ coeff = round(coeff)
1205
+ return r'$\mathdefault{%s%g\times%s^{%d}}$' \
1206
+ % (sign_string, coeff, base, exponent)
1207
+
1208
+
1209
+ class LogitFormatter(Formatter):
1210
+ """
1211
+ Probability formatter (using Math text).
1212
+ """
1213
+
1214
+ def __init__(
1215
+ self,
1216
+ *,
1217
+ use_overline=False,
1218
+ one_half=r"\frac{1}{2}",
1219
+ minor=False,
1220
+ minor_threshold=25,
1221
+ minor_number=6,
1222
+ ):
1223
+ r"""
1224
+ Parameters
1225
+ ----------
1226
+ use_overline : bool, default: False
1227
+ If x > 1/2, with x = 1 - v, indicate if x should be displayed as
1228
+ $\overline{v}$. The default is to display $1 - v$.
1229
+
1230
+ one_half : str, default: r"\\frac{1}{2}"
1231
+ The string used to represent 1/2.
1232
+
1233
+ minor : bool, default: False
1234
+ Indicate if the formatter is formatting minor ticks or not.
1235
+ Basically minor ticks are not labelled, except when only few ticks
1236
+ are provided, ticks with most space with neighbor ticks are
1237
+ labelled. See other parameters to change the default behavior.
1238
+
1239
+ minor_threshold : int, default: 25
1240
+ Maximum number of locs for labelling some minor ticks. This
1241
+ parameter have no effect if minor is False.
1242
+
1243
+ minor_number : int, default: 6
1244
+ Number of ticks which are labelled when the number of ticks is
1245
+ below the threshold.
1246
+ """
1247
+ self._use_overline = use_overline
1248
+ self._one_half = one_half
1249
+ self._minor = minor
1250
+ self._labelled = set()
1251
+ self._minor_threshold = minor_threshold
1252
+ self._minor_number = minor_number
1253
+
1254
+ def use_overline(self, use_overline):
1255
+ r"""
1256
+ Switch display mode with overline for labelling p>1/2.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ use_overline : bool
1261
+ If x > 1/2, with x = 1 - v, indicate if x should be displayed as
1262
+ $\overline{v}$. The default is to display $1 - v$.
1263
+ """
1264
+ self._use_overline = use_overline
1265
+
1266
+ def set_one_half(self, one_half):
1267
+ r"""
1268
+ Set the way one half is displayed.
1269
+
1270
+ one_half : str
1271
+ The string used to represent 1/2.
1272
+ """
1273
+ self._one_half = one_half
1274
+
1275
+ def set_minor_threshold(self, minor_threshold):
1276
+ """
1277
+ Set the threshold for labelling minors ticks.
1278
+
1279
+ Parameters
1280
+ ----------
1281
+ minor_threshold : int
1282
+ Maximum number of locations for labelling some minor ticks. This
1283
+ parameter have no effect if minor is False.
1284
+ """
1285
+ self._minor_threshold = minor_threshold
1286
+
1287
+ def set_minor_number(self, minor_number):
1288
+ """
1289
+ Set the number of minor ticks to label when some minor ticks are
1290
+ labelled.
1291
+
1292
+ Parameters
1293
+ ----------
1294
+ minor_number : int
1295
+ Number of ticks which are labelled when the number of ticks is
1296
+ below the threshold.
1297
+ """
1298
+ self._minor_number = minor_number
1299
+
1300
+ def set_locs(self, locs):
1301
+ self._locs = np.array(locs)
1302
+ self._labelled.clear()
1303
+
1304
+ if not self._minor:
1305
+ return None
1306
+ if all(
1307
+ _is_decade(x, rtol=1e-7)
1308
+ or _is_decade(1 - x, rtol=1e-7)
1309
+ or (_is_close_to_int(2 * x) and
1310
+ int(np.round(2 * x)) == 1)
1311
+ for x in locs
1312
+ ):
1313
+ # minor ticks are subsample from ideal, so no label
1314
+ return None
1315
+ if len(locs) < self._minor_threshold:
1316
+ if len(locs) < self._minor_number:
1317
+ self._labelled.update(locs)
1318
+ else:
1319
+ # we do not have a lot of minor ticks, so only few decades are
1320
+ # displayed, then we choose some (spaced) minor ticks to label.
1321
+ # Only minor ticks are known, we assume it is sufficient to
1322
+ # choice which ticks are displayed.
1323
+ # For each ticks we compute the distance between the ticks and
1324
+ # the previous, and between the ticks and the next one. Ticks
1325
+ # with smallest minimum are chosen. As tiebreak, the ticks
1326
+ # with smallest sum is chosen.
1327
+ diff = np.diff(-np.log(1 / self._locs - 1))
1328
+ space_pessimistic = np.minimum(
1329
+ np.concatenate(((np.inf,), diff)),
1330
+ np.concatenate((diff, (np.inf,))),
1331
+ )
1332
+ space_sum = (
1333
+ np.concatenate(((0,), diff))
1334
+ + np.concatenate((diff, (0,)))
1335
+ )
1336
+ good_minor = sorted(
1337
+ range(len(self._locs)),
1338
+ key=lambda i: (space_pessimistic[i], space_sum[i]),
1339
+ )[-self._minor_number:]
1340
+ self._labelled.update(locs[i] for i in good_minor)
1341
+
1342
+ def _format_value(self, x, locs, sci_notation=True):
1343
+ if sci_notation:
1344
+ exponent = math.floor(np.log10(x))
1345
+ min_precision = 0
1346
+ else:
1347
+ exponent = 0
1348
+ min_precision = 1
1349
+ value = x * 10 ** (-exponent)
1350
+ if len(locs) < 2:
1351
+ precision = min_precision
1352
+ else:
1353
+ diff = np.sort(np.abs(locs - x))[1]
1354
+ precision = -np.log10(diff) + exponent
1355
+ precision = (
1356
+ int(np.round(precision))
1357
+ if _is_close_to_int(precision)
1358
+ else math.ceil(precision)
1359
+ )
1360
+ if precision < min_precision:
1361
+ precision = min_precision
1362
+ mantissa = r"%.*f" % (precision, value)
1363
+ if not sci_notation:
1364
+ return mantissa
1365
+ s = r"%s\cdot10^{%d}" % (mantissa, exponent)
1366
+ return s
1367
+
1368
+ def _one_minus(self, s):
1369
+ if self._use_overline:
1370
+ return r"\overline{%s}" % s
1371
+ else:
1372
+ return f"1-{s}"
1373
+
1374
+ def __call__(self, x, pos=None):
1375
+ if self._minor and x not in self._labelled:
1376
+ return ""
1377
+ if x <= 0 or x >= 1:
1378
+ return ""
1379
+ if _is_close_to_int(2 * x) and round(2 * x) == 1:
1380
+ s = self._one_half
1381
+ elif x < 0.5 and _is_decade(x, rtol=1e-7):
1382
+ exponent = round(math.log10(x))
1383
+ s = "10^{%d}" % exponent
1384
+ elif x > 0.5 and _is_decade(1 - x, rtol=1e-7):
1385
+ exponent = round(math.log10(1 - x))
1386
+ s = self._one_minus("10^{%d}" % exponent)
1387
+ elif x < 0.1:
1388
+ s = self._format_value(x, self._locs)
1389
+ elif x > 0.9:
1390
+ s = self._one_minus(self._format_value(1-x, 1-self._locs))
1391
+ else:
1392
+ s = self._format_value(x, self._locs, sci_notation=False)
1393
+ return r"$\mathdefault{%s}$" % s
1394
+
1395
+ def format_data_short(self, value):
1396
+ # docstring inherited
1397
+ # Thresholds chosen to use scientific notation iff exponent <= -2.
1398
+ if value < 0.1:
1399
+ return f"{value:e}"
1400
+ if value < 0.9:
1401
+ return f"{value:f}"
1402
+ return f"1-{1 - value:e}"
1403
+
1404
+
1405
+ class EngFormatter(ScalarFormatter):
1406
+ """
1407
+ Format axis values using engineering prefixes to represent powers
1408
+ of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7.
1409
+ """
1410
+
1411
+ # The SI engineering prefixes
1412
+ ENG_PREFIXES = {
1413
+ -30: "q",
1414
+ -27: "r",
1415
+ -24: "y",
1416
+ -21: "z",
1417
+ -18: "a",
1418
+ -15: "f",
1419
+ -12: "p",
1420
+ -9: "n",
1421
+ -6: "\N{MICRO SIGN}",
1422
+ -3: "m",
1423
+ 0: "",
1424
+ 3: "k",
1425
+ 6: "M",
1426
+ 9: "G",
1427
+ 12: "T",
1428
+ 15: "P",
1429
+ 18: "E",
1430
+ 21: "Z",
1431
+ 24: "Y",
1432
+ 27: "R",
1433
+ 30: "Q"
1434
+ }
1435
+
1436
+ def __init__(self, unit="", places=None, sep=" ", *, usetex=None,
1437
+ useMathText=None, useOffset=False):
1438
+ r"""
1439
+ Parameters
1440
+ ----------
1441
+ unit : str, default: ""
1442
+ Unit symbol to use, suitable for use with single-letter
1443
+ representations of powers of 1000. For example, 'Hz' or 'm'.
1444
+
1445
+ places : int, default: None
1446
+ Precision with which to display the number, specified in
1447
+ digits after the decimal point (there will be between one
1448
+ and three digits before the decimal point). If it is None,
1449
+ the formatting falls back to the floating point format '%g',
1450
+ which displays up to 6 *significant* digits, i.e. the equivalent
1451
+ value for *places* varies between 0 and 5 (inclusive).
1452
+
1453
+ sep : str, default: " "
1454
+ Separator used between the value and the prefix/unit. For
1455
+ example, one get '3.14 mV' if ``sep`` is " " (default) and
1456
+ '3.14mV' if ``sep`` is "". Besides the default behavior, some
1457
+ other useful options may be:
1458
+
1459
+ * ``sep=""`` to append directly the prefix/unit to the value;
1460
+ * ``sep="\N{THIN SPACE}"`` (``U+2009``);
1461
+ * ``sep="\N{NARROW NO-BREAK SPACE}"`` (``U+202F``);
1462
+ * ``sep="\N{NO-BREAK SPACE}"`` (``U+00A0``).
1463
+
1464
+ usetex : bool, default: :rc:`text.usetex`
1465
+ To enable/disable the use of TeX's math mode for rendering the
1466
+ numbers in the formatter.
1467
+
1468
+ useMathText : bool, default: :rc:`axes.formatter.use_mathtext`
1469
+ To enable/disable the use mathtext for rendering the numbers in
1470
+ the formatter.
1471
+ useOffset : bool or float, default: False
1472
+ Whether to use offset notation with :math:`10^{3*N}` based prefixes.
1473
+ This features allows showing an offset with standard SI order of
1474
+ magnitude prefix near the axis. Offset is computed similarly to
1475
+ how `ScalarFormatter` computes it internally, but here you are
1476
+ guaranteed to get an offset which will make the tick labels exceed
1477
+ 3 digits. See also `.set_useOffset`.
1478
+
1479
+ .. versionadded:: 3.10
1480
+ """
1481
+ self.unit = unit
1482
+ self.places = places
1483
+ self.sep = sep
1484
+ super().__init__(
1485
+ useOffset=useOffset,
1486
+ useMathText=useMathText,
1487
+ useLocale=False,
1488
+ usetex=usetex,
1489
+ )
1490
+
1491
+ def __call__(self, x, pos=None):
1492
+ """
1493
+ Return the format for tick value *x* at position *pos*.
1494
+
1495
+ If there is no currently offset in the data, it returns the best
1496
+ engineering formatting that fits the given argument, independently.
1497
+ """
1498
+ if len(self._locs) == 0 or self.offset == 0:
1499
+ return self.fix_minus(self.format_data(x))
1500
+ else:
1501
+ xp = (x - self.offset) / (10. ** self._orderOfMagnitude)
1502
+ if abs(xp) < 1e-8:
1503
+ xp = 0
1504
+ return self._format_maybe_minus_and_locale(self._format, xp)
1505
+
1506
+ def set_locs(self, locs):
1507
+ # docstring inherited
1508
+ self._locs = locs
1509
+ if len(self._locs) > 0:
1510
+ vmin, vmax = sorted(self.axis.get_view_interval())
1511
+ if self._useOffset:
1512
+ self._compute_offset()
1513
+ if self.offset != 0:
1514
+ # We don't want to use the offset computed by
1515
+ # self._compute_offset because it rounds the offset unaware
1516
+ # of our engineering prefixes preference, and this can
1517
+ # cause ticks with 4+ digits to appear. These ticks are
1518
+ # slightly less readable, so if offset is justified
1519
+ # (decided by self._compute_offset) we set it to better
1520
+ # value:
1521
+ self.offset = round((vmin + vmax)/2, 3)
1522
+ # Use log1000 to use engineers' oom standards
1523
+ self._orderOfMagnitude = math.floor(math.log(vmax - vmin, 1000))*3
1524
+ self._set_format()
1525
+
1526
+ # Simplify a bit ScalarFormatter.get_offset: We always want to use
1527
+ # self.format_data. Also we want to return a non-empty string only if there
1528
+ # is an offset, no matter what is self._orderOfMagnitude. If there _is_ an
1529
+ # offset, self._orderOfMagnitude is consulted. This behavior is verified
1530
+ # in `test_ticker.py`.
1531
+ def get_offset(self):
1532
+ # docstring inherited
1533
+ if len(self._locs) == 0:
1534
+ return ''
1535
+ if self.offset:
1536
+ offsetStr = ''
1537
+ if self.offset:
1538
+ offsetStr = self.format_data(self.offset)
1539
+ if self.offset > 0:
1540
+ offsetStr = '+' + offsetStr
1541
+ sciNotStr = self.format_data(10 ** self._orderOfMagnitude)
1542
+ if self._useMathText or self._usetex:
1543
+ if sciNotStr != '':
1544
+ sciNotStr = r'\times%s' % sciNotStr
1545
+ s = f'${sciNotStr}{offsetStr}$'
1546
+ else:
1547
+ s = sciNotStr + offsetStr
1548
+ return self.fix_minus(s)
1549
+ return ''
1550
+
1551
+ def format_eng(self, num):
1552
+ """Alias to EngFormatter.format_data"""
1553
+ return self.format_data(num)
1554
+
1555
+ def format_data(self, value):
1556
+ """
1557
+ Format a number in engineering notation, appending a letter
1558
+ representing the power of 1000 of the original number.
1559
+ Some examples:
1560
+
1561
+ >>> format_data(0) # for self.places = 0
1562
+ '0'
1563
+
1564
+ >>> format_data(1000000) # for self.places = 1
1565
+ '1.0 M'
1566
+
1567
+ >>> format_data(-1e-6) # for self.places = 2
1568
+ '-1.00 \N{MICRO SIGN}'
1569
+ """
1570
+ sign = 1
1571
+ fmt = "g" if self.places is None else f".{self.places:d}f"
1572
+
1573
+ if value < 0:
1574
+ sign = -1
1575
+ value = -value
1576
+
1577
+ if value != 0:
1578
+ pow10 = int(math.floor(math.log10(value) / 3) * 3)
1579
+ else:
1580
+ pow10 = 0
1581
+ # Force value to zero, to avoid inconsistencies like
1582
+ # format_eng(-0) = "0" and format_eng(0.0) = "0"
1583
+ # but format_eng(-0.0) = "-0.0"
1584
+ value = 0.0
1585
+
1586
+ pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES))
1587
+
1588
+ mant = sign * value / (10.0 ** pow10)
1589
+ # Taking care of the cases like 999.9..., which may be rounded to 1000
1590
+ # instead of 1 k. Beware of the corner case of values that are beyond
1591
+ # the range of SI prefixes (i.e. > 'Y').
1592
+ if (abs(float(format(mant, fmt))) >= 1000
1593
+ and pow10 < max(self.ENG_PREFIXES)):
1594
+ mant /= 1000
1595
+ pow10 += 3
1596
+
1597
+ unit_prefix = self.ENG_PREFIXES[int(pow10)]
1598
+ if self.unit or unit_prefix:
1599
+ suffix = f"{self.sep}{unit_prefix}{self.unit}"
1600
+ else:
1601
+ suffix = ""
1602
+ if self._usetex or self._useMathText:
1603
+ return f"${mant:{fmt}}${suffix}"
1604
+ else:
1605
+ return f"{mant:{fmt}}{suffix}"
1606
+
1607
+
1608
+ class PercentFormatter(Formatter):
1609
+ """
1610
+ Format numbers as a percentage.
1611
+
1612
+ Parameters
1613
+ ----------
1614
+ xmax : float
1615
+ Determines how the number is converted into a percentage.
1616
+ *xmax* is the data value that corresponds to 100%.
1617
+ Percentages are computed as ``x / xmax * 100``. So if the data is
1618
+ already scaled to be percentages, *xmax* will be 100. Another common
1619
+ situation is where *xmax* is 1.0.
1620
+
1621
+ decimals : None or int
1622
+ The number of decimal places to place after the point.
1623
+ If *None* (the default), the number will be computed automatically.
1624
+
1625
+ symbol : str or None
1626
+ A string that will be appended to the label. It may be
1627
+ *None* or empty to indicate that no symbol should be used. LaTeX
1628
+ special characters are escaped in *symbol* whenever latex mode is
1629
+ enabled, unless *is_latex* is *True*.
1630
+
1631
+ is_latex : bool
1632
+ If *False*, reserved LaTeX characters in *symbol* will be escaped.
1633
+ """
1634
+ def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False):
1635
+ self.xmax = xmax + 0.0
1636
+ self.decimals = decimals
1637
+ self._symbol = symbol
1638
+ self._is_latex = is_latex
1639
+
1640
+ def __call__(self, x, pos=None):
1641
+ """Format the tick as a percentage with the appropriate scaling."""
1642
+ ax_min, ax_max = self.axis.get_view_interval()
1643
+ display_range = abs(ax_max - ax_min)
1644
+ return self.fix_minus(self.format_pct(x, display_range))
1645
+
1646
+ def format_pct(self, x, display_range):
1647
+ """
1648
+ Format the number as a percentage number with the correct
1649
+ number of decimals and adds the percent symbol, if any.
1650
+
1651
+ If ``self.decimals`` is `None`, the number of digits after the
1652
+ decimal point is set based on the *display_range* of the axis
1653
+ as follows:
1654
+
1655
+ ============= ======== =======================
1656
+ display_range decimals sample
1657
+ ============= ======== =======================
1658
+ >50 0 ``x = 34.5`` => 35%
1659
+ >5 1 ``x = 34.5`` => 34.5%
1660
+ >0.5 2 ``x = 34.5`` => 34.50%
1661
+ ... ... ...
1662
+ ============= ======== =======================
1663
+
1664
+ This method will not be very good for tiny axis ranges or
1665
+ extremely large ones. It assumes that the values on the chart
1666
+ are percentages displayed on a reasonable scale.
1667
+ """
1668
+ x = self.convert_to_pct(x)
1669
+ if self.decimals is None:
1670
+ # conversion works because display_range is a difference
1671
+ scaled_range = self.convert_to_pct(display_range)
1672
+ if scaled_range <= 0:
1673
+ decimals = 0
1674
+ else:
1675
+ # Luckily Python's built-in ceil rounds to +inf, not away from
1676
+ # zero. This is very important since the equation for decimals
1677
+ # starts out as `scaled_range > 0.5 * 10**(2 - decimals)`
1678
+ # and ends up with `decimals > 2 - log10(2 * scaled_range)`.
1679
+ decimals = math.ceil(2.0 - math.log10(2.0 * scaled_range))
1680
+ if decimals > 5:
1681
+ decimals = 5
1682
+ elif decimals < 0:
1683
+ decimals = 0
1684
+ else:
1685
+ decimals = self.decimals
1686
+ s = f'{x:0.{int(decimals)}f}'
1687
+
1688
+ return s + self.symbol
1689
+
1690
+ def convert_to_pct(self, x):
1691
+ return 100.0 * (x / self.xmax)
1692
+
1693
+ @property
1694
+ def symbol(self):
1695
+ r"""
1696
+ The configured percent symbol as a string.
1697
+
1698
+ If LaTeX is enabled via :rc:`text.usetex`, the special characters
1699
+ ``{'#', '$', '%', '&', '~', '_', '^', '\', '{', '}'}`` are
1700
+ automatically escaped in the string.
1701
+ """
1702
+ symbol = self._symbol
1703
+ if not symbol:
1704
+ symbol = ''
1705
+ elif not self._is_latex and mpl.rcParams['text.usetex']:
1706
+ # Source: http://www.personal.ceu.hu/tex/specchar.htm
1707
+ # Backslash must be first for this to work correctly since
1708
+ # it keeps getting added in
1709
+ for spec in r'\#$%&~_^{}':
1710
+ symbol = symbol.replace(spec, '\\' + spec)
1711
+ return symbol
1712
+
1713
+ @symbol.setter
1714
+ def symbol(self, symbol):
1715
+ self._symbol = symbol
1716
+
1717
+
1718
+ class Locator(TickHelper):
1719
+ """
1720
+ Determine tick locations.
1721
+
1722
+ Note that the same locator should not be used across multiple
1723
+ `~matplotlib.axis.Axis` because the locator stores references to the Axis
1724
+ data and view limits.
1725
+ """
1726
+
1727
+ # Some automatic tick locators can generate so many ticks they
1728
+ # kill the machine when you try and render them.
1729
+ # This parameter is set to cause locators to raise an error if too
1730
+ # many ticks are generated.
1731
+ MAXTICKS = 1000
1732
+
1733
+ def tick_values(self, vmin, vmax):
1734
+ """
1735
+ Return the values of the located ticks given **vmin** and **vmax**.
1736
+
1737
+ .. note::
1738
+ To get tick locations with the vmin and vmax values defined
1739
+ automatically for the associated ``axis`` simply call
1740
+ the Locator instance::
1741
+
1742
+ >>> print(type(loc))
1743
+ <type 'Locator'>
1744
+ >>> print(loc())
1745
+ [1, 2, 3, 4]
1746
+
1747
+ """
1748
+ raise NotImplementedError('Derived must override')
1749
+
1750
+ def set_params(self, **kwargs):
1751
+ """
1752
+ Do nothing, and raise a warning. Any locator class not supporting the
1753
+ set_params() function will call this.
1754
+ """
1755
+ _api.warn_external(
1756
+ "'set_params()' not defined for locator of type " +
1757
+ str(type(self)))
1758
+
1759
+ def __call__(self):
1760
+ """Return the locations of the ticks."""
1761
+ # note: some locators return data limits, other return view limits,
1762
+ # hence there is no *one* interface to call self.tick_values.
1763
+ raise NotImplementedError('Derived must override')
1764
+
1765
+ def raise_if_exceeds(self, locs):
1766
+ """
1767
+ Log at WARNING level if *locs* is longer than `Locator.MAXTICKS`.
1768
+
1769
+ This is intended to be called immediately before returning *locs* from
1770
+ ``__call__`` to inform users in case their Locator returns a huge
1771
+ number of ticks, causing Matplotlib to run out of memory.
1772
+
1773
+ The "strange" name of this method dates back to when it would raise an
1774
+ exception instead of emitting a log.
1775
+ """
1776
+ if len(locs) >= self.MAXTICKS:
1777
+ _log.warning(
1778
+ "Locator attempting to generate %s ticks ([%s, ..., %s]), "
1779
+ "which exceeds Locator.MAXTICKS (%s).",
1780
+ len(locs), locs[0], locs[-1], self.MAXTICKS)
1781
+ return locs
1782
+
1783
+ def nonsingular(self, v0, v1):
1784
+ """
1785
+ Adjust a range as needed to avoid singularities.
1786
+
1787
+ This method gets called during autoscaling, with ``(v0, v1)`` set to
1788
+ the data limits on the Axes if the Axes contains any data, or
1789
+ ``(-inf, +inf)`` if not.
1790
+
1791
+ - If ``v0 == v1`` (possibly up to some floating point slop), this
1792
+ method returns an expanded interval around this value.
1793
+ - If ``(v0, v1) == (-inf, +inf)``, this method returns appropriate
1794
+ default view limits.
1795
+ - Otherwise, ``(v0, v1)`` is returned without modification.
1796
+ """
1797
+ return mtransforms._nonsingular(v0, v1, expander=.05)
1798
+
1799
+ def view_limits(self, vmin, vmax):
1800
+ """
1801
+ Select a scale for the range from vmin to vmax.
1802
+
1803
+ Subclasses should override this method to change locator behaviour.
1804
+ """
1805
+ return mtransforms._nonsingular(vmin, vmax)
1806
+
1807
+
1808
+ class IndexLocator(Locator):
1809
+ """
1810
+ Place ticks at every nth point plotted.
1811
+
1812
+ IndexLocator assumes index plotting; i.e., that the ticks are placed at integer
1813
+ values in the range between 0 and len(data) inclusive.
1814
+ """
1815
+
1816
+ def __init__(self, base, offset):
1817
+ """Place ticks every *base* data point, starting at *offset*."""
1818
+ self._base = base
1819
+ self.offset = offset
1820
+
1821
+ def set_params(self, base=None, offset=None):
1822
+ """Set parameters within this locator"""
1823
+ if base is not None:
1824
+ self._base = base
1825
+ if offset is not None:
1826
+ self.offset = offset
1827
+
1828
+ def __call__(self):
1829
+ """Return the locations of the ticks"""
1830
+ dmin, dmax = self.axis.get_data_interval()
1831
+ return self.tick_values(dmin, dmax)
1832
+
1833
+ def tick_values(self, vmin, vmax):
1834
+ # We want tick values in the closed interval [vmin, vmax].
1835
+ # Since np.arange(start, stop) returns values in the semi-open interval
1836
+ # [start, stop), we add a minimal offset so that stop = vmax + eps
1837
+ tick_values = np.arange(vmin + self.offset, vmax + 1e-12, self._base)
1838
+ return self.raise_if_exceeds(tick_values)
1839
+
1840
+
1841
+ class FixedLocator(Locator):
1842
+ r"""
1843
+ Place ticks at a set of fixed values.
1844
+
1845
+ If *nbins* is None ticks are placed at all values. Otherwise, the *locs* array of
1846
+ possible positions will be subsampled to keep the number of ticks
1847
+ :math:`\leq nbins + 1`. The subsampling will be done to include the smallest
1848
+ absolute value; for example, if zero is included in the array of possibilities, then
1849
+ it will be included in the chosen ticks.
1850
+ """
1851
+
1852
+ def __init__(self, locs, nbins=None):
1853
+ self.locs = np.asarray(locs)
1854
+ _api.check_shape((None,), locs=self.locs)
1855
+ self.nbins = max(nbins, 2) if nbins is not None else None
1856
+
1857
+ def set_params(self, nbins=None):
1858
+ """Set parameters within this locator."""
1859
+ if nbins is not None:
1860
+ self.nbins = nbins
1861
+
1862
+ def __call__(self):
1863
+ return self.tick_values(None, None)
1864
+
1865
+ def tick_values(self, vmin, vmax):
1866
+ """
1867
+ Return the locations of the ticks.
1868
+
1869
+ .. note::
1870
+
1871
+ Because the values are fixed, *vmin* and *vmax* are not used.
1872
+ """
1873
+ if self.nbins is None:
1874
+ return self.locs
1875
+ step = max(int(np.ceil(len(self.locs) / self.nbins)), 1)
1876
+ ticks = self.locs[::step]
1877
+ for i in range(1, step):
1878
+ ticks1 = self.locs[i::step]
1879
+ if np.abs(ticks1).min() < np.abs(ticks).min():
1880
+ ticks = ticks1
1881
+ return self.raise_if_exceeds(ticks)
1882
+
1883
+
1884
+ class NullLocator(Locator):
1885
+ """
1886
+ Place no ticks.
1887
+ """
1888
+
1889
+ def __call__(self):
1890
+ return self.tick_values(None, None)
1891
+
1892
+ def tick_values(self, vmin, vmax):
1893
+ """
1894
+ Return the locations of the ticks.
1895
+
1896
+ .. note::
1897
+
1898
+ Because there are no ticks, *vmin* and *vmax* are not used.
1899
+ """
1900
+ return []
1901
+
1902
+
1903
+ class LinearLocator(Locator):
1904
+ """
1905
+ Place ticks at evenly spaced values.
1906
+
1907
+ The first time this function is called, it will try to set the number of
1908
+ ticks to make a nice tick partitioning. Thereafter, the number of ticks
1909
+ will be fixed to avoid jumping during interactive navigation.
1910
+ """
1911
+
1912
+ def __init__(self, numticks=None, presets=None):
1913
+ """
1914
+ Parameters
1915
+ ----------
1916
+ numticks : int or None, default None
1917
+ Number of ticks. If None, *numticks* = 11.
1918
+ presets : dict or None, default: None
1919
+ Dictionary mapping ``(vmin, vmax)`` to an array of locations.
1920
+ Overrides *numticks* if there is an entry for the current
1921
+ ``(vmin, vmax)``.
1922
+ """
1923
+ self.numticks = numticks
1924
+ if presets is None:
1925
+ self.presets = {}
1926
+ else:
1927
+ self.presets = presets
1928
+
1929
+ @property
1930
+ def numticks(self):
1931
+ # Old hard-coded default.
1932
+ return self._numticks if self._numticks is not None else 11
1933
+
1934
+ @numticks.setter
1935
+ def numticks(self, numticks):
1936
+ self._numticks = numticks
1937
+
1938
+ def set_params(self, numticks=None, presets=None):
1939
+ """Set parameters within this locator."""
1940
+ if presets is not None:
1941
+ self.presets = presets
1942
+ if numticks is not None:
1943
+ self.numticks = numticks
1944
+
1945
+ def __call__(self):
1946
+ """Return the locations of the ticks."""
1947
+ vmin, vmax = self.axis.get_view_interval()
1948
+ return self.tick_values(vmin, vmax)
1949
+
1950
+ def tick_values(self, vmin, vmax):
1951
+ vmin, vmax = mtransforms._nonsingular(vmin, vmax, expander=0.05)
1952
+
1953
+ if (vmin, vmax) in self.presets:
1954
+ return self.presets[(vmin, vmax)]
1955
+
1956
+ if self.numticks == 0:
1957
+ return []
1958
+ ticklocs = np.linspace(vmin, vmax, self.numticks)
1959
+
1960
+ return self.raise_if_exceeds(ticklocs)
1961
+
1962
+ def view_limits(self, vmin, vmax):
1963
+ """Try to choose the view limits intelligently."""
1964
+
1965
+ if vmax < vmin:
1966
+ vmin, vmax = vmax, vmin
1967
+
1968
+ if vmin == vmax:
1969
+ vmin -= 1
1970
+ vmax += 1
1971
+
1972
+ if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
1973
+ exponent, remainder = divmod(
1974
+ math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1)))
1975
+ exponent -= (remainder < .5)
1976
+ scale = max(self.numticks - 1, 1) ** (-exponent)
1977
+ vmin = math.floor(scale * vmin) / scale
1978
+ vmax = math.ceil(scale * vmax) / scale
1979
+
1980
+ return mtransforms._nonsingular(vmin, vmax)
1981
+
1982
+
1983
+ class MultipleLocator(Locator):
1984
+ """
1985
+ Place ticks at every integer multiple of a base plus an offset.
1986
+ """
1987
+
1988
+ def __init__(self, base=1.0, offset=0.0):
1989
+ """
1990
+ Parameters
1991
+ ----------
1992
+ base : float > 0, default: 1.0
1993
+ Interval between ticks.
1994
+ offset : float, default: 0.0
1995
+ Value added to each multiple of *base*.
1996
+
1997
+ .. versionadded:: 3.8
1998
+ """
1999
+ self._edge = _Edge_integer(base, 0)
2000
+ self._offset = offset
2001
+
2002
+ def set_params(self, base=None, offset=None):
2003
+ """
2004
+ Set parameters within this locator.
2005
+
2006
+ Parameters
2007
+ ----------
2008
+ base : float > 0, optional
2009
+ Interval between ticks.
2010
+ offset : float, optional
2011
+ Value added to each multiple of *base*.
2012
+
2013
+ .. versionadded:: 3.8
2014
+ """
2015
+ if base is not None:
2016
+ self._edge = _Edge_integer(base, 0)
2017
+ if offset is not None:
2018
+ self._offset = offset
2019
+
2020
+ def __call__(self):
2021
+ """Return the locations of the ticks."""
2022
+ vmin, vmax = self.axis.get_view_interval()
2023
+ return self.tick_values(vmin, vmax)
2024
+
2025
+ def tick_values(self, vmin, vmax):
2026
+ if vmax < vmin:
2027
+ vmin, vmax = vmax, vmin
2028
+ step = self._edge.step
2029
+ vmin -= self._offset
2030
+ vmax -= self._offset
2031
+ vmin = self._edge.ge(vmin) * step
2032
+ n = (vmax - vmin + 0.001 * step) // step
2033
+ locs = vmin - step + np.arange(n + 3) * step + self._offset
2034
+ return self.raise_if_exceeds(locs)
2035
+
2036
+ def view_limits(self, dmin, dmax):
2037
+ """
2038
+ Set the view limits to the nearest tick values that contain the data.
2039
+ """
2040
+ if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
2041
+ vmin = self._edge.le(dmin - self._offset) * self._edge.step + self._offset
2042
+ vmax = self._edge.ge(dmax - self._offset) * self._edge.step + self._offset
2043
+ if vmin == vmax:
2044
+ vmin -= 1
2045
+ vmax += 1
2046
+ else:
2047
+ vmin = dmin
2048
+ vmax = dmax
2049
+
2050
+ return mtransforms._nonsingular(vmin, vmax)
2051
+
2052
+
2053
+ def scale_range(vmin, vmax, n=1, threshold=100):
2054
+ dv = abs(vmax - vmin) # > 0 as nonsingular is called before.
2055
+ meanv = (vmax + vmin) / 2
2056
+ if abs(meanv) / dv < threshold:
2057
+ offset = 0
2058
+ else:
2059
+ offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv)
2060
+ scale = 10 ** (math.log10(dv / n) // 1)
2061
+ return scale, offset
2062
+
2063
+
2064
+ class _Edge_integer:
2065
+ """
2066
+ Helper for `.MaxNLocator`, `.MultipleLocator`, etc.
2067
+
2068
+ Take floating-point precision limitations into account when calculating
2069
+ tick locations as integer multiples of a step.
2070
+ """
2071
+
2072
+ def __init__(self, step, offset):
2073
+ """
2074
+ Parameters
2075
+ ----------
2076
+ step : float > 0
2077
+ Interval between ticks.
2078
+ offset : float
2079
+ Offset subtracted from the data limits prior to calculating tick
2080
+ locations.
2081
+ """
2082
+ if step <= 0:
2083
+ raise ValueError("'step' must be positive")
2084
+ self.step = step
2085
+ self._offset = abs(offset)
2086
+
2087
+ def closeto(self, ms, edge):
2088
+ # Allow more slop when the offset is large compared to the step.
2089
+ if self._offset > 0:
2090
+ digits = np.log10(self._offset / self.step)
2091
+ tol = max(1e-10, 10 ** (digits - 12))
2092
+ tol = min(0.4999, tol)
2093
+ else:
2094
+ tol = 1e-10
2095
+ return abs(ms - edge) < tol
2096
+
2097
+ def le(self, x):
2098
+ """Return the largest n: n*step <= x."""
2099
+ d, m = divmod(x, self.step)
2100
+ if self.closeto(m / self.step, 1):
2101
+ return d + 1
2102
+ return d
2103
+
2104
+ def ge(self, x):
2105
+ """Return the smallest n: n*step >= x."""
2106
+ d, m = divmod(x, self.step)
2107
+ if self.closeto(m / self.step, 0):
2108
+ return d
2109
+ return d + 1
2110
+
2111
+
2112
+ class MaxNLocator(Locator):
2113
+ """
2114
+ Place evenly spaced ticks, with a cap on the total number of ticks.
2115
+
2116
+ Finds nice tick locations with no more than :math:`nbins + 1` ticks being within the
2117
+ view limits. Locations beyond the limits are added to support autoscaling.
2118
+ """
2119
+ default_params = dict(nbins=10,
2120
+ steps=None,
2121
+ integer=False,
2122
+ symmetric=False,
2123
+ prune=None,
2124
+ min_n_ticks=2)
2125
+
2126
+ def __init__(self, nbins=None, **kwargs):
2127
+ """
2128
+ Parameters
2129
+ ----------
2130
+ nbins : int or 'auto', default: 10
2131
+ Maximum number of intervals; one less than max number of
2132
+ ticks. If the string 'auto', the number of bins will be
2133
+ automatically determined based on the length of the axis.
2134
+
2135
+ steps : array-like, optional
2136
+ Sequence of acceptable tick multiples, starting with 1 and
2137
+ ending with 10. For example, if ``steps=[1, 2, 4, 5, 10]``,
2138
+ ``20, 40, 60`` or ``0.4, 0.6, 0.8`` would be possible
2139
+ sets of ticks because they are multiples of 2.
2140
+ ``30, 60, 90`` would not be generated because 3 does not
2141
+ appear in this example list of steps.
2142
+
2143
+ integer : bool, default: False
2144
+ If True, ticks will take only integer values, provided at least
2145
+ *min_n_ticks* integers are found within the view limits.
2146
+
2147
+ symmetric : bool, default: False
2148
+ If True, autoscaling will result in a range symmetric about zero.
2149
+
2150
+ prune : {'lower', 'upper', 'both', None}, default: None
2151
+ Remove the 'lower' tick, the 'upper' tick, or ticks on 'both' sides
2152
+ *if they fall exactly on an axis' edge* (this typically occurs when
2153
+ :rc:`axes.autolimit_mode` is 'round_numbers'). Removing such ticks
2154
+ is mostly useful for stacked or ganged plots, where the upper tick
2155
+ of an Axes overlaps with the lower tick of the axes above it.
2156
+
2157
+ min_n_ticks : int, default: 2
2158
+ Relax *nbins* and *integer* constraints if necessary to obtain
2159
+ this minimum number of ticks.
2160
+ """
2161
+ if nbins is not None:
2162
+ kwargs['nbins'] = nbins
2163
+ self.set_params(**{**self.default_params, **kwargs})
2164
+
2165
+ @staticmethod
2166
+ def _validate_steps(steps):
2167
+ if not np.iterable(steps):
2168
+ raise ValueError('steps argument must be an increasing sequence '
2169
+ 'of numbers between 1 and 10 inclusive')
2170
+ steps = np.asarray(steps)
2171
+ if np.any(np.diff(steps) <= 0) or steps[-1] > 10 or steps[0] < 1:
2172
+ raise ValueError('steps argument must be an increasing sequence '
2173
+ 'of numbers between 1 and 10 inclusive')
2174
+ if steps[0] != 1:
2175
+ steps = np.concatenate([[1], steps])
2176
+ if steps[-1] != 10:
2177
+ steps = np.concatenate([steps, [10]])
2178
+ return steps
2179
+
2180
+ @staticmethod
2181
+ def _staircase(steps):
2182
+ # Make an extended staircase within which the needed step will be
2183
+ # found. This is probably much larger than necessary.
2184
+ return np.concatenate([0.1 * steps[:-1], steps, [10 * steps[1]]])
2185
+
2186
+ def set_params(self, **kwargs):
2187
+ """
2188
+ Set parameters for this locator.
2189
+
2190
+ Parameters
2191
+ ----------
2192
+ nbins : int or 'auto', optional
2193
+ see `.MaxNLocator`
2194
+ steps : array-like, optional
2195
+ see `.MaxNLocator`
2196
+ integer : bool, optional
2197
+ see `.MaxNLocator`
2198
+ symmetric : bool, optional
2199
+ see `.MaxNLocator`
2200
+ prune : {'lower', 'upper', 'both', None}, optional
2201
+ see `.MaxNLocator`
2202
+ min_n_ticks : int, optional
2203
+ see `.MaxNLocator`
2204
+ """
2205
+ if 'nbins' in kwargs:
2206
+ self._nbins = kwargs.pop('nbins')
2207
+ if self._nbins != 'auto':
2208
+ self._nbins = int(self._nbins)
2209
+ if 'symmetric' in kwargs:
2210
+ self._symmetric = kwargs.pop('symmetric')
2211
+ if 'prune' in kwargs:
2212
+ prune = kwargs.pop('prune')
2213
+ _api.check_in_list(['upper', 'lower', 'both', None], prune=prune)
2214
+ self._prune = prune
2215
+ if 'min_n_ticks' in kwargs:
2216
+ self._min_n_ticks = max(1, kwargs.pop('min_n_ticks'))
2217
+ if 'steps' in kwargs:
2218
+ steps = kwargs.pop('steps')
2219
+ if steps is None:
2220
+ self._steps = np.array([1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10])
2221
+ else:
2222
+ self._steps = self._validate_steps(steps)
2223
+ self._extended_steps = self._staircase(self._steps)
2224
+ if 'integer' in kwargs:
2225
+ self._integer = kwargs.pop('integer')
2226
+ if kwargs:
2227
+ raise _api.kwarg_error("set_params", kwargs)
2228
+
2229
+ def _raw_ticks(self, vmin, vmax):
2230
+ """
2231
+ Generate a list of tick locations including the range *vmin* to
2232
+ *vmax*. In some applications, one or both of the end locations
2233
+ will not be needed, in which case they are trimmed off
2234
+ elsewhere.
2235
+ """
2236
+ if self._nbins == 'auto':
2237
+ if self.axis is not None:
2238
+ nbins = np.clip(self.axis.get_tick_space(),
2239
+ max(1, self._min_n_ticks - 1), 9)
2240
+ else:
2241
+ nbins = 9
2242
+ else:
2243
+ nbins = self._nbins
2244
+
2245
+ scale, offset = scale_range(vmin, vmax, nbins)
2246
+ _vmin = vmin - offset
2247
+ _vmax = vmax - offset
2248
+ steps = self._extended_steps * scale
2249
+ if self._integer:
2250
+ # For steps > 1, keep only integer values.
2251
+ igood = (steps < 1) | (np.abs(steps - np.round(steps)) < 0.001)
2252
+ steps = steps[igood]
2253
+
2254
+ raw_step = ((_vmax - _vmin) / nbins)
2255
+ if hasattr(self.axis, "axes") and self.axis.axes.name == '3d':
2256
+ # Due to the change in automargin behavior in mpl3.9, we need to
2257
+ # adjust the raw step to match the mpl3.8 appearance. The zoom
2258
+ # factor of 2/48, gives us the 23/24 modifier.
2259
+ raw_step = raw_step * 23/24
2260
+ large_steps = steps >= raw_step
2261
+ if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
2262
+ # Classic round_numbers mode may require a larger step.
2263
+ # Get first multiple of steps that are <= _vmin
2264
+ floored_vmins = (_vmin // steps) * steps
2265
+ floored_vmaxs = floored_vmins + steps * nbins
2266
+ large_steps = large_steps & (floored_vmaxs >= _vmax)
2267
+
2268
+ # Find index of smallest large step
2269
+ if any(large_steps):
2270
+ istep = np.nonzero(large_steps)[0][0]
2271
+ else:
2272
+ istep = len(steps) - 1
2273
+
2274
+ # Start at smallest of the steps greater than the raw step, and check
2275
+ # if it provides enough ticks. If not, work backwards through
2276
+ # smaller steps until one is found that provides enough ticks.
2277
+ for step in steps[:istep+1][::-1]:
2278
+
2279
+ if (self._integer and
2280
+ np.floor(_vmax) - np.ceil(_vmin) >= self._min_n_ticks - 1):
2281
+ step = max(1, step)
2282
+ best_vmin = (_vmin // step) * step
2283
+
2284
+ # Find tick locations spanning the vmin-vmax range, taking into
2285
+ # account degradation of precision when there is a large offset.
2286
+ # The edge ticks beyond vmin and/or vmax are needed for the
2287
+ # "round_numbers" autolimit mode.
2288
+ edge = _Edge_integer(step, offset)
2289
+ low = edge.le(_vmin - best_vmin)
2290
+ high = edge.ge(_vmax - best_vmin)
2291
+ ticks = np.arange(low, high + 1) * step + best_vmin
2292
+ # Count only the ticks that will be displayed.
2293
+ nticks = ((ticks <= _vmax) & (ticks >= _vmin)).sum()
2294
+ if nticks >= self._min_n_ticks:
2295
+ break
2296
+ return ticks + offset
2297
+
2298
+ def __call__(self):
2299
+ vmin, vmax = self.axis.get_view_interval()
2300
+ return self.tick_values(vmin, vmax)
2301
+
2302
+ def tick_values(self, vmin, vmax):
2303
+ if self._symmetric:
2304
+ vmax = max(abs(vmin), abs(vmax))
2305
+ vmin = -vmax
2306
+ vmin, vmax = mtransforms._nonsingular(
2307
+ vmin, vmax, expander=1e-13, tiny=1e-14)
2308
+ locs = self._raw_ticks(vmin, vmax)
2309
+
2310
+ prune = self._prune
2311
+ if prune == 'lower':
2312
+ locs = locs[1:]
2313
+ elif prune == 'upper':
2314
+ locs = locs[:-1]
2315
+ elif prune == 'both':
2316
+ locs = locs[1:-1]
2317
+ return self.raise_if_exceeds(locs)
2318
+
2319
+ def view_limits(self, dmin, dmax):
2320
+ if self._symmetric:
2321
+ dmax = max(abs(dmin), abs(dmax))
2322
+ dmin = -dmax
2323
+
2324
+ dmin, dmax = mtransforms._nonsingular(
2325
+ dmin, dmax, expander=1e-12, tiny=1e-13)
2326
+
2327
+ if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
2328
+ return self._raw_ticks(dmin, dmax)[[0, -1]]
2329
+ else:
2330
+ return dmin, dmax
2331
+
2332
+
2333
+ def _is_decade(x, *, base=10, rtol=None):
2334
+ """Return True if *x* is an integer power of *base*."""
2335
+ if not np.isfinite(x):
2336
+ return False
2337
+ if x == 0.0:
2338
+ return True
2339
+ lx = np.log(abs(x)) / np.log(base)
2340
+ if rtol is None:
2341
+ return np.isclose(lx, np.round(lx))
2342
+ else:
2343
+ return np.isclose(lx, np.round(lx), rtol=rtol)
2344
+
2345
+
2346
+ def _decade_less_equal(x, base):
2347
+ """
2348
+ Return the largest integer power of *base* that's less or equal to *x*.
2349
+
2350
+ If *x* is negative, the exponent will be *greater*.
2351
+ """
2352
+ return (x if x == 0 else
2353
+ -_decade_greater_equal(-x, base) if x < 0 else
2354
+ base ** np.floor(np.log(x) / np.log(base)))
2355
+
2356
+
2357
+ def _decade_greater_equal(x, base):
2358
+ """
2359
+ Return the smallest integer power of *base* that's greater or equal to *x*.
2360
+
2361
+ If *x* is negative, the exponent will be *smaller*.
2362
+ """
2363
+ return (x if x == 0 else
2364
+ -_decade_less_equal(-x, base) if x < 0 else
2365
+ base ** np.ceil(np.log(x) / np.log(base)))
2366
+
2367
+
2368
+ def _decade_less(x, base):
2369
+ """
2370
+ Return the largest integer power of *base* that's less than *x*.
2371
+
2372
+ If *x* is negative, the exponent will be *greater*.
2373
+ """
2374
+ if x < 0:
2375
+ return -_decade_greater(-x, base)
2376
+ less = _decade_less_equal(x, base)
2377
+ if less == x:
2378
+ less /= base
2379
+ return less
2380
+
2381
+
2382
+ def _decade_greater(x, base):
2383
+ """
2384
+ Return the smallest integer power of *base* that's greater than *x*.
2385
+
2386
+ If *x* is negative, the exponent will be *smaller*.
2387
+ """
2388
+ if x < 0:
2389
+ return -_decade_less(-x, base)
2390
+ greater = _decade_greater_equal(x, base)
2391
+ if greater == x:
2392
+ greater *= base
2393
+ return greater
2394
+
2395
+
2396
+ def _is_close_to_int(x):
2397
+ return math.isclose(x, round(x))
2398
+
2399
+
2400
+ class LogLocator(Locator):
2401
+ """
2402
+ Place logarithmically spaced ticks.
2403
+
2404
+ Places ticks at the values ``subs[j] * base**i``.
2405
+ """
2406
+
2407
+ def __init__(self, base=10.0, subs=(1.0,), *, numticks=None):
2408
+ """
2409
+ Parameters
2410
+ ----------
2411
+ base : float, default: 10.0
2412
+ The base of the log used, so major ticks are placed at ``base**n``, where
2413
+ ``n`` is an integer.
2414
+ subs : None or {'auto', 'all'} or sequence of float, default: (1.0,)
2415
+ Gives the multiples of integer powers of the base at which to place ticks.
2416
+ The default of ``(1.0, )`` places ticks only at integer powers of the base.
2417
+ Permitted string values are ``'auto'`` and ``'all'``. Both of these use an
2418
+ algorithm based on the axis view limits to determine whether and how to put
2419
+ ticks between integer powers of the base:
2420
+ - ``'auto'``: Ticks are placed only between integer powers.
2421
+ - ``'all'``: Ticks are placed between *and* at integer powers.
2422
+ - ``None``: Equivalent to ``'auto'``.
2423
+ numticks : None or int, default: None
2424
+ The maximum number of ticks to allow on a given axis. The default of
2425
+ ``None`` will try to choose intelligently as long as this Locator has
2426
+ already been assigned to an axis using `~.axis.Axis.get_tick_space`, but
2427
+ otherwise falls back to 9.
2428
+ """
2429
+ if numticks is None:
2430
+ if mpl.rcParams['_internal.classic_mode']:
2431
+ numticks = 15
2432
+ else:
2433
+ numticks = 'auto'
2434
+ self._base = float(base)
2435
+ self._set_subs(subs)
2436
+ self.numticks = numticks
2437
+
2438
+ def set_params(self, base=None, subs=None, *, numticks=None):
2439
+ """Set parameters within this locator."""
2440
+ if base is not None:
2441
+ self._base = float(base)
2442
+ if subs is not None:
2443
+ self._set_subs(subs)
2444
+ if numticks is not None:
2445
+ self.numticks = numticks
2446
+
2447
+ def _set_subs(self, subs):
2448
+ """
2449
+ Set the minor ticks for the log scaling every ``base**i*subs[j]``.
2450
+ """
2451
+ if subs is None: # consistency with previous bad API
2452
+ self._subs = 'auto'
2453
+ elif isinstance(subs, str):
2454
+ _api.check_in_list(('all', 'auto'), subs=subs)
2455
+ self._subs = subs
2456
+ else:
2457
+ try:
2458
+ self._subs = np.asarray(subs, dtype=float)
2459
+ except ValueError as e:
2460
+ raise ValueError("subs must be None, 'all', 'auto' or "
2461
+ "a sequence of floats, not "
2462
+ f"{subs}.") from e
2463
+ if self._subs.ndim != 1:
2464
+ raise ValueError("A sequence passed to subs must be "
2465
+ "1-dimensional, not "
2466
+ f"{self._subs.ndim}-dimensional.")
2467
+
2468
+ def __call__(self):
2469
+ """Return the locations of the ticks."""
2470
+ vmin, vmax = self.axis.get_view_interval()
2471
+ return self.tick_values(vmin, vmax)
2472
+
2473
+ def _log_b(self, x):
2474
+ # Use specialized logs if possible, as they can be more accurate; e.g.
2475
+ # log(.001) / log(10) = -2.999... (whether math.log or np.log) due to
2476
+ # floating point error.
2477
+ return (np.log10(x) if self._base == 10 else
2478
+ np.log2(x) if self._base == 2 else
2479
+ np.log(x) / np.log(self._base))
2480
+
2481
+ def tick_values(self, vmin, vmax):
2482
+ n_request = (
2483
+ self.numticks if self.numticks != "auto" else
2484
+ np.clip(self.axis.get_tick_space(), 2, 9) if self.axis is not None else
2485
+ 9)
2486
+
2487
+ b = self._base
2488
+ if vmin <= 0.0:
2489
+ if self.axis is not None:
2490
+ vmin = self.axis.get_minpos()
2491
+
2492
+ if vmin <= 0.0 or not np.isfinite(vmin):
2493
+ raise ValueError(
2494
+ "Data cannot be log-scaled because all values are <= 0.")
2495
+
2496
+ if vmax < vmin:
2497
+ vmin, vmax = vmax, vmin
2498
+ # Min and max exponents, float and int versions; e.g., if vmin=10^0.3,
2499
+ # vmax=10^6.9, then efmin=0.3, emin=1, emax=6, efmax=6.9, n_avail=6.
2500
+ efmin, efmax = self._log_b([vmin, vmax])
2501
+ emin = math.ceil(efmin)
2502
+ emax = math.floor(efmax)
2503
+ n_avail = emax - emin + 1 # Total number of decade ticks available.
2504
+
2505
+ if isinstance(self._subs, str):
2506
+ if n_avail >= 10 or b < 3:
2507
+ if self._subs == 'auto':
2508
+ return np.array([]) # no minor or major ticks
2509
+ else:
2510
+ subs = np.array([1.0]) # major ticks
2511
+ else:
2512
+ _first = 2.0 if self._subs == 'auto' else 1.0
2513
+ subs = np.arange(_first, b)
2514
+ else:
2515
+ subs = self._subs
2516
+
2517
+ # Get decades between major ticks. Include an extra tick outside the
2518
+ # lower and the upper limit: QuadContourSet._autolev relies on this.
2519
+ if mpl.rcParams["_internal.classic_mode"]: # keep historic formulas
2520
+ stride = max(math.ceil((n_avail - 1) / (n_request - 1)), 1)
2521
+ decades = np.arange(emin - stride, emax + stride + 1, stride)
2522
+ else:
2523
+ # *Determine the actual number of ticks*: Find the largest number
2524
+ # of ticks, no more than the requested number, that can actually
2525
+ # be drawn (e.g., with 9 decades ticks, no stride yields 7
2526
+ # ticks). For a given value of the stride *s*, there are either
2527
+ # floor(n_avail/s) or ceil(n_avail/s) ticks depending on the
2528
+ # offset. Pick the smallest stride such that floor(n_avail/s) <
2529
+ # n_request, i.e. n_avail/s < n_request+1, then re-set n_request
2530
+ # to ceil(...) if acceptable, else to floor(...) (which must then
2531
+ # equal the original n_request, i.e. n_request is kept unchanged).
2532
+ stride = n_avail // (n_request + 1) + 1
2533
+ nr = math.ceil(n_avail / stride)
2534
+ if nr <= n_request:
2535
+ n_request = nr
2536
+ else:
2537
+ assert nr == n_request + 1
2538
+ if n_request == 0: # No tick in bounds; two ticks just outside.
2539
+ decades = [emin - 1, emax + 1]
2540
+ stride = decades[1] - decades[0]
2541
+ elif n_request == 1: # A single tick close to center.
2542
+ mid = round((efmin + efmax) / 2)
2543
+ stride = max(mid - (emin - 1), (emax + 1) - mid)
2544
+ decades = [mid - stride, mid, mid + stride]
2545
+ else:
2546
+ # *Determine the stride*: Pick the largest stride that yields
2547
+ # this actual n_request (e.g., with 15 decades, strides of
2548
+ # 5, 6, or 7 *can* yield 3 ticks; picking a larger stride
2549
+ # minimizes unticked space at the ends). First try for
2550
+ # ceil(n_avail/stride) == n_request
2551
+ # i.e.
2552
+ # n_avail/n_request <= stride < n_avail/(n_request-1)
2553
+ # else fallback to
2554
+ # floor(n_avail/stride) == n_request
2555
+ # i.e.
2556
+ # n_avail/(n_request+1) < stride <= n_avail/n_request
2557
+ # One of these cases must have an integer solution (given the
2558
+ # choice of n_request above).
2559
+ stride = (n_avail - 1) // (n_request - 1)
2560
+ if stride < n_avail / n_request: # fallback to second case
2561
+ stride = n_avail // n_request
2562
+ # *Determine the offset*: For a given stride *and offset*
2563
+ # (0 <= offset < stride), the actual number of ticks is
2564
+ # ceil((n_avail - offset) / stride), which must be equal to
2565
+ # n_request. This leads to olo <= offset < ohi, with the
2566
+ # values defined below.
2567
+ olo = max(n_avail - stride * n_request, 0)
2568
+ ohi = min(n_avail - stride * (n_request - 1), stride)
2569
+ # Try to see if we can pick an offset so that ticks are at
2570
+ # integer multiples of the stride while satisfying the bounds
2571
+ # above; if not, fallback to the smallest acceptable offset.
2572
+ offset = (-emin) % stride
2573
+ if not olo <= offset < ohi:
2574
+ offset = olo
2575
+ decades = range(emin + offset - stride, emax + stride + 1, stride)
2576
+
2577
+ # Guess whether we're a minor locator, based on whether subs include
2578
+ # anything other than 1.
2579
+ is_minor = len(subs) > 1 or (len(subs) == 1 and subs[0] != 1.0)
2580
+ if is_minor:
2581
+ if stride == 1 or n_avail <= 1:
2582
+ # Minor ticks start in the decade preceding the first major tick.
2583
+ ticklocs = np.concatenate([
2584
+ subs * b**decade for decade in range(emin - 1, emax + 1)])
2585
+ else:
2586
+ ticklocs = np.array([])
2587
+ else:
2588
+ ticklocs = b ** np.array(decades)
2589
+
2590
+ if (len(subs) > 1
2591
+ and stride == 1
2592
+ and (len(decades) - 2 # major
2593
+ + ((vmin <= ticklocs) & (ticklocs <= vmax)).sum()) # minor
2594
+ <= 1):
2595
+ # If we're a minor locator *that expects at least two ticks per
2596
+ # decade* and the major locator stride is 1 and there's no more
2597
+ # than one major or minor tick, switch to AutoLocator.
2598
+ return AutoLocator().tick_values(vmin, vmax)
2599
+ else:
2600
+ return self.raise_if_exceeds(ticklocs)
2601
+
2602
+ def view_limits(self, vmin, vmax):
2603
+ """Try to choose the view limits intelligently."""
2604
+ b = self._base
2605
+
2606
+ vmin, vmax = self.nonsingular(vmin, vmax)
2607
+
2608
+ if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
2609
+ vmin = _decade_less_equal(vmin, b)
2610
+ vmax = _decade_greater_equal(vmax, b)
2611
+
2612
+ return vmin, vmax
2613
+
2614
+ def nonsingular(self, vmin, vmax):
2615
+ if vmin > vmax:
2616
+ vmin, vmax = vmax, vmin
2617
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
2618
+ vmin, vmax = 1, 10 # Initial range, no data plotted yet.
2619
+ elif vmax <= 0:
2620
+ _api.warn_external(
2621
+ "Data has no positive values, and therefore cannot be "
2622
+ "log-scaled.")
2623
+ vmin, vmax = 1, 10
2624
+ else:
2625
+ # Consider shared axises
2626
+ minpos = min(axis.get_minpos() for axis in self.axis._get_shared_axis())
2627
+ if not np.isfinite(minpos):
2628
+ minpos = 1e-300 # This should never take effect.
2629
+ if vmin <= 0:
2630
+ vmin = minpos
2631
+ if vmin == vmax:
2632
+ vmin = _decade_less(vmin, self._base)
2633
+ vmax = _decade_greater(vmax, self._base)
2634
+ return vmin, vmax
2635
+
2636
+
2637
+ class SymmetricalLogLocator(Locator):
2638
+ """
2639
+ Place ticks spaced linearly near zero and spaced logarithmically beyond a threshold.
2640
+ """
2641
+
2642
+ def __init__(self, transform=None, subs=None, linthresh=None, base=None):
2643
+ """
2644
+ Parameters
2645
+ ----------
2646
+ transform : `~.scale.SymmetricalLogTransform`, optional
2647
+ If set, defines the *base* and *linthresh* of the symlog transform.
2648
+ base, linthresh : float, optional
2649
+ The *base* and *linthresh* of the symlog transform, as documented
2650
+ for `.SymmetricalLogScale`. These parameters are only used if
2651
+ *transform* is not set.
2652
+ subs : sequence of float, default: [1]
2653
+ The multiples of integer powers of the base where ticks are placed,
2654
+ i.e., ticks are placed at
2655
+ ``[sub * base**i for i in ... for sub in subs]``.
2656
+
2657
+ Notes
2658
+ -----
2659
+ Either *transform*, or both *base* and *linthresh*, must be given.
2660
+ """
2661
+ if transform is not None:
2662
+ self._base = transform.base
2663
+ self._linthresh = transform.linthresh
2664
+ elif linthresh is not None and base is not None:
2665
+ self._base = base
2666
+ self._linthresh = linthresh
2667
+ else:
2668
+ raise ValueError("Either transform, or both linthresh "
2669
+ "and base, must be provided.")
2670
+ if subs is None:
2671
+ self._subs = [1.0]
2672
+ else:
2673
+ self._subs = subs
2674
+ self.numticks = 15
2675
+
2676
+ def set_params(self, subs=None, numticks=None):
2677
+ """Set parameters within this locator."""
2678
+ if numticks is not None:
2679
+ self.numticks = numticks
2680
+ if subs is not None:
2681
+ self._subs = subs
2682
+
2683
+ def __call__(self):
2684
+ """Return the locations of the ticks."""
2685
+ # Note, these are untransformed coordinates
2686
+ vmin, vmax = self.axis.get_view_interval()
2687
+ return self.tick_values(vmin, vmax)
2688
+
2689
+ def tick_values(self, vmin, vmax):
2690
+ linthresh = self._linthresh
2691
+
2692
+ if vmax < vmin:
2693
+ vmin, vmax = vmax, vmin
2694
+
2695
+ # The domain is divided into three sections, only some of
2696
+ # which may actually be present.
2697
+ #
2698
+ # <======== -t ==0== t ========>
2699
+ # aaaaaaaaa bbbbb ccccccccc
2700
+ #
2701
+ # a) and c) will have ticks at integral log positions. The
2702
+ # number of ticks needs to be reduced if there are more
2703
+ # than self.numticks of them.
2704
+ #
2705
+ # b) has a tick at 0 and only 0 (we assume t is a small
2706
+ # number, and the linear segment is just an implementation
2707
+ # detail and not interesting.)
2708
+ #
2709
+ # We could also add ticks at t, but that seems to usually be
2710
+ # uninteresting.
2711
+ #
2712
+ # "simple" mode is when the range falls entirely within [-t, t]
2713
+ # -- it should just display (vmin, 0, vmax)
2714
+ if -linthresh <= vmin < vmax <= linthresh:
2715
+ # only the linear range is present
2716
+ return sorted({vmin, 0, vmax})
2717
+
2718
+ # Lower log range is present
2719
+ has_a = (vmin < -linthresh)
2720
+ # Upper log range is present
2721
+ has_c = (vmax > linthresh)
2722
+
2723
+ # Check if linear range is present
2724
+ has_b = (has_a and vmax > -linthresh) or (has_c and vmin < linthresh)
2725
+
2726
+ base = self._base
2727
+
2728
+ def get_log_range(lo, hi):
2729
+ lo = np.floor(np.log(lo) / np.log(base))
2730
+ hi = np.ceil(np.log(hi) / np.log(base))
2731
+ return lo, hi
2732
+
2733
+ # Calculate all the ranges, so we can determine striding
2734
+ a_lo, a_hi = (0, 0)
2735
+ if has_a:
2736
+ a_upper_lim = min(-linthresh, vmax)
2737
+ a_lo, a_hi = get_log_range(abs(a_upper_lim), abs(vmin) + 1)
2738
+
2739
+ c_lo, c_hi = (0, 0)
2740
+ if has_c:
2741
+ c_lower_lim = max(linthresh, vmin)
2742
+ c_lo, c_hi = get_log_range(c_lower_lim, vmax + 1)
2743
+
2744
+ # Calculate the total number of integer exponents in a and c ranges
2745
+ total_ticks = (a_hi - a_lo) + (c_hi - c_lo)
2746
+ if has_b:
2747
+ total_ticks += 1
2748
+ stride = max(total_ticks // (self.numticks - 1), 1)
2749
+
2750
+ decades = []
2751
+ if has_a:
2752
+ decades.extend(-1 * (base ** (np.arange(a_lo, a_hi,
2753
+ stride)[::-1])))
2754
+
2755
+ if has_b:
2756
+ decades.append(0.0)
2757
+
2758
+ if has_c:
2759
+ decades.extend(base ** (np.arange(c_lo, c_hi, stride)))
2760
+
2761
+ subs = np.asarray(self._subs)
2762
+
2763
+ if len(subs) > 1 or subs[0] != 1.0:
2764
+ ticklocs = []
2765
+ for decade in decades:
2766
+ if decade == 0:
2767
+ ticklocs.append(decade)
2768
+ else:
2769
+ ticklocs.extend(subs * decade)
2770
+ else:
2771
+ ticklocs = decades
2772
+
2773
+ return self.raise_if_exceeds(np.array(ticklocs))
2774
+
2775
+ def view_limits(self, vmin, vmax):
2776
+ """Try to choose the view limits intelligently."""
2777
+ b = self._base
2778
+ if vmax < vmin:
2779
+ vmin, vmax = vmax, vmin
2780
+
2781
+ if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
2782
+ vmin = _decade_less_equal(vmin, b)
2783
+ vmax = _decade_greater_equal(vmax, b)
2784
+ if vmin == vmax:
2785
+ vmin = _decade_less(vmin, b)
2786
+ vmax = _decade_greater(vmax, b)
2787
+
2788
+ return mtransforms._nonsingular(vmin, vmax)
2789
+
2790
+
2791
+ class AsinhLocator(Locator):
2792
+ """
2793
+ Place ticks spaced evenly on an inverse-sinh scale.
2794
+
2795
+ Generally used with the `~.scale.AsinhScale` class.
2796
+
2797
+ .. note::
2798
+
2799
+ This API is provisional and may be revised in the future
2800
+ based on early user feedback.
2801
+ """
2802
+ def __init__(self, linear_width, numticks=11, symthresh=0.2,
2803
+ base=10, subs=None):
2804
+ """
2805
+ Parameters
2806
+ ----------
2807
+ linear_width : float
2808
+ The scale parameter defining the extent
2809
+ of the quasi-linear region.
2810
+ numticks : int, default: 11
2811
+ The approximate number of major ticks that will fit
2812
+ along the entire axis
2813
+ symthresh : float, default: 0.2
2814
+ The fractional threshold beneath which data which covers
2815
+ a range that is approximately symmetric about zero
2816
+ will have ticks that are exactly symmetric.
2817
+ base : int, default: 10
2818
+ The number base used for rounding tick locations
2819
+ on a logarithmic scale. If this is less than one,
2820
+ then rounding is to the nearest integer multiple
2821
+ of powers of ten.
2822
+ subs : tuple, default: None
2823
+ Multiples of the number base, typically used
2824
+ for the minor ticks, e.g. (2, 5) when base=10.
2825
+ """
2826
+ super().__init__()
2827
+ self.linear_width = linear_width
2828
+ self.numticks = numticks
2829
+ self.symthresh = symthresh
2830
+ self.base = base
2831
+ self.subs = subs
2832
+
2833
+ def set_params(self, numticks=None, symthresh=None,
2834
+ base=None, subs=None):
2835
+ """Set parameters within this locator."""
2836
+ if numticks is not None:
2837
+ self.numticks = numticks
2838
+ if symthresh is not None:
2839
+ self.symthresh = symthresh
2840
+ if base is not None:
2841
+ self.base = base
2842
+ if subs is not None:
2843
+ self.subs = subs if len(subs) > 0 else None
2844
+
2845
+ def __call__(self):
2846
+ vmin, vmax = self.axis.get_view_interval()
2847
+ if (vmin * vmax) < 0 and abs(1 + vmax / vmin) < self.symthresh:
2848
+ # Data-range appears to be almost symmetric, so round up:
2849
+ bound = max(abs(vmin), abs(vmax))
2850
+ return self.tick_values(-bound, bound)
2851
+ else:
2852
+ return self.tick_values(vmin, vmax)
2853
+
2854
+ def tick_values(self, vmin, vmax):
2855
+ # Construct a set of uniformly-spaced "on-screen" locations.
2856
+ ymin, ymax = self.linear_width * np.arcsinh(np.array([vmin, vmax])
2857
+ / self.linear_width)
2858
+ ys = np.linspace(ymin, ymax, self.numticks)
2859
+ zero_dev = abs(ys / (ymax - ymin))
2860
+ if ymin * ymax < 0:
2861
+ # Ensure that the zero tick-mark is included, if the axis straddles zero.
2862
+ ys = np.hstack([ys[(zero_dev > 0.5 / self.numticks)], 0.0])
2863
+
2864
+ # Transform the "on-screen" grid to the data space:
2865
+ xs = self.linear_width * np.sinh(ys / self.linear_width)
2866
+ zero_xs = (ys == 0)
2867
+
2868
+ # Round the data-space values to be intuitive base-n numbers, keeping track of
2869
+ # positive and negative values separately and carefully treating the zero value.
2870
+ with np.errstate(divide="ignore"): # base ** log(0) = base ** -inf = 0.
2871
+ if self.base > 1:
2872
+ pows = (np.sign(xs)
2873
+ * self.base ** np.floor(np.log(abs(xs)) / math.log(self.base)))
2874
+ qs = np.outer(pows, self.subs).flatten() if self.subs else pows
2875
+ else: # No need to adjust sign(pows), as it cancels out when computing qs.
2876
+ pows = np.where(zero_xs, 1, 10**np.floor(np.log10(abs(xs))))
2877
+ qs = pows * np.round(xs / pows)
2878
+ ticks = np.array(sorted(set(qs)))
2879
+
2880
+ return ticks if len(ticks) >= 2 else np.linspace(vmin, vmax, self.numticks)
2881
+
2882
+
2883
+ class LogitLocator(MaxNLocator):
2884
+ """
2885
+ Place ticks spaced evenly on a logit scale.
2886
+ """
2887
+
2888
+ def __init__(self, minor=False, *, nbins="auto"):
2889
+ """
2890
+ Parameters
2891
+ ----------
2892
+ nbins : int or 'auto', optional
2893
+ Number of ticks. Only used if minor is False.
2894
+ minor : bool, default: False
2895
+ Indicate if this locator is for minor ticks or not.
2896
+ """
2897
+
2898
+ self._minor = minor
2899
+ super().__init__(nbins=nbins, steps=[1, 2, 5, 10])
2900
+
2901
+ def set_params(self, minor=None, **kwargs):
2902
+ """Set parameters within this locator."""
2903
+ if minor is not None:
2904
+ self._minor = minor
2905
+ super().set_params(**kwargs)
2906
+
2907
+ @property
2908
+ def minor(self):
2909
+ return self._minor
2910
+
2911
+ @minor.setter
2912
+ def minor(self, value):
2913
+ self.set_params(minor=value)
2914
+
2915
+ def tick_values(self, vmin, vmax):
2916
+ # dummy axis has no axes attribute
2917
+ if hasattr(self.axis, "axes") and self.axis.axes.name == "polar":
2918
+ raise NotImplementedError("Polar axis cannot be logit scaled yet")
2919
+
2920
+ if self._nbins == "auto":
2921
+ if self.axis is not None:
2922
+ nbins = self.axis.get_tick_space()
2923
+ if nbins < 2:
2924
+ nbins = 2
2925
+ else:
2926
+ nbins = 9
2927
+ else:
2928
+ nbins = self._nbins
2929
+
2930
+ # We define ideal ticks with their index:
2931
+ # linscale: ... 1e-3 1e-2 1e-1 1/2 1-1e-1 1-1e-2 1-1e-3 ...
2932
+ # b-scale : ... -3 -2 -1 0 1 2 3 ...
2933
+ def ideal_ticks(x):
2934
+ return 10 ** x if x < 0 else 1 - (10 ** (-x)) if x > 0 else 0.5
2935
+
2936
+ vmin, vmax = self.nonsingular(vmin, vmax)
2937
+ binf = int(
2938
+ np.floor(np.log10(vmin))
2939
+ if vmin < 0.5
2940
+ else 0
2941
+ if vmin < 0.9
2942
+ else -np.ceil(np.log10(1 - vmin))
2943
+ )
2944
+ bsup = int(
2945
+ np.ceil(np.log10(vmax))
2946
+ if vmax <= 0.5
2947
+ else 1
2948
+ if vmax <= 0.9
2949
+ else -np.floor(np.log10(1 - vmax))
2950
+ )
2951
+ numideal = bsup - binf - 1
2952
+ if numideal >= 2:
2953
+ # have 2 or more wanted ideal ticks, so use them as major ticks
2954
+ if numideal > nbins:
2955
+ # to many ideal ticks, subsampling ideals for major ticks, and
2956
+ # take others for minor ticks
2957
+ subsampling_factor = math.ceil(numideal / nbins)
2958
+ if self._minor:
2959
+ ticklocs = [
2960
+ ideal_ticks(b)
2961
+ for b in range(binf, bsup + 1)
2962
+ if (b % subsampling_factor) != 0
2963
+ ]
2964
+ else:
2965
+ ticklocs = [
2966
+ ideal_ticks(b)
2967
+ for b in range(binf, bsup + 1)
2968
+ if (b % subsampling_factor) == 0
2969
+ ]
2970
+ return self.raise_if_exceeds(np.array(ticklocs))
2971
+ if self._minor:
2972
+ ticklocs = []
2973
+ for b in range(binf, bsup):
2974
+ if b < -1:
2975
+ ticklocs.extend(np.arange(2, 10) * 10 ** b)
2976
+ elif b == -1:
2977
+ ticklocs.extend(np.arange(2, 5) / 10)
2978
+ elif b == 0:
2979
+ ticklocs.extend(np.arange(6, 9) / 10)
2980
+ else:
2981
+ ticklocs.extend(
2982
+ 1 - np.arange(2, 10)[::-1] * 10 ** (-b - 1)
2983
+ )
2984
+ return self.raise_if_exceeds(np.array(ticklocs))
2985
+ ticklocs = [ideal_ticks(b) for b in range(binf, bsup + 1)]
2986
+ return self.raise_if_exceeds(np.array(ticklocs))
2987
+ # the scale is zoomed so same ticks as linear scale can be used
2988
+ if self._minor:
2989
+ return []
2990
+ return super().tick_values(vmin, vmax)
2991
+
2992
+ def nonsingular(self, vmin, vmax):
2993
+ standard_minpos = 1e-7
2994
+ initial_range = (standard_minpos, 1 - standard_minpos)
2995
+ if vmin > vmax:
2996
+ vmin, vmax = vmax, vmin
2997
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
2998
+ vmin, vmax = initial_range # Initial range, no data plotted yet.
2999
+ elif vmax <= 0 or vmin >= 1:
3000
+ # vmax <= 0 occurs when all values are negative
3001
+ # vmin >= 1 occurs when all values are greater than one
3002
+ _api.warn_external(
3003
+ "Data has no values between 0 and 1, and therefore cannot be "
3004
+ "logit-scaled."
3005
+ )
3006
+ vmin, vmax = initial_range
3007
+ else:
3008
+ minpos = (
3009
+ self.axis.get_minpos()
3010
+ if self.axis is not None
3011
+ else standard_minpos
3012
+ )
3013
+ if not np.isfinite(minpos):
3014
+ minpos = standard_minpos # This should never take effect.
3015
+ if vmin <= 0:
3016
+ vmin = minpos
3017
+ # NOTE: for vmax, we should query a property similar to get_minpos,
3018
+ # but related to the maximal, less-than-one data point.
3019
+ # Unfortunately, Bbox._minpos is defined very deep in the BBox and
3020
+ # updated with data, so for now we use 1 - minpos as a substitute.
3021
+ if vmax >= 1:
3022
+ vmax = 1 - minpos
3023
+ if vmin == vmax:
3024
+ vmin, vmax = 0.1 * vmin, 1 - 0.1 * vmin
3025
+
3026
+ return vmin, vmax
3027
+
3028
+
3029
+ class AutoLocator(MaxNLocator):
3030
+ """
3031
+ Place evenly spaced ticks, with the step size and maximum number of ticks chosen
3032
+ automatically.
3033
+
3034
+ This is a subclass of `~matplotlib.ticker.MaxNLocator`, with parameters
3035
+ *nbins = 'auto'* and *steps = [1, 2, 2.5, 5, 10]*.
3036
+ """
3037
+ def __init__(self):
3038
+ """
3039
+ To know the values of the non-public parameters, please have a
3040
+ look to the defaults of `~matplotlib.ticker.MaxNLocator`.
3041
+ """
3042
+ if mpl.rcParams['_internal.classic_mode']:
3043
+ nbins = 9
3044
+ steps = [1, 2, 5, 10]
3045
+ else:
3046
+ nbins = 'auto'
3047
+ steps = [1, 2, 2.5, 5, 10]
3048
+ super().__init__(nbins=nbins, steps=steps)
3049
+
3050
+
3051
+ class AutoMinorLocator(Locator):
3052
+ """
3053
+ Place evenly spaced minor ticks, with the step size and maximum number of ticks
3054
+ chosen automatically.
3055
+
3056
+ The Axis must use a linear scale and have evenly spaced major ticks.
3057
+ """
3058
+
3059
+ def __init__(self, n=None):
3060
+ """
3061
+ Parameters
3062
+ ----------
3063
+ n : int or 'auto', default: :rc:`xtick.minor.ndivs` or :rc:`ytick.minor.ndivs`
3064
+ The number of subdivisions of the interval between major ticks;
3065
+ e.g., n=2 will place a single minor tick midway between major ticks.
3066
+
3067
+ If *n* is 'auto', it will be set to 4 or 5: if the distance
3068
+ between the major ticks equals 1, 2.5, 5 or 10 it can be perfectly
3069
+ divided in 5 equidistant sub-intervals with a length multiple of
3070
+ 0.05; otherwise, it is divided in 4 sub-intervals.
3071
+ """
3072
+ self.ndivs = n
3073
+
3074
+ def __call__(self):
3075
+ # docstring inherited
3076
+ if self.axis.get_scale() == 'log':
3077
+ _api.warn_external('AutoMinorLocator does not work on logarithmic scales')
3078
+ return []
3079
+
3080
+ majorlocs = np.unique(self.axis.get_majorticklocs())
3081
+ if len(majorlocs) < 2:
3082
+ # Need at least two major ticks to find minor tick locations.
3083
+ # TODO: Figure out a way to still be able to display minor ticks with less
3084
+ # than two major ticks visible. For now, just display no ticks at all.
3085
+ return []
3086
+ majorstep = majorlocs[1] - majorlocs[0]
3087
+
3088
+ if self.ndivs is None:
3089
+ self.ndivs = mpl.rcParams[
3090
+ 'ytick.minor.ndivs' if self.axis.axis_name == 'y'
3091
+ else 'xtick.minor.ndivs'] # for x and z axis
3092
+
3093
+ if self.ndivs == 'auto':
3094
+ majorstep_mantissa = 10 ** (np.log10(majorstep) % 1)
3095
+ ndivs = 5 if np.isclose(majorstep_mantissa, [1, 2.5, 5, 10]).any() else 4
3096
+ else:
3097
+ ndivs = self.ndivs
3098
+
3099
+ minorstep = majorstep / ndivs
3100
+
3101
+ vmin, vmax = sorted(self.axis.get_view_interval())
3102
+ t0 = majorlocs[0]
3103
+ tmin = round((vmin - t0) / minorstep)
3104
+ tmax = round((vmax - t0) / minorstep) + 1
3105
+ locs = (np.arange(tmin, tmax) * minorstep) + t0
3106
+
3107
+ return self.raise_if_exceeds(locs)
3108
+
3109
+ def tick_values(self, vmin, vmax):
3110
+ raise NotImplementedError(
3111
+ f"Cannot get tick locations for a {type(self).__name__}")