dates.py 65 KB

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