dates.py 65 KB

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