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
matplotlib_rs/dates.py ADDED
@@ -0,0 +1,1847 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ Matplotlib provides sophisticated date plotting capabilities, standing on the
4
+ shoulders of python :mod:`datetime` and the add-on module dateutil_.
5
+
6
+ By default, Matplotlib uses the units machinery described in
7
+ `~matplotlib.units` to convert `datetime.datetime`, and `numpy.datetime64`
8
+ objects when plotted on an x- or y-axis. The user does not
9
+ need to do anything for dates to be formatted, but dates often have strict
10
+ formatting needs, so this module provides many tick locators and formatters.
11
+ A basic example using `numpy.datetime64` is::
12
+
13
+ import numpy as np
14
+
15
+ times = np.arange(np.datetime64('2001-01-02'),
16
+ np.datetime64('2002-02-03'), np.timedelta64(75, 'm'))
17
+ y = np.random.randn(len(times))
18
+
19
+ fig, ax = plt.subplots()
20
+ ax.plot(times, y)
21
+
22
+ .. seealso::
23
+
24
+ - :doc:`/gallery/ticks/date`
25
+ - :doc:`/gallery/ticks/date_concise_formatter`
26
+ - :doc:`/gallery/ticks/date_demo_convert`
27
+
28
+ .. _date-format:
29
+
30
+ Matplotlib date format
31
+ ----------------------
32
+
33
+ Matplotlib represents dates using floating point numbers specifying the number
34
+ of days since a default epoch of 1970-01-01 UTC; for example,
35
+ 1970-01-01, 06:00 is the floating point number 0.25. The formatters and
36
+ locators require the use of `datetime.datetime` objects, so only dates between
37
+ year 0001 and 9999 can be represented. Microsecond precision
38
+ is achievable for (approximately) 70 years on either side of the epoch, and
39
+ 20 microseconds for the rest of the allowable range of dates (year 0001 to
40
+ 9999). The epoch can be changed at import time via `.dates.set_epoch` or
41
+ :rc:`date.epoch` to other dates if necessary; see
42
+ :doc:`/gallery/ticks/date_precision_and_epochs` for a discussion.
43
+
44
+ .. note::
45
+
46
+ Before Matplotlib 3.3, the epoch was 0000-12-31 which lost modern
47
+ microsecond precision and also made the default axis limit of 0 an invalid
48
+ datetime. In 3.3 the epoch was changed as above. To convert old
49
+ ordinal floats to the new epoch, users can do::
50
+
51
+ new_ordinal = old_ordinal + mdates.date2num(np.datetime64('0000-12-31'))
52
+
53
+
54
+ There are a number of helper functions to convert between :mod:`datetime`
55
+ objects and Matplotlib dates:
56
+
57
+ .. currentmodule:: matplotlib.dates
58
+
59
+ .. autosummary::
60
+ :nosignatures:
61
+
62
+ datestr2num
63
+ date2num
64
+ num2date
65
+ num2timedelta
66
+ drange
67
+ set_epoch
68
+ get_epoch
69
+
70
+ .. note::
71
+
72
+ Like Python's `datetime.datetime`, Matplotlib uses the Gregorian calendar
73
+ for all conversions between dates and floating point numbers. This practice
74
+ is not universal, and calendar differences can cause confusing
75
+ differences between what Python and Matplotlib give as the number of days
76
+ since 0001-01-01 and what other software and databases yield. For
77
+ example, the US Naval Observatory uses a calendar that switches
78
+ from Julian to Gregorian in October, 1582. Hence, using their
79
+ calculator, the number of days between 0001-01-01 and 2006-04-01 is
80
+ 732403, whereas using the Gregorian calendar via the datetime
81
+ module we find::
82
+
83
+ In [1]: date(2006, 4, 1).toordinal() - date(1, 1, 1).toordinal()
84
+ Out[1]: 732401
85
+
86
+ All the Matplotlib date converters, locators and formatters are timezone aware.
87
+ If no explicit timezone is provided, :rc:`timezone` is assumed, provided as a
88
+ string. If you want to use a different timezone, pass the *tz* keyword
89
+ argument of `num2date` to any date tick locators or formatters you create. This
90
+ can be either a `datetime.tzinfo` instance or a string with the timezone name
91
+ that can be parsed by `~dateutil.tz.gettz`.
92
+
93
+ A wide range of specific and general purpose date tick locators and
94
+ formatters are provided in this module. See
95
+ :mod:`matplotlib.ticker` for general information on tick locators
96
+ and formatters. These are described below.
97
+
98
+ The dateutil_ module provides additional code to handle date ticking, making it
99
+ easy to place ticks on any kinds of dates. See examples below.
100
+
101
+ .. _dateutil: https://dateutil.readthedocs.io
102
+
103
+ .. _date-locators:
104
+
105
+ Date tick locators
106
+ ------------------
107
+
108
+ Most of the date tick locators can locate single or multiple ticks. For example::
109
+
110
+ # import constants for the days of the week
111
+ from matplotlib_rs.dates import MO, TU, WE, TH, FR, SA, SU
112
+
113
+ # tick on Mondays every week
114
+ loc = WeekdayLocator(byweekday=MO, tz=tz)
115
+
116
+ # tick on Mondays and Saturdays
117
+ loc = WeekdayLocator(byweekday=(MO, SA))
118
+
119
+ In addition, most of the constructors take an interval argument::
120
+
121
+ # tick on Mondays every second week
122
+ loc = WeekdayLocator(byweekday=MO, interval=2)
123
+
124
+ The rrule locator allows completely general date ticking::
125
+
126
+ # tick every 5th easter
127
+ rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
128
+ loc = RRuleLocator(rule)
129
+
130
+ The available date tick locators are:
131
+
132
+ * `MicrosecondLocator`: Locate microseconds.
133
+
134
+ * `SecondLocator`: Locate seconds.
135
+
136
+ * `MinuteLocator`: Locate minutes.
137
+
138
+ * `HourLocator`: Locate hours.
139
+
140
+ * `DayLocator`: Locate specified days of the month.
141
+
142
+ * `WeekdayLocator`: Locate days of the week, e.g., MO, TU.
143
+
144
+ * `MonthLocator`: Locate months, e.g., 7 for July.
145
+
146
+ * `YearLocator`: Locate years that are multiples of base.
147
+
148
+ * `RRuleLocator`: Locate using a `rrulewrapper`.
149
+ `rrulewrapper` is a simple wrapper around dateutil_'s `dateutil.rrule`
150
+ which allow almost arbitrary date tick specifications.
151
+ See :doc:`rrule example </gallery/ticks/date_demo_rrule>`.
152
+
153
+ * `AutoDateLocator`: On autoscale, this class picks the best `DateLocator`
154
+ (e.g., `RRuleLocator`) to set the view limits and the tick locations. If
155
+ called with ``interval_multiples=True`` it will make ticks line up with
156
+ sensible multiples of the tick intervals. For example, if the interval is
157
+ 4 hours, it will pick hours 0, 4, 8, etc. as ticks. This behaviour is not
158
+ guaranteed by default.
159
+
160
+ .. _date-formatters:
161
+
162
+ Date formatters
163
+ ---------------
164
+
165
+ The available date formatters are:
166
+
167
+ * `AutoDateFormatter`: attempts to figure out the best format to use. This is
168
+ most useful when used with the `AutoDateLocator`.
169
+
170
+ * `ConciseDateFormatter`: also attempts to figure out the best format to use,
171
+ and to make the format as compact as possible while still having complete
172
+ date information. This is most useful when used with the `AutoDateLocator`.
173
+
174
+ * `DateFormatter`: use `~datetime.datetime.strftime` format strings.
175
+ """
176
+
177
+ import datetime
178
+ import functools
179
+ import logging
180
+ import re
181
+
182
+ # dateutil is vendored: matplotlib_rs needs only NumPy.
183
+ from matplotlib_rs._vendor.dateutil.rrule import (
184
+ rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
185
+ MINUTELY, SECONDLY)
186
+ from matplotlib_rs._vendor.dateutil.relativedelta import relativedelta
187
+ from matplotlib_rs._vendor import dateutil
188
+ import matplotlib_rs._vendor.dateutil.parser
189
+ import matplotlib_rs._vendor.dateutil.tz
190
+ import numpy as np
191
+
192
+ import matplotlib_rs as mpl
193
+ from matplotlib_rs import _api, cbook, ticker, units
194
+
195
+ __all__ = ('datestr2num', 'date2num', 'num2date', 'num2timedelta', 'drange',
196
+ 'set_epoch', 'get_epoch', 'DateFormatter', 'ConciseDateFormatter',
197
+ 'AutoDateFormatter', 'DateLocator', 'RRuleLocator',
198
+ 'AutoDateLocator', 'YearLocator', 'MonthLocator', 'WeekdayLocator',
199
+ 'DayLocator', 'HourLocator', 'MinuteLocator',
200
+ 'SecondLocator', 'MicrosecondLocator',
201
+ 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',
202
+ 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
203
+ 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',
204
+ 'DateConverter', 'ConciseDateConverter', 'rrulewrapper')
205
+
206
+
207
+ _log = logging.getLogger(__name__)
208
+ UTC = datetime.timezone.utc
209
+
210
+
211
+ def _get_tzinfo(tz=None):
212
+ """
213
+ Generate `~datetime.tzinfo` from a string or return `~datetime.tzinfo`.
214
+ If None, retrieve the preferred timezone from the rcParams dictionary.
215
+ """
216
+ tz = mpl._val_or_rc(tz, 'timezone')
217
+ if tz == 'UTC':
218
+ return UTC
219
+ if isinstance(tz, str):
220
+ tzinfo = dateutil.tz.gettz(tz)
221
+ if tzinfo is None:
222
+ raise ValueError(f"{tz} is not a valid timezone as parsed by"
223
+ " dateutil.tz.gettz.")
224
+ return tzinfo
225
+ if isinstance(tz, datetime.tzinfo):
226
+ return tz
227
+ raise TypeError(f"tz must be string or tzinfo subclass, not {tz!r}.")
228
+
229
+
230
+ # Time-related constants.
231
+ EPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())
232
+ # EPOCH_OFFSET is not used by matplotlib
233
+ MICROSECONDLY = SECONDLY + 1
234
+ HOURS_PER_DAY = 24.
235
+ MIN_PER_HOUR = 60.
236
+ SEC_PER_MIN = 60.
237
+ MONTHS_PER_YEAR = 12.
238
+
239
+ DAYS_PER_WEEK = 7.
240
+ DAYS_PER_MONTH = 30.
241
+ DAYS_PER_YEAR = 365.0
242
+
243
+ MINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY
244
+
245
+ SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
246
+ SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
247
+ SEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK
248
+
249
+ MUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY
250
+
251
+ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
252
+ MO, TU, WE, TH, FR, SA, SU)
253
+ WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
254
+
255
+ # default epoch: passed to np.datetime64...
256
+ _epoch = None
257
+
258
+
259
+ def _reset_epoch_test_example():
260
+ """
261
+ Reset the Matplotlib date epoch so it can be set again.
262
+
263
+ Only for use in tests and examples.
264
+ """
265
+ global _epoch
266
+ _epoch = None
267
+
268
+
269
+ def set_epoch(epoch):
270
+ """
271
+ Set the epoch (origin for dates) for datetime calculations.
272
+
273
+ The default epoch is :rc:`date.epoch`.
274
+
275
+ If microsecond accuracy is desired, the date being plotted needs to be
276
+ within approximately 70 years of the epoch. Matplotlib internally
277
+ represents dates as days since the epoch, so floating point dynamic
278
+ range needs to be within a factor of 2^52.
279
+
280
+ `~.dates.set_epoch` must be called before any dates are converted
281
+ (i.e. near the import section) or a RuntimeError will be raised.
282
+
283
+ See also :doc:`/gallery/ticks/date_precision_and_epochs`.
284
+
285
+ Parameters
286
+ ----------
287
+ epoch : str
288
+ valid UTC date parsable by `numpy.datetime64` (do not include
289
+ timezone).
290
+
291
+ """
292
+ global _epoch
293
+ if _epoch is not None:
294
+ raise RuntimeError('set_epoch must be called before dates plotted.')
295
+ _epoch = epoch
296
+
297
+
298
+ def get_epoch():
299
+ """
300
+ Get the epoch used by `.dates`.
301
+
302
+ Returns
303
+ -------
304
+ epoch : str
305
+ String for the epoch (parsable by `numpy.datetime64`).
306
+ """
307
+ global _epoch
308
+
309
+ _epoch = mpl._val_or_rc(_epoch, 'date.epoch')
310
+ return _epoch
311
+
312
+
313
+ def _dt64_to_ordinalf(d):
314
+ """
315
+ Convert a `numpy.ndarray` of np.datetime64 to
316
+ Gregorian date as UTC float relative to the epoch (see `.get_epoch`).
317
+ Roundoff is float64 precision. Practically: microseconds for dates
318
+ between 290301 BC, 294241 AD, milliseconds for larger dates
319
+ (see `numpy.datetime64`).
320
+ """
321
+
322
+ # the "extra" ensures that we at least allow the dynamic range out to
323
+ # seconds. That should get out to +/-2e11 years.
324
+ dseconds = d.astype('datetime64[s]')
325
+ extra = (d - dseconds).astype('timedelta64[ns]')
326
+ t0 = np.datetime64(get_epoch(), 's')
327
+ dt = (dseconds - t0).astype(np.float64)
328
+ dt += extra.astype(np.float64) / 1.0e9
329
+ dt = dt / SEC_PER_DAY
330
+
331
+ dt[np.isnat(d)] = np.nan
332
+ return dt
333
+
334
+
335
+ def _from_ordinalf(x, tz=None):
336
+ """
337
+ Convert Gregorian float of the date, preserving hours, minutes,
338
+ seconds and microseconds. Return value is a `.datetime`.
339
+
340
+ The input date *x* is a float in ordinal days at UTC, and the output will
341
+ be the specified `.datetime` object corresponding to that time in
342
+ timezone *tz*, or if *tz* is ``None``, in the timezone specified in
343
+ :rc:`timezone`.
344
+ """
345
+
346
+ tz = _get_tzinfo(tz)
347
+
348
+ dt = (np.datetime64(get_epoch()) +
349
+ np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us'))
350
+ if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'):
351
+ raise ValueError(f'Date ordinal {x} converts to {dt} (using '
352
+ f'epoch {get_epoch()}), but Matplotlib dates must be '
353
+ 'between year 0001 and 9999.')
354
+ # convert from datetime64 to datetime:
355
+ dt = dt.tolist()
356
+
357
+ # datetime64 is always UTC:
358
+ dt = dt.replace(tzinfo=dateutil.tz.gettz('UTC'))
359
+ # but maybe we are working in a different timezone so move.
360
+ dt = dt.astimezone(tz)
361
+ # fix round off errors
362
+ if np.abs(x) > 70 * 365:
363
+ # if x is big, round off to nearest twenty microseconds.
364
+ # This avoids floating point roundoff error
365
+ ms = round(dt.microsecond / 20) * 20
366
+ if ms == 1000000:
367
+ dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
368
+ else:
369
+ dt = dt.replace(microsecond=ms)
370
+
371
+ return dt
372
+
373
+
374
+ # a version of _from_ordinalf that can operate on numpy arrays
375
+ _from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O")
376
+ # a version of dateutil.parser.parse that can operate on numpy arrays
377
+ _dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)
378
+
379
+
380
+ def datestr2num(d, default=None):
381
+ """
382
+ Convert a date string to a datenum using `dateutil.parser.parse`.
383
+
384
+ Parameters
385
+ ----------
386
+ d : str or sequence of str
387
+ The dates to convert.
388
+
389
+ default : datetime.datetime, optional
390
+ The default date to use when fields are missing in *d*.
391
+ """
392
+ if isinstance(d, str):
393
+ dt = dateutil.parser.parse(d, default=default)
394
+ return date2num(dt)
395
+ else:
396
+ if default is not None:
397
+ d = [date2num(dateutil.parser.parse(s, default=default))
398
+ for s in d]
399
+ return np.asarray(d)
400
+ d = np.asarray(d)
401
+ if not d.size:
402
+ return d
403
+ return date2num(_dateutil_parser_parse_np_vectorized(d))
404
+
405
+
406
+ def date2num(d):
407
+ """
408
+ Convert datetime objects to Matplotlib dates.
409
+
410
+ Parameters
411
+ ----------
412
+ d : `datetime.datetime` or `numpy.datetime64` or sequences of these
413
+
414
+ Returns
415
+ -------
416
+ float or sequence of floats
417
+ Number of days since the epoch. See `.get_epoch` for the
418
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`. If
419
+ the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970
420
+ ("1970-01-01T12:00:00") returns 0.5.
421
+
422
+ Notes
423
+ -----
424
+ The Gregorian calendar is assumed; this is not universal practice.
425
+ For details see the module docstring.
426
+ """
427
+ # Unpack in case of e.g. Pandas or xarray object
428
+ d = cbook._unpack_to_numpy(d)
429
+
430
+ # make an iterable, but save state to unpack later:
431
+ iterable = np.iterable(d)
432
+ if not iterable:
433
+ d = [d]
434
+
435
+ masked = np.ma.is_masked(d)
436
+ mask = np.ma.getmask(d)
437
+ d = np.asarray(d)
438
+
439
+ # convert to datetime64 arrays, if not already:
440
+ if not np.issubdtype(d.dtype, np.datetime64):
441
+ # datetime arrays
442
+ if not d.size:
443
+ # deals with an empty array...
444
+ return d
445
+ tzi = getattr(d[0], 'tzinfo', None)
446
+ if tzi is not None:
447
+ # make datetime naive:
448
+ d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]
449
+ d = np.asarray(d)
450
+ d = d.astype('datetime64[us]')
451
+
452
+ d = np.ma.masked_array(d, mask=mask) if masked else d
453
+ d = _dt64_to_ordinalf(d)
454
+
455
+ return d if iterable else d[0]
456
+
457
+
458
+ def num2date(x, tz=None):
459
+ """
460
+ Convert Matplotlib dates to `~datetime.datetime` objects.
461
+
462
+ Parameters
463
+ ----------
464
+ x : float or sequence of floats
465
+ Number of days (fraction part represents hours, minutes, seconds)
466
+ since the epoch. See `.get_epoch` for the
467
+ epoch, which can be changed by :rc:`date.epoch` or `.set_epoch`.
468
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
469
+ Timezone of *x*. If a string, *tz* is passed to `dateutil.tz`.
470
+
471
+ Returns
472
+ -------
473
+ `~datetime.datetime` or sequence of `~datetime.datetime`
474
+ Dates are returned in timezone *tz*.
475
+
476
+ If *x* is a sequence, a sequence of `~datetime.datetime` objects will
477
+ be returned.
478
+
479
+ Notes
480
+ -----
481
+ The Gregorian calendar is assumed; this is not universal practice.
482
+ For details, see the module docstring.
483
+ """
484
+ tz = _get_tzinfo(tz)
485
+ return _from_ordinalf_np_vectorized(x, tz).tolist()
486
+
487
+
488
+ _ordinalf_to_timedelta_np_vectorized = np.vectorize(
489
+ lambda x: datetime.timedelta(days=x), otypes="O")
490
+
491
+
492
+ def num2timedelta(x):
493
+ """
494
+ Convert number of days to a `~datetime.timedelta` object.
495
+
496
+ If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
497
+ be returned.
498
+
499
+ Parameters
500
+ ----------
501
+ x : float, sequence of floats
502
+ Number of days. The fraction part represents hours, minutes, seconds.
503
+
504
+ Returns
505
+ -------
506
+ `datetime.timedelta` or list[`datetime.timedelta`]
507
+ """
508
+ return _ordinalf_to_timedelta_np_vectorized(x).tolist()
509
+
510
+
511
+ def drange(dstart, dend, delta):
512
+ """
513
+ Return a sequence of equally spaced Matplotlib dates.
514
+
515
+ The dates start at *dstart* and reach up to, but not including *dend*.
516
+ They are spaced by *delta*.
517
+
518
+ Parameters
519
+ ----------
520
+ dstart, dend : `~datetime.datetime`
521
+ The date limits.
522
+ delta : `datetime.timedelta`
523
+ Spacing of the dates.
524
+
525
+ Returns
526
+ -------
527
+ `numpy.array`
528
+ A list floats representing Matplotlib dates.
529
+
530
+ """
531
+ f1 = date2num(dstart)
532
+ f2 = date2num(dend)
533
+ step = delta.total_seconds() / SEC_PER_DAY
534
+
535
+ # calculate the difference between dend and dstart in times of delta
536
+ num = int(np.ceil((f2 - f1) / step))
537
+
538
+ # calculate end of the interval which will be generated
539
+ dinterval_end = dstart + num * delta
540
+
541
+ # ensure, that a half open interval will be generated [dstart, dend)
542
+ if dinterval_end >= dend:
543
+ # if the endpoint is greater than or equal to dend,
544
+ # just subtract one delta
545
+ dinterval_end -= delta
546
+ num -= 1
547
+
548
+ f2 = date2num(dinterval_end) # new float-endpoint
549
+ return np.linspace(f1, f2, num + 1)
550
+
551
+
552
+ def _wrap_in_tex(text):
553
+ p = r'([a-zA-Z]+)'
554
+ ret_text = re.sub(p, r'}$\1$\\mathdefault{', text)
555
+
556
+ # Braces ensure symbols are not spaced like binary operators.
557
+ ret_text = ret_text.replace('-', '{-}').replace(':', '{:}')
558
+ # To not concatenate space between numbers.
559
+ ret_text = ret_text.replace(' ', r'\;')
560
+ ret_text = '$\\mathdefault{' + ret_text + '}$'
561
+ ret_text = ret_text.replace('$\\mathdefault{}$', '')
562
+ return ret_text
563
+
564
+
565
+ ## date tick locators and formatters ###
566
+
567
+
568
+ class DateFormatter(ticker.Formatter):
569
+ """
570
+ Format a tick (in days since the epoch) with a
571
+ `~datetime.datetime.strftime` format string.
572
+ """
573
+
574
+ def __init__(self, fmt, tz=None, *, usetex=None):
575
+ """
576
+ Parameters
577
+ ----------
578
+ fmt : str
579
+ `~datetime.datetime.strftime` format string
580
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
581
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
582
+ usetex : bool, default: :rc:`text.usetex`
583
+ To enable/disable the use of TeX's math mode for rendering the
584
+ results of the formatter.
585
+ """
586
+ self.tz = _get_tzinfo(tz)
587
+ self.fmt = fmt
588
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
589
+
590
+ def __call__(self, x, pos=0):
591
+ result = num2date(x, self.tz).strftime(self.fmt)
592
+ return _wrap_in_tex(result) if self._usetex else result
593
+
594
+ def set_tzinfo(self, tz):
595
+ self.tz = _get_tzinfo(tz)
596
+
597
+
598
+ class ConciseDateFormatter(ticker.Formatter):
599
+ """
600
+ A `.Formatter` which attempts to figure out the best format to use for the
601
+ date, and to make it as compact as possible, but still be complete. This is
602
+ most useful when used with the `AutoDateLocator`::
603
+
604
+ >>> locator = AutoDateLocator()
605
+ >>> formatter = ConciseDateFormatter(locator)
606
+
607
+ Parameters
608
+ ----------
609
+ locator : `.ticker.Locator`
610
+ Locator that this axis is using.
611
+
612
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
613
+ Ticks timezone, passed to `.dates.num2date`.
614
+
615
+ formats : list of 6 strings, optional
616
+ Format strings for 6 levels of tick labelling: mostly years,
617
+ months, days, hours, minutes, and seconds. Strings use
618
+ the same format codes as `~datetime.datetime.strftime`. Default is
619
+ ``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
620
+
621
+ zero_formats : list of 6 strings, optional
622
+ Format strings for tick labels that are "zeros" for a given tick
623
+ level. For instance, if most ticks are months, ticks around 1 Jan 2005
624
+ will be labeled "Dec", "2005", "Feb". The default is
625
+ ``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
626
+
627
+ offset_formats : list of 6 strings, optional
628
+ Format strings for the 6 levels that is applied to the "offset"
629
+ string found on the right side of an x-axis, or top of a y-axis.
630
+ Combined with the tick labels this should completely specify the
631
+ date. The default is::
632
+
633
+ ['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
634
+
635
+ show_offset : bool, default: True
636
+ Whether to show the offset or not.
637
+
638
+ usetex : bool, default: :rc:`text.usetex`
639
+ To enable/disable the use of TeX's math mode for rendering the results
640
+ of the formatter.
641
+
642
+ Examples
643
+ --------
644
+ See :doc:`/gallery/ticks/date_concise_formatter`
645
+
646
+ .. plot::
647
+
648
+ import datetime
649
+ import matplotlib_rs.dates as mdates
650
+
651
+ base = datetime.datetime(2005, 2, 1)
652
+ dates = np.array([base + datetime.timedelta(hours=(2 * i))
653
+ for i in range(732)])
654
+ N = len(dates)
655
+ np.random.seed(19680801)
656
+ y = np.cumsum(np.random.randn(N))
657
+
658
+ fig, ax = plt.subplots(constrained_layout=True)
659
+ locator = mdates.AutoDateLocator()
660
+ formatter = mdates.ConciseDateFormatter(locator)
661
+ ax.xaxis.set_major_locator(locator)
662
+ ax.xaxis.set_major_formatter(formatter)
663
+
664
+ ax.plot(dates, y)
665
+ ax.set_title('Concise Date Formatter')
666
+
667
+ """
668
+
669
+ offset_string = _api.deprecate_privatize_attribute(
670
+ "3.11", alternative="get_offset()"
671
+ )
672
+
673
+ def __init__(self, locator, tz=None, formats=None, offset_formats=None,
674
+ zero_formats=None, show_offset=True, *, usetex=None):
675
+ """
676
+ Autoformat the date labels. The default format is used to form an
677
+ initial string, and then redundant elements are removed.
678
+ """
679
+ self._locator = locator
680
+ self._tz = tz
681
+ self.defaultfmt = '%Y'
682
+ # there are 6 levels with each level getting a specific format
683
+ # 0: mostly years, 1: months, 2: days,
684
+ # 3: hours, 4: minutes, 5: seconds
685
+ if formats:
686
+ if len(formats) != 6:
687
+ raise ValueError('formats argument must be a list of '
688
+ '6 format strings (or None)')
689
+ self.formats = formats
690
+ else:
691
+ self.formats = ['%Y', # ticks are mostly years
692
+ '%b', # ticks are mostly months
693
+ '%d', # ticks are mostly days
694
+ '%H:%M', # hrs
695
+ '%H:%M', # min
696
+ '%S.%f', # secs
697
+ ]
698
+ # fmt for zeros ticks at this level. These are
699
+ # ticks that should be labeled w/ info the level above.
700
+ # like 1 Jan can just be labelled "Jan". 02:02:00 can
701
+ # just be labeled 02:02.
702
+ if zero_formats:
703
+ if len(zero_formats) != 6:
704
+ raise ValueError('zero_formats argument must be a list of '
705
+ '6 format strings (or None)')
706
+ self.zero_formats = zero_formats
707
+ elif formats:
708
+ # use the users formats for the zero tick formats
709
+ self.zero_formats = [''] + self.formats[:-1]
710
+ else:
711
+ # make the defaults a bit nicer:
712
+ self.zero_formats = [''] + self.formats[:-1]
713
+ self.zero_formats[3] = '%b-%d'
714
+
715
+ if offset_formats:
716
+ if len(offset_formats) != 6:
717
+ raise ValueError('offset_formats argument must be a list of '
718
+ '6 format strings (or None)')
719
+ self.offset_formats = offset_formats
720
+ else:
721
+ self.offset_formats = ['',
722
+ '%Y',
723
+ '%Y-%b',
724
+ '%Y-%b-%d',
725
+ '%Y-%b-%d',
726
+ '%Y-%b-%d %H:%M']
727
+ self._offset_string = ''
728
+ self.show_offset = show_offset
729
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
730
+
731
+ def __call__(self, x, pos=None):
732
+ formatter = DateFormatter(self.defaultfmt, self._tz,
733
+ usetex=self._usetex)
734
+ return formatter(x, pos=pos)
735
+
736
+ def format_ticks(self, values):
737
+ tickdatetime = [num2date(value, tz=self._tz) for value in values]
738
+ tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
739
+
740
+ # basic algorithm:
741
+ # 1) only display a part of the date if it changes over the ticks.
742
+ # 2) don't display the smaller part of the date if:
743
+ # it is always the same or if it is the start of the
744
+ # year, month, day etc.
745
+ # fmt for most ticks at this level
746
+ fmts = self.formats
747
+ # format beginnings of days, months, years, etc.
748
+ zerofmts = self.zero_formats
749
+ # offset fmt are for the offset in the upper left of the
750
+ # or lower right of the axis.
751
+ offsetfmts = self.offset_formats
752
+ show_offset = self.show_offset
753
+
754
+ # determine the level we will label at:
755
+ # mostly 0: years, 1: months, 2: days,
756
+ # 3: hours, 4: minutes, 5: seconds, 6: microseconds
757
+ for level in range(5, -1, -1):
758
+ unique = np.unique(tickdate[:, level])
759
+ if len(unique) > 1:
760
+ # if 1 is included in unique, the year is shown in ticks
761
+ if level < 2 and np.any(unique == 1):
762
+ show_offset = False
763
+ break
764
+ elif level == 0:
765
+ # all tickdate are the same, so only micros might be different
766
+ # set to the most precise (6: microseconds doesn't exist...)
767
+ level = 5
768
+
769
+ # level is the basic level we will label at.
770
+ # now loop through and decide the actual ticklabels
771
+ zerovals = [0, 1, 1, 0, 0, 0, 0]
772
+ labels = [''] * len(tickdate)
773
+ for nn in range(len(tickdate)):
774
+ if level < 5:
775
+ if tickdate[nn][level] == zerovals[level]:
776
+ fmt = zerofmts[level]
777
+ else:
778
+ fmt = fmts[level]
779
+ else:
780
+ # special handling for seconds + microseconds
781
+ if (tickdatetime[nn].second == tickdatetime[nn].microsecond
782
+ == 0):
783
+ fmt = zerofmts[level]
784
+ else:
785
+ fmt = fmts[level]
786
+ labels[nn] = tickdatetime[nn].strftime(fmt)
787
+
788
+ # special handling of seconds and microseconds:
789
+ # strip extra zeros and decimal if possible.
790
+ # this is complicated by two factors. 1) we have some level-4 strings
791
+ # here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
792
+ # same number of decimals for each string (i.e. 0.5 and 1.0).
793
+ if level >= 5:
794
+ trailing_zeros = min(
795
+ (len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
796
+ default=None)
797
+ if trailing_zeros:
798
+ for nn in range(len(labels)):
799
+ if '.' in labels[nn]:
800
+ labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
801
+
802
+ if show_offset:
803
+ # set the offset string:
804
+ if (self._locator.axis and
805
+ self._locator.axis.__name__ in ('xaxis', 'yaxis')
806
+ and self._locator.axis.get_inverted()):
807
+ self._offset_string = tickdatetime[0].strftime(offsetfmts[level])
808
+ else:
809
+ self._offset_string = tickdatetime[-1].strftime(offsetfmts[level])
810
+ if self._usetex:
811
+ self._offset_string = _wrap_in_tex(self._offset_string)
812
+ else:
813
+ self._offset_string = ''
814
+
815
+ if self._usetex:
816
+ return [_wrap_in_tex(l) for l in labels]
817
+ else:
818
+ return labels
819
+
820
+ def get_offset(self):
821
+ return self._offset_string
822
+
823
+ def format_data_short(self, value):
824
+ return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S')
825
+
826
+
827
+ class AutoDateFormatter(ticker.Formatter):
828
+ """
829
+ A `.Formatter` which attempts to figure out the best format to use. This
830
+ is most useful when used with the `AutoDateLocator`.
831
+
832
+ `.AutoDateFormatter` has a ``.scaled`` dictionary that maps tick scales (the
833
+ interval in days between one major tick) to format strings; this dictionary
834
+ defaults to ::
835
+
836
+ self.scaled = {
837
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
838
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
839
+ 1: rcParams['date.autoformatter.day'],
840
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
841
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
842
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
843
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond'],
844
+ }
845
+
846
+ The formatter uses the format string corresponding to the lowest key in
847
+ the dictionary that is greater or equal to the current scale. Dictionary
848
+ entries can be customized::
849
+
850
+ locator = AutoDateLocator()
851
+ formatter = AutoDateFormatter(locator)
852
+ formatter.scaled[1/(24*60)] = '%M:%S' # only show min and sec
853
+
854
+ Custom callables can also be used instead of format strings. The following
855
+ example shows how to use a custom format function to strip trailing zeros
856
+ from decimal seconds and adds the date to the first ticklabel::
857
+
858
+ def my_format_function(x, pos=None):
859
+ x = matplotlib.dates.num2date(x)
860
+ if pos == 0:
861
+ fmt = '%D %H:%M:%S.%f'
862
+ else:
863
+ fmt = '%H:%M:%S.%f'
864
+ label = x.strftime(fmt)
865
+ label = label.rstrip("0")
866
+ label = label.rstrip(".")
867
+ return label
868
+
869
+ formatter.scaled[1/(24*60)] = my_format_function
870
+ """
871
+
872
+ # This can be improved by providing some user-level direction on
873
+ # how to choose the best format (precedence, etc.).
874
+
875
+ # Perhaps a 'struct' that has a field for each time-type where a
876
+ # zero would indicate "don't show" and a number would indicate
877
+ # "show" with some sort of priority. Same priorities could mean
878
+ # show all with the same priority.
879
+
880
+ # Or more simply, perhaps just a format string for each
881
+ # possibility...
882
+
883
+ def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d', *,
884
+ usetex=None):
885
+ """
886
+ Autoformat the date labels.
887
+
888
+ Parameters
889
+ ----------
890
+ locator : `.ticker.Locator`
891
+ Locator that this axis is using.
892
+
893
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
894
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
895
+
896
+ defaultfmt : str
897
+ The default format to use if none of the values in ``self.scaled``
898
+ are greater than the unit returned by ``locator._get_unit()``.
899
+
900
+ usetex : bool, default: :rc:`text.usetex`
901
+ To enable/disable the use of TeX's math mode for rendering the
902
+ results of the formatter. If any entries in ``self.scaled`` are set
903
+ as functions, then it is up to the customized function to enable or
904
+ disable TeX's math mode itself.
905
+ """
906
+ self._locator = locator
907
+ self._tz = tz
908
+ self.defaultfmt = defaultfmt
909
+ self._formatter = DateFormatter(self.defaultfmt, tz)
910
+ rcParams = mpl.rcParams
911
+ self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
912
+ self.scaled = {
913
+ DAYS_PER_YEAR: rcParams['date.autoformatter.year'],
914
+ DAYS_PER_MONTH: rcParams['date.autoformatter.month'],
915
+ 1: rcParams['date.autoformatter.day'],
916
+ 1 / HOURS_PER_DAY: rcParams['date.autoformatter.hour'],
917
+ 1 / MINUTES_PER_DAY: rcParams['date.autoformatter.minute'],
918
+ 1 / SEC_PER_DAY: rcParams['date.autoformatter.second'],
919
+ 1 / MUSECONDS_PER_DAY: rcParams['date.autoformatter.microsecond']
920
+ }
921
+
922
+ def _set_locator(self, locator):
923
+ self._locator = locator
924
+
925
+ def __call__(self, x, pos=None):
926
+ try:
927
+ locator_unit_scale = float(self._locator._get_unit())
928
+ except AttributeError:
929
+ locator_unit_scale = 1
930
+ # Pick the first scale which is greater than the locator unit.
931
+ fmt = next((fmt for scale, fmt in sorted(self.scaled.items())
932
+ if scale >= locator_unit_scale),
933
+ self.defaultfmt)
934
+
935
+ if isinstance(fmt, str):
936
+ self._formatter = DateFormatter(fmt, self._tz, usetex=self._usetex)
937
+ result = self._formatter(x, pos)
938
+ elif callable(fmt):
939
+ result = fmt(x, pos)
940
+ else:
941
+ raise TypeError(f'Unexpected type passed to {self!r}.')
942
+
943
+ return result
944
+
945
+
946
+ class rrulewrapper:
947
+ """
948
+ A simple wrapper around a `dateutil.rrule` allowing flexible
949
+ date tick specifications.
950
+ """
951
+ def __init__(self, freq, tzinfo=None, **kwargs):
952
+ """
953
+ Parameters
954
+ ----------
955
+ freq : {YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY}
956
+ Tick frequency. These constants are defined in `dateutil.rrule`,
957
+ but they are accessible from `matplotlib.dates` as well.
958
+ tzinfo : `datetime.tzinfo`, optional
959
+ Time zone information. The default is None.
960
+ **kwargs
961
+ Additional keyword arguments are passed to the `dateutil.rrule`.
962
+ """
963
+ kwargs['freq'] = freq
964
+ self._base_tzinfo = tzinfo
965
+
966
+ self._update_rrule(**kwargs)
967
+
968
+ def set(self, **kwargs):
969
+ """Set parameters for an existing wrapper."""
970
+ self._construct.update(kwargs)
971
+
972
+ self._update_rrule(**self._construct)
973
+
974
+ def _update_rrule(self, **kwargs):
975
+ tzinfo = self._base_tzinfo
976
+
977
+ # rrule does not play nicely with timezones - especially pytz time
978
+ # zones, it's best to use naive zones and attach timezones once the
979
+ # datetimes are returned
980
+ if 'dtstart' in kwargs:
981
+ dtstart = kwargs['dtstart']
982
+ if dtstart.tzinfo is not None:
983
+ if tzinfo is None:
984
+ tzinfo = dtstart.tzinfo
985
+ else:
986
+ dtstart = dtstart.astimezone(tzinfo)
987
+
988
+ kwargs['dtstart'] = dtstart.replace(tzinfo=None)
989
+
990
+ if 'until' in kwargs:
991
+ until = kwargs['until']
992
+ if until.tzinfo is not None:
993
+ if tzinfo is not None:
994
+ until = until.astimezone(tzinfo)
995
+ else:
996
+ raise ValueError('until cannot be aware if dtstart '
997
+ 'is naive and tzinfo is None')
998
+
999
+ kwargs['until'] = until.replace(tzinfo=None)
1000
+
1001
+ self._construct = kwargs.copy()
1002
+ self._tzinfo = tzinfo
1003
+ self._rrule = rrule(**self._construct)
1004
+
1005
+ def _attach_tzinfo(self, dt, tzinfo):
1006
+ # pytz zones are attached by "localizing" the datetime
1007
+ if hasattr(tzinfo, 'localize'):
1008
+ return tzinfo.localize(dt, is_dst=True)
1009
+
1010
+ return dt.replace(tzinfo=tzinfo)
1011
+
1012
+ def _aware_return_wrapper(self, f, returns_list=False):
1013
+ """Decorator function that allows rrule methods to handle tzinfo."""
1014
+ # This is only necessary if we're actually attaching a tzinfo
1015
+ if self._tzinfo is None:
1016
+ return f
1017
+
1018
+ # All datetime arguments must be naive. If they are not naive, they are
1019
+ # converted to the _tzinfo zone before dropping the zone.
1020
+ def normalize_arg(arg):
1021
+ if isinstance(arg, datetime.datetime) and arg.tzinfo is not None:
1022
+ if arg.tzinfo is not self._tzinfo:
1023
+ arg = arg.astimezone(self._tzinfo)
1024
+
1025
+ return arg.replace(tzinfo=None)
1026
+
1027
+ return arg
1028
+
1029
+ def normalize_args(args, kwargs):
1030
+ args = tuple(normalize_arg(arg) for arg in args)
1031
+ kwargs = {kw: normalize_arg(arg) for kw, arg in kwargs.items()}
1032
+
1033
+ return args, kwargs
1034
+
1035
+ # There are two kinds of functions we care about - ones that return
1036
+ # dates and ones that return lists of dates.
1037
+ if not returns_list:
1038
+ def inner_func(*args, **kwargs):
1039
+ args, kwargs = normalize_args(args, kwargs)
1040
+ dt = f(*args, **kwargs)
1041
+ return self._attach_tzinfo(dt, self._tzinfo)
1042
+ else:
1043
+ def inner_func(*args, **kwargs):
1044
+ args, kwargs = normalize_args(args, kwargs)
1045
+ dts = f(*args, **kwargs)
1046
+ return [self._attach_tzinfo(dt, self._tzinfo) for dt in dts]
1047
+
1048
+ return functools.wraps(f)(inner_func)
1049
+
1050
+ def __getattr__(self, name):
1051
+ if name in self.__dict__:
1052
+ return self.__dict__[name]
1053
+
1054
+ f = getattr(self._rrule, name)
1055
+
1056
+ if name in {'after', 'before'}:
1057
+ return self._aware_return_wrapper(f)
1058
+ elif name in {'xafter', 'xbefore', 'between'}:
1059
+ return self._aware_return_wrapper(f, returns_list=True)
1060
+ else:
1061
+ return f
1062
+
1063
+ def __setstate__(self, state):
1064
+ self.__dict__.update(state)
1065
+
1066
+
1067
+ class DateLocator(ticker.Locator):
1068
+ """
1069
+ Determines the tick locations when plotting dates.
1070
+
1071
+ This class is subclassed by other Locators and
1072
+ is not meant to be used on its own.
1073
+ """
1074
+ hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}
1075
+
1076
+ def __init__(self, tz=None):
1077
+ """
1078
+ Parameters
1079
+ ----------
1080
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1081
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1082
+ """
1083
+ self.tz = _get_tzinfo(tz)
1084
+
1085
+ def set_tzinfo(self, tz):
1086
+ """
1087
+ Set timezone info.
1088
+
1089
+ Parameters
1090
+ ----------
1091
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1092
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1093
+ """
1094
+ self.tz = _get_tzinfo(tz)
1095
+
1096
+ def datalim_to_dt(self):
1097
+ """Convert axis data interval to datetime objects."""
1098
+ dmin, dmax = self.axis.get_data_interval()
1099
+ if dmin > dmax:
1100
+ dmin, dmax = dmax, dmin
1101
+
1102
+ return num2date(dmin, self.tz), num2date(dmax, self.tz)
1103
+
1104
+ def viewlim_to_dt(self):
1105
+ """Convert the view interval to datetime objects."""
1106
+ vmin, vmax = self.axis.get_view_interval()
1107
+ if vmin > vmax:
1108
+ vmin, vmax = vmax, vmin
1109
+ return num2date(vmin, self.tz), num2date(vmax, self.tz)
1110
+
1111
+ def _get_unit(self):
1112
+ """
1113
+ Return how many days a unit of the locator is; used for
1114
+ intelligent autoscaling.
1115
+ """
1116
+ return 1
1117
+
1118
+ def _get_interval(self):
1119
+ """
1120
+ Return the number of units for each tick.
1121
+ """
1122
+ return 1
1123
+
1124
+ def nonsingular(self, vmin, vmax):
1125
+ """
1126
+ Given the proposed upper and lower extent, adjust the range
1127
+ if it is too close to being singular (i.e. a range of ~0).
1128
+ """
1129
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
1130
+ # Except if there is no data, then use 1970 as default.
1131
+ return (date2num(datetime.date(1970, 1, 1)),
1132
+ date2num(datetime.date(1970, 1, 2)))
1133
+ if vmax < vmin:
1134
+ vmin, vmax = vmax, vmin
1135
+ unit = self._get_unit()
1136
+ interval = self._get_interval()
1137
+ if abs(vmax - vmin) < 1e-6:
1138
+ vmin -= 2 * unit * interval
1139
+ vmax += 2 * unit * interval
1140
+ return vmin, vmax
1141
+
1142
+
1143
+ class RRuleLocator(DateLocator):
1144
+ # use the dateutil rrule instance
1145
+
1146
+ def __init__(self, o, tz=None):
1147
+ super().__init__(tz)
1148
+ self.rule = o
1149
+
1150
+ def __call__(self):
1151
+ # if no data have been set, this will tank with a ValueError
1152
+ try:
1153
+ dmin, dmax = self.viewlim_to_dt()
1154
+ except ValueError:
1155
+ return []
1156
+
1157
+ return self.tick_values(dmin, dmax)
1158
+
1159
+ def tick_values(self, vmin, vmax):
1160
+ start, stop = self._create_rrule(vmin, vmax)
1161
+ dates = self.rule.between(start, stop, True)
1162
+ if len(dates) == 0:
1163
+ return date2num([vmin, vmax])
1164
+ return self.raise_if_exceeds(date2num(dates))
1165
+
1166
+ def _create_rrule(self, vmin, vmax):
1167
+ # set appropriate rrule dtstart and until and return
1168
+ # start and end
1169
+ delta = relativedelta(vmax, vmin)
1170
+
1171
+ # We need to cap at the endpoints of valid datetime
1172
+ try:
1173
+ start = vmin - delta
1174
+ except (ValueError, OverflowError):
1175
+ # cap
1176
+ start = datetime.datetime(1, 1, 1, 0, 0, 0,
1177
+ tzinfo=datetime.timezone.utc)
1178
+
1179
+ try:
1180
+ stop = vmax + delta
1181
+ except (ValueError, OverflowError):
1182
+ # cap
1183
+ stop = datetime.datetime(9999, 12, 31, 23, 59, 59,
1184
+ tzinfo=datetime.timezone.utc)
1185
+
1186
+ self.rule.set(dtstart=start, until=stop)
1187
+
1188
+ return vmin, vmax
1189
+
1190
+ def _get_unit(self):
1191
+ # docstring inherited
1192
+ freq = self.rule._rrule._freq
1193
+ return self.get_unit_generic(freq)
1194
+
1195
+ @staticmethod
1196
+ def get_unit_generic(freq):
1197
+ if freq == YEARLY:
1198
+ return DAYS_PER_YEAR
1199
+ elif freq == MONTHLY:
1200
+ return DAYS_PER_MONTH
1201
+ elif freq == WEEKLY:
1202
+ return DAYS_PER_WEEK
1203
+ elif freq == DAILY:
1204
+ return 1.0
1205
+ elif freq == HOURLY:
1206
+ return 1.0 / HOURS_PER_DAY
1207
+ elif freq == MINUTELY:
1208
+ return 1.0 / MINUTES_PER_DAY
1209
+ elif freq == SECONDLY:
1210
+ return 1.0 / SEC_PER_DAY
1211
+ else:
1212
+ # error
1213
+ return -1 # or should this just return '1'?
1214
+
1215
+ def _get_interval(self):
1216
+ return self.rule._rrule._interval
1217
+
1218
+
1219
+ class AutoDateLocator(DateLocator):
1220
+ """
1221
+ On autoscale, this class picks the best `DateLocator` to set the view
1222
+ limits and the tick locations.
1223
+
1224
+ Attributes
1225
+ ----------
1226
+ intervald : dict
1227
+
1228
+ Mapping of tick frequencies to multiples allowed for that ticking.
1229
+ The default is ::
1230
+
1231
+ self.intervald = {
1232
+ YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
1233
+ 1000, 2000, 4000, 5000, 10000],
1234
+ MONTHLY : [1, 2, 3, 4, 6],
1235
+ DAILY : [1, 2, 3, 7, 14, 21],
1236
+ HOURLY : [1, 2, 3, 4, 6, 12],
1237
+ MINUTELY: [1, 5, 10, 15, 30],
1238
+ SECONDLY: [1, 5, 10, 15, 30],
1239
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500,
1240
+ 1000, 2000, 5000, 10000, 20000, 50000,
1241
+ 100000, 200000, 500000, 1000000],
1242
+ }
1243
+
1244
+ where the keys are defined in `dateutil.rrule`.
1245
+
1246
+ The interval is used to specify multiples that are appropriate for
1247
+ the frequency of ticking. For instance, every 7 days is sensible
1248
+ for daily ticks, but for minutes/seconds, 15 or 30 make sense.
1249
+
1250
+ When customizing, you should only modify the values for the existing
1251
+ keys. You should not add or delete entries.
1252
+
1253
+ Example for forcing ticks every 3 hours::
1254
+
1255
+ locator = AutoDateLocator()
1256
+ locator.intervald[HOURLY] = [3] # only show every 3 hours
1257
+ """
1258
+
1259
+ def __init__(self, tz=None, minticks=5, maxticks=None,
1260
+ interval_multiples=True):
1261
+ """
1262
+ Parameters
1263
+ ----------
1264
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1265
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1266
+ minticks : int
1267
+ The minimum number of ticks desired; controls whether ticks occur
1268
+ yearly, monthly, etc.
1269
+ maxticks : int
1270
+ The maximum number of ticks desired; controls the interval between
1271
+ ticks (ticking every other, every 3, etc.). For fine-grained
1272
+ control, this can be a dictionary mapping individual rrule
1273
+ frequency constants (YEARLY, MONTHLY, etc.) to their own maximum
1274
+ number of ticks. This can be used to keep the number of ticks
1275
+ appropriate to the format chosen in `AutoDateFormatter`. Any
1276
+ frequency not specified in this dictionary is given a default
1277
+ value.
1278
+ interval_multiples : bool, default: True
1279
+ Whether ticks should be chosen to be multiple of the interval,
1280
+ locking them to 'nicer' locations. For example, this will force
1281
+ the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done
1282
+ at 6 hour intervals.
1283
+ """
1284
+ super().__init__(tz=tz)
1285
+ self._freq = YEARLY
1286
+ self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY,
1287
+ SECONDLY, MICROSECONDLY]
1288
+ self.minticks = minticks
1289
+
1290
+ self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12,
1291
+ MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8}
1292
+ if maxticks is not None:
1293
+ try:
1294
+ self.maxticks.update(maxticks)
1295
+ except TypeError:
1296
+ # Assume we were given an integer. Use this as the maximum
1297
+ # number of ticks for every frequency and create a
1298
+ # dictionary for this
1299
+ self.maxticks = dict.fromkeys(self._freqs, maxticks)
1300
+ self.interval_multiples = interval_multiples
1301
+ self.intervald = {
1302
+ YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,
1303
+ 1000, 2000, 4000, 5000, 10000],
1304
+ MONTHLY: [1, 2, 3, 4, 6],
1305
+ DAILY: [1, 2, 3, 7, 14, 21],
1306
+ HOURLY: [1, 2, 3, 4, 6, 12],
1307
+ MINUTELY: [1, 5, 10, 15, 30],
1308
+ SECONDLY: [1, 5, 10, 15, 30],
1309
+ MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,
1310
+ 5000, 10000, 20000, 50000, 100000, 200000, 500000,
1311
+ 1000000],
1312
+ }
1313
+ if interval_multiples:
1314
+ # Swap "3" for "4" in the DAILY list; If we use 3 we get bad
1315
+ # tick loc for months w/ 31 days: 1, 4, ..., 28, 31, 1
1316
+ # If we use 4 then we get: 1, 5, ... 25, 29, 1
1317
+ self.intervald[DAILY] = [1, 2, 4, 7, 14]
1318
+
1319
+ self._byranges = [None, range(1, 13), range(1, 32),
1320
+ range(0, 24), range(0, 60), range(0, 60), None]
1321
+
1322
+ def __call__(self):
1323
+ # docstring inherited
1324
+ dmin, dmax = self.viewlim_to_dt()
1325
+ locator = self.get_locator(dmin, dmax)
1326
+ return locator()
1327
+
1328
+ def tick_values(self, vmin, vmax):
1329
+ return self.get_locator(vmin, vmax).tick_values(vmin, vmax)
1330
+
1331
+ def nonsingular(self, vmin, vmax):
1332
+ # whatever is thrown at us, we can scale the unit.
1333
+ # But default nonsingular date plots at an ~4 year period.
1334
+ if not np.isfinite(vmin) or not np.isfinite(vmax):
1335
+ # Except if there is no data, then use 1970 as default.
1336
+ return (date2num(datetime.date(1970, 1, 1)),
1337
+ date2num(datetime.date(1970, 1, 2)))
1338
+ if vmax < vmin:
1339
+ vmin, vmax = vmax, vmin
1340
+ if vmin == vmax:
1341
+ vmin = vmin - DAYS_PER_YEAR * 2
1342
+ vmax = vmax + DAYS_PER_YEAR * 2
1343
+ return vmin, vmax
1344
+
1345
+ def _get_unit(self):
1346
+ if self._freq in [MICROSECONDLY]:
1347
+ return 1. / MUSECONDS_PER_DAY
1348
+ else:
1349
+ return RRuleLocator.get_unit_generic(self._freq)
1350
+
1351
+ def get_locator(self, dmin, dmax):
1352
+ """Pick the best locator based on a distance."""
1353
+ delta = relativedelta(dmax, dmin)
1354
+ tdelta = dmax - dmin
1355
+
1356
+ # take absolute difference
1357
+ if dmin > dmax:
1358
+ delta = -delta
1359
+ tdelta = -tdelta
1360
+ # The following uses a mix of calls to relativedelta and timedelta
1361
+ # methods because there is incomplete overlap in the functionality of
1362
+ # these similar functions, and it's best to avoid doing our own math
1363
+ # whenever possible.
1364
+ numYears = float(delta.years)
1365
+ numMonths = numYears * MONTHS_PER_YEAR + delta.months
1366
+ numDays = tdelta.days # Avoids estimates of days/month, days/year.
1367
+ numHours = numDays * HOURS_PER_DAY + delta.hours
1368
+ numMinutes = numHours * MIN_PER_HOUR + delta.minutes
1369
+ numSeconds = np.floor(tdelta.total_seconds())
1370
+ numMicroseconds = np.floor(tdelta.total_seconds() * 1e6)
1371
+
1372
+ nums = [numYears, numMonths, numDays, numHours, numMinutes,
1373
+ numSeconds, numMicroseconds]
1374
+
1375
+ use_rrule_locator = [True] * 6 + [False]
1376
+
1377
+ # Default setting of bymonth, etc. to pass to rrule
1378
+ # [unused (for year), bymonth, bymonthday, byhour, byminute,
1379
+ # bysecond, unused (for microseconds)]
1380
+ byranges = [None, 1, 1, 0, 0, 0, None]
1381
+
1382
+ # Loop over all the frequencies and try to find one that gives at
1383
+ # least a minticks tick positions. Once this is found, look for
1384
+ # an interval from a list specific to that frequency that gives no
1385
+ # more than maxticks tick positions. Also, set up some ranges
1386
+ # (bymonth, etc.) as appropriate to be passed to rrulewrapper.
1387
+ for i, (freq, num) in enumerate(zip(self._freqs, nums)):
1388
+ # If this particular frequency doesn't give enough ticks, continue
1389
+ if num < self.minticks:
1390
+ # Since we're not using this particular frequency, set
1391
+ # the corresponding by_ to None so the rrule can act as
1392
+ # appropriate
1393
+ byranges[i] = None
1394
+ continue
1395
+
1396
+ # Find the first available interval that doesn't give too many
1397
+ # ticks
1398
+ for interval in self.intervald[freq]:
1399
+ if num <= interval * (self.maxticks[freq] - 1):
1400
+ break
1401
+ else:
1402
+ if not (self.interval_multiples and freq == DAILY):
1403
+ _api.warn_external(
1404
+ f"AutoDateLocator was unable to pick an appropriate "
1405
+ f"interval for this date range. It may be necessary "
1406
+ f"to add an interval value to the AutoDateLocator's "
1407
+ f"intervald dictionary. Defaulting to {interval}.")
1408
+
1409
+ # Set some parameters as appropriate
1410
+ self._freq = freq
1411
+
1412
+ if self._byranges[i] and self.interval_multiples:
1413
+ byranges[i] = self._byranges[i][::interval]
1414
+ if i in (DAILY, WEEKLY):
1415
+ if interval == 14:
1416
+ # just make first and 15th. Avoids 30th.
1417
+ byranges[i] = [1, 15]
1418
+ elif interval == 7:
1419
+ byranges[i] = [1, 8, 15, 22]
1420
+
1421
+ interval = 1
1422
+ else:
1423
+ byranges[i] = self._byranges[i]
1424
+ break
1425
+ else:
1426
+ interval = 1
1427
+
1428
+ if (freq == YEARLY) and self.interval_multiples:
1429
+ locator = YearLocator(interval, tz=self.tz)
1430
+ elif use_rrule_locator[i]:
1431
+ _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges
1432
+ rrule = rrulewrapper(self._freq, interval=interval,
1433
+ dtstart=dmin, until=dmax,
1434
+ bymonth=bymonth, bymonthday=bymonthday,
1435
+ byhour=byhour, byminute=byminute,
1436
+ bysecond=bysecond)
1437
+
1438
+ locator = RRuleLocator(rrule, tz=self.tz)
1439
+ else:
1440
+ locator = MicrosecondLocator(interval, tz=self.tz)
1441
+ if date2num(dmin) > 70 * 365 and interval < 1000:
1442
+ _api.warn_external(
1443
+ 'Plotting microsecond time intervals for dates far from '
1444
+ f'the epoch (time origin: {get_epoch()}) is not well-'
1445
+ 'supported. See matplotlib.dates.set_epoch to change the '
1446
+ 'epoch.')
1447
+
1448
+ locator.set_axis(self.axis)
1449
+ return locator
1450
+
1451
+
1452
+ class YearLocator(RRuleLocator):
1453
+ """
1454
+ Make ticks on a given day of each year that is a multiple of base.
1455
+
1456
+ Examples::
1457
+
1458
+ # Tick every year on Jan 1st
1459
+ locator = YearLocator()
1460
+
1461
+ # Tick every 5 years on July 4th
1462
+ locator = YearLocator(5, month=7, day=4)
1463
+ """
1464
+ def __init__(self, base=1, month=1, day=1, tz=None):
1465
+ """
1466
+ Parameters
1467
+ ----------
1468
+ base : int, default: 1
1469
+ Mark ticks every *base* years.
1470
+ month : int, default: 1
1471
+ The month on which to place the ticks, starting from 1. Default is
1472
+ January.
1473
+ day : int, default: 1
1474
+ The day on which to place the ticks.
1475
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1476
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1477
+ """
1478
+ rule = rrulewrapper(YEARLY, interval=base, bymonth=month,
1479
+ bymonthday=day, **self.hms0d)
1480
+ super().__init__(rule, tz=tz)
1481
+ self.base = ticker._Edge_integer(base, 0)
1482
+
1483
+ def _create_rrule(self, vmin, vmax):
1484
+ # 'start' needs to be a multiple of the interval to create ticks on
1485
+ # interval multiples when the tick frequency is YEARLY
1486
+ ymin = max(self.base.le(vmin.year) * self.base.step, 1)
1487
+ ymax = min(self.base.ge(vmax.year) * self.base.step, 9999)
1488
+
1489
+ c = self.rule._construct
1490
+ replace = {'year': ymin,
1491
+ 'month': c.get('bymonth', 1),
1492
+ 'day': c.get('bymonthday', 1),
1493
+ 'hour': 0, 'minute': 0, 'second': 0}
1494
+
1495
+ start = vmin.replace(**replace)
1496
+ stop = start.replace(year=ymax)
1497
+ self.rule.set(dtstart=start, until=stop)
1498
+
1499
+ return start, stop
1500
+
1501
+
1502
+ class MonthLocator(RRuleLocator):
1503
+ """
1504
+ Make ticks on occurrences of each month, e.g., 1, 3, 12.
1505
+ """
1506
+ def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
1507
+ """
1508
+ Parameters
1509
+ ----------
1510
+ bymonth : int or list of int, default: all months
1511
+ Ticks will be placed on every month in *bymonth*. Default is
1512
+ ``range(1, 13)``, i.e. every month.
1513
+ bymonthday : int, default: 1
1514
+ The day on which to place the ticks.
1515
+ interval : int, default: 1
1516
+ The interval between each iteration. For example, if
1517
+ ``interval=2``, mark every second occurrence.
1518
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1519
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1520
+ """
1521
+ if bymonth is None:
1522
+ bymonth = range(1, 13)
1523
+
1524
+ rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
1525
+ interval=interval, **self.hms0d)
1526
+ super().__init__(rule, tz=tz)
1527
+
1528
+
1529
+ class WeekdayLocator(RRuleLocator):
1530
+ """
1531
+ Make ticks on occurrences of each weekday.
1532
+ """
1533
+
1534
+ def __init__(self, byweekday=1, interval=1, tz=None):
1535
+ """
1536
+ Parameters
1537
+ ----------
1538
+ byweekday : int, list of int, constant from :mod:`dateutil.rrule`, or \
1539
+ list of constants, default: 1 (Tuesday)
1540
+ Ticks will be placed on every weekday in *byweekday*. Default is
1541
+ every Tuesday.
1542
+
1543
+ Elements of *byweekday* (if a sequence) must be either integers or
1544
+ MO, TU, WE, TH, FR, SA, SU, the constants from
1545
+ :mod:`dateutil.rrule`, which have been imported into the
1546
+ :mod:`matplotlib.dates` namespace.
1547
+ interval : int, default: 1
1548
+ The interval between each iteration. For example, if
1549
+ ``interval=2``, mark every second occurrence.
1550
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1551
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1552
+ """
1553
+ rule = rrulewrapper(DAILY, byweekday=byweekday,
1554
+ interval=interval, **self.hms0d)
1555
+ super().__init__(rule, tz=tz)
1556
+
1557
+
1558
+ class DayLocator(RRuleLocator):
1559
+ """
1560
+ Make ticks on occurrences of each day of the month. For example,
1561
+ 1, 15, 30.
1562
+ """
1563
+ def __init__(self, bymonthday=None, interval=1, tz=None):
1564
+ """
1565
+ Parameters
1566
+ ----------
1567
+ bymonthday : int or list of int, default: all days
1568
+ Ticks will be placed on every day in *bymonthday*. Default is
1569
+ ``bymonthday=range(1, 32)``, i.e., every day of the month.
1570
+ interval : int, default: 1
1571
+ The interval between each iteration. For example, if
1572
+ ``interval=2``, mark every second occurrence.
1573
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1574
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1575
+ """
1576
+ if interval != int(interval) or interval < 1:
1577
+ raise ValueError("interval must be an integer greater than 0")
1578
+ if bymonthday is None:
1579
+ bymonthday = range(1, 32)
1580
+
1581
+ rule = rrulewrapper(DAILY, bymonthday=bymonthday,
1582
+ interval=interval, **self.hms0d)
1583
+ super().__init__(rule, tz=tz)
1584
+
1585
+
1586
+ class HourLocator(RRuleLocator):
1587
+ """
1588
+ Make ticks on occurrences of each hour.
1589
+ """
1590
+ def __init__(self, byhour=None, interval=1, tz=None):
1591
+ """
1592
+ Parameters
1593
+ ----------
1594
+ byhour : int or list of int, default: all hours
1595
+ Ticks will be placed on every hour in *byhour*. Default is
1596
+ ``byhour=range(24)``, i.e., every hour.
1597
+ interval : int, default: 1
1598
+ The interval between each iteration. For example, if
1599
+ ``interval=2``, mark every second occurrence.
1600
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1601
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1602
+ """
1603
+ if byhour is None:
1604
+ byhour = range(24)
1605
+
1606
+ rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
1607
+ byminute=0, bysecond=0)
1608
+ super().__init__(rule, tz=tz)
1609
+
1610
+
1611
+ class MinuteLocator(RRuleLocator):
1612
+ """
1613
+ Make ticks on occurrences of each minute.
1614
+ """
1615
+ def __init__(self, byminute=None, interval=1, tz=None):
1616
+ """
1617
+ Parameters
1618
+ ----------
1619
+ byminute : int or list of int, default: all minutes
1620
+ Ticks will be placed on every minute in *byminute*. Default is
1621
+ ``byminute=range(60)``, i.e., every minute.
1622
+ interval : int, default: 1
1623
+ The interval between each iteration. For example, if
1624
+ ``interval=2``, mark every second occurrence.
1625
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1626
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1627
+ """
1628
+ if byminute is None:
1629
+ byminute = range(60)
1630
+
1631
+ rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,
1632
+ bysecond=0)
1633
+ super().__init__(rule, tz=tz)
1634
+
1635
+
1636
+ class SecondLocator(RRuleLocator):
1637
+ """
1638
+ Make ticks on occurrences of each second.
1639
+ """
1640
+ def __init__(self, bysecond=None, interval=1, tz=None):
1641
+ """
1642
+ Parameters
1643
+ ----------
1644
+ bysecond : int or list of int, default: all seconds
1645
+ Ticks will be placed on every second in *bysecond*. Default is
1646
+ ``bysecond = range(60)``, i.e., every second.
1647
+ interval : int, default: 1
1648
+ The interval between each iteration. For example, if
1649
+ ``interval=2``, mark every second occurrence.
1650
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1651
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1652
+ """
1653
+ if bysecond is None:
1654
+ bysecond = range(60)
1655
+
1656
+ rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
1657
+ super().__init__(rule, tz=tz)
1658
+
1659
+
1660
+ class MicrosecondLocator(DateLocator):
1661
+ """
1662
+ Make ticks on regular intervals of one or more microsecond(s).
1663
+
1664
+ .. note::
1665
+
1666
+ By default, Matplotlib uses a floating point representation of time in
1667
+ days since the epoch, so plotting data with
1668
+ microsecond time resolution does not work well for
1669
+ dates that are far (about 70 years) from the epoch (check with
1670
+ `~.dates.get_epoch`).
1671
+
1672
+ If you want sub-microsecond resolution time plots, it is strongly
1673
+ recommended to use floating point seconds, not datetime-like
1674
+ time representation.
1675
+
1676
+ If you really must use datetime.datetime() or similar and still
1677
+ need microsecond precision, change the time origin via
1678
+ `.dates.set_epoch` to something closer to the dates being plotted.
1679
+ See :doc:`/gallery/ticks/date_precision_and_epochs`.
1680
+
1681
+ """
1682
+ def __init__(self, interval=1, tz=None):
1683
+ """
1684
+ Parameters
1685
+ ----------
1686
+ interval : int, default: 1
1687
+ The interval between each iteration. For example, if
1688
+ ``interval=2``, mark every second occurrence.
1689
+ tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
1690
+ Ticks timezone. If a string, *tz* is passed to `dateutil.tz`.
1691
+ """
1692
+ super().__init__(tz=tz)
1693
+ self._interval = interval
1694
+ self._wrapped_locator = ticker.MultipleLocator(interval)
1695
+
1696
+ def set_axis(self, axis):
1697
+ self._wrapped_locator.set_axis(axis)
1698
+ return super().set_axis(axis)
1699
+
1700
+ def __call__(self):
1701
+ # if no data have been set, this will tank with a ValueError
1702
+ try:
1703
+ dmin, dmax = self.viewlim_to_dt()
1704
+ except ValueError:
1705
+ return []
1706
+
1707
+ return self.tick_values(dmin, dmax)
1708
+
1709
+ def tick_values(self, vmin, vmax):
1710
+ nmin, nmax = date2num((vmin, vmax))
1711
+ t0 = np.floor(nmin)
1712
+ nmax = nmax - t0
1713
+ nmin = nmin - t0
1714
+ nmin *= MUSECONDS_PER_DAY
1715
+ nmax *= MUSECONDS_PER_DAY
1716
+
1717
+ ticks = self._wrapped_locator.tick_values(nmin, nmax)
1718
+
1719
+ ticks = ticks / MUSECONDS_PER_DAY + t0
1720
+ return ticks
1721
+
1722
+ def _get_unit(self):
1723
+ # docstring inherited
1724
+ return 1. / MUSECONDS_PER_DAY
1725
+
1726
+ def _get_interval(self):
1727
+ # docstring inherited
1728
+ return self._interval
1729
+
1730
+
1731
+ class DateConverter(units.ConversionInterface):
1732
+ """
1733
+ Converter for `datetime.date` and `datetime.datetime` data, or for
1734
+ date/time data represented as it would be converted by `date2num`.
1735
+
1736
+ The 'unit' tag for such data is None or a `~datetime.tzinfo` instance.
1737
+ """
1738
+
1739
+ def __init__(self, *, interval_multiples=True):
1740
+ self._interval_multiples = interval_multiples
1741
+ super().__init__()
1742
+
1743
+ def axisinfo(self, unit, axis):
1744
+ """
1745
+ Return the `~matplotlib.units.AxisInfo` for *unit*.
1746
+
1747
+ *unit* is a `~datetime.tzinfo` instance or None.
1748
+ The *axis* argument is required but not used.
1749
+ """
1750
+ tz = unit
1751
+
1752
+ majloc = AutoDateLocator(tz=tz,
1753
+ interval_multiples=self._interval_multiples)
1754
+ majfmt = AutoDateFormatter(majloc, tz=tz)
1755
+ datemin = datetime.date(1970, 1, 1)
1756
+ datemax = datetime.date(1970, 1, 2)
1757
+
1758
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
1759
+ default_limits=(datemin, datemax))
1760
+
1761
+ @staticmethod
1762
+ def convert(value, unit, axis):
1763
+ """
1764
+ If *value* is not already a number or sequence of numbers, convert it
1765
+ with `date2num`.
1766
+
1767
+ The *unit* and *axis* arguments are not used.
1768
+ """
1769
+ return date2num(value)
1770
+
1771
+ @staticmethod
1772
+ def default_units(x, axis):
1773
+ """
1774
+ Return the `~datetime.tzinfo` instance of *x* or of its first element,
1775
+ or None
1776
+ """
1777
+ if isinstance(x, np.ndarray):
1778
+ x = x.ravel()
1779
+
1780
+ try:
1781
+ x = cbook._safe_first_finite(x)
1782
+ except (TypeError, StopIteration):
1783
+ pass
1784
+
1785
+ try:
1786
+ return x.tzinfo
1787
+ except AttributeError:
1788
+ pass
1789
+ return None
1790
+
1791
+
1792
+ class ConciseDateConverter(DateConverter):
1793
+ # docstring inherited
1794
+
1795
+ def __init__(self, formats=None, zero_formats=None, offset_formats=None,
1796
+ show_offset=True, *, interval_multiples=True):
1797
+ self._formats = formats
1798
+ self._zero_formats = zero_formats
1799
+ self._offset_formats = offset_formats
1800
+ self._show_offset = show_offset
1801
+ self._interval_multiples = interval_multiples
1802
+ super().__init__()
1803
+
1804
+ def axisinfo(self, unit, axis):
1805
+ # docstring inherited
1806
+ tz = unit
1807
+ majloc = AutoDateLocator(tz=tz,
1808
+ interval_multiples=self._interval_multiples)
1809
+ majfmt = ConciseDateFormatter(majloc, tz=tz, formats=self._formats,
1810
+ zero_formats=self._zero_formats,
1811
+ offset_formats=self._offset_formats,
1812
+ show_offset=self._show_offset)
1813
+ datemin = datetime.date(1970, 1, 1)
1814
+ datemax = datetime.date(1970, 1, 2)
1815
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
1816
+ default_limits=(datemin, datemax))
1817
+
1818
+
1819
+ class _SwitchableDateConverter:
1820
+ """
1821
+ Helper converter-like object that generates and dispatches to
1822
+ temporary ConciseDateConverter or DateConverter instances based on
1823
+ :rc:`date.converter` and :rc:`date.interval_multiples`.
1824
+ """
1825
+
1826
+ @staticmethod
1827
+ def _get_converter():
1828
+ converter_cls = {
1829
+ "concise": ConciseDateConverter, "auto": DateConverter}[
1830
+ mpl.rcParams["date.converter"]]
1831
+ interval_multiples = mpl.rcParams["date.interval_multiples"]
1832
+ return converter_cls(interval_multiples=interval_multiples)
1833
+
1834
+ def axisinfo(self, *args, **kwargs):
1835
+ return self._get_converter().axisinfo(*args, **kwargs)
1836
+
1837
+ def default_units(self, *args, **kwargs):
1838
+ return self._get_converter().default_units(*args, **kwargs)
1839
+
1840
+ def convert(self, *args, **kwargs):
1841
+ return self._get_converter().convert(*args, **kwargs)
1842
+
1843
+
1844
+ units.registry[np.datetime64] = \
1845
+ units.registry[datetime.date] = \
1846
+ units.registry[datetime.datetime] = \
1847
+ _SwitchableDateConverter()