dates.py 67 KB

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