Matplotlib provides sophisticated date plotting capabilities, standing on the
shoulders of python datetime and the add-on module dateutil.
By default, Matplotlib uses the units machinery described in
units to convert datetime.datetime, and numpy.datetime64
objects when plotted on an x- or y-axis. The user does not
need to do anything for dates to be formatted, but dates often have strict
formatting needs, so this module provides many tick locators and formatters.
A basic example using is:
Matplotlib represents dates using floating point numbers specifying the number
of days since a default epoch of 1970-01-01 UTC; for example,
1970-01-01, 06:00 is the floating point number 0.25. The formatters and
locators require the use of datetime.datetime objects, so only dates between
year 0001 and 9999 can be represented. Microsecond precision
is achievable for (approximately) 70 years on either side of the epoch, and
20 microseconds for the rest of the allowable range of dates (year 0001 to
9999). The epoch can be changed at import time via dates.set_epoch or
rcParams["date.epoch"] (default: '1970-01-01T00:00:00') to other dates if necessary; see
Date precision and epochs for a discussion.
There are a number of helper functions to convert between datetime
objects and Matplotlib dates:
All the Matplotlib date converters, locators and formatters are timezone aware.
If no explicit timezone is provided, rcParams["timezone"] (default: 'UTC') is assumed, provided as a
string. If you want to use a different timezone, pass the tz keyword
argument of num2date to any date tick locators or formatters you create. This
can be either a datetime.tzinfo instance or a string with the timezone name
that can be parsed by gettz.
A wide range of specific and general purpose date tick locators and
formatters are provided in this module. See
matplotlib.ticker for general information on tick locators
and formatters. These are described below.
The dateutil module provides additional code to handle date ticking, making it
easy to place ticks on any kinds of dates. See examples below.
Date tick locators
Most of the date tick locators can locate single or multiple ticks. For example:
# import constants for the days of the weekfrommatplotlib.datesimportMO,TU,WE,TH,FR,SA,SU# tick on Mondays every weekloc=WeekdayLocator(byweekday=MO,tz=tz)# tick on Mondays and Saturdaysloc=WeekdayLocator(byweekday=(MO,SA))
In addition, most of the constructors take an interval argument:
# tick on Mondays every second weekloc=WeekdayLocator(byweekday=MO,interval=2)
The rrule locator allows completely general date ticking:
# tick every 5th easterrule=rrulewrapper(YEARLY,byeaster=1,interval=5)loc=RRuleLocator(rule)
ConciseDateFormatter: also attempts to figure out the best format to use,
and to make the format as compact as possible while still having complete
date information. This is most useful when used with the AutoDateLocator.
A Formatter which attempts to figure out the best format to use. This
is most useful when used with the AutoDateLocator.
AutoDateFormatter has a .scaled dictionary that maps tick scales (the
interval in days between one major tick) to format strings; this dictionary
defaults to
The formatter uses the format string corresponding to the lowest key in
the dictionary that is greater or equal to the current scale. Dictionary
entries can be customized:
locator=AutoDateLocator()formatter=AutoDateFormatter(locator)formatter.scaled[1/(24*60)]='%M:%S'# only show min and sec
Custom callables can also be used instead of format strings. The following
example shows how to use a custom format function to strip trailing zeros
from decimal seconds and adds the date to the first ticklabel:
A Formatter which attempts to figure out the best format to use for the
date, and to make it as compact as possible, but still be complete. This is
most useful when used with the AutoDateLocator:
Autoformat the date labels. The default format is used to form an
initial string, and then redundant elements are removed.
format_data_short(value)
Return a short string representation of value for the mouseover
tooltip (the coordinate display in the interactive figure window).
This should return concise, plain text (no mathtext / LaTeX).
The precision is typically adapted to the current axis resolution
so that neighbouring pixels produce distinguishable labels.
Defaults to Formatter.format_data; subclasses should override
this to provide a plain-text representation that is independent
of the current tick locations.
Note: The mouseover text can be customized by setting the
Axes.fmt_xdata and Axes.fmt_ydata attributes.
format_ticks(values)
Return the tick label strings for all values.
This is the public API for generating tick labels. It calls
set_locs to configure context-dependent formatting state before
delegating to __call__ for each individual value.
The output may contain mathtext or LaTeX markup.
Use this method (rather than __call__) whenever formatting a
complete set of tick values, so that formatters which need to see
all tick locations (e.g. to determine precision, offsets, or which
date components to display) can work correctly.
byweekday : int, list of int, constant from dateutil.rrule, or list of constants, default: 1 (Tuesday)
Ticks will be placed on every weekday in byweekday. Default is
every Tuesday.
Elements of byweekday (if a sequence) must be either integers or
MO, TU, WE, TH, FR, SA, SU, the constants from
dateutil.rrule, which have been imported into the
matplotlib.dates namespace.
interval : int, default: 1
The interval between each iteration. For example, if
interval=2, mark every second occurrence.
Number of days since the epoch. See get_epoch for the
epoch, which can be changed by rcParams["date.epoch"] (default: '1970-01-01T00:00:00') or set_epoch. If
the epoch is "1970-01-01T00:00:00" (default) then noon Jan 1 1970
("1970-01-01T12:00:00") returns 0.5.
Notes
The Gregorian calendar is assumed; this is not universal practice.
For details see the module docstring.
Number of days (fraction part represents hours, minutes, seconds)
since the epoch. See get_epoch for the
epoch, which can be changed by rcParams["date.epoch"] (default: '1970-01-01T00:00:00') or set_epoch.
The relativedelta type is designed to be applied to an existing datetime and
can replace specific components of that datetime, or represents an interval
of time.
It is based on the specification of the excellent work done by M.-A. Lemburg
in his
mx.DateTime extension.
However, notice that this type does NOT implement the same algorithm as
his work. Do NOT expect it to behave like mx.DateTime's counterpart.
There are two different ways to build a relativedelta instance. The
first one is passing it two date/datetime classes:
relativedelta(datetime1,datetime2)
The second one is passing it any number of the following keyword arguments:
If microsecond accuracy is desired, the date being plotted needs to be
within approximately 70 years of the epoch. Matplotlib internally
represents dates as days since the epoch, so floating point dynamic
range needs to be within a factor of 2^52.
set_epoch must be called before any dates are converted
(i.e. near the import section) or a RuntimeError will be raised.
AutoDateLocator: On autoscale, this class picks the best DateLocator
(e.g., RRuleLocator) to set the view limits and the tick locations. If
called with interval_multiples=True it will make ticks line up with
sensible multiples of the tick intervals. For example, if the interval is
4 hours, it will pick hours 0, 4, 8, etc. as ticks. This behaviour is not
guaranteed by default.
[
'date.autoformatter.minute'
],
1
/
SEC_PER_DAY
:
rcParams
[
'date.autoformatter.second'
],
1
/
MUSECONDS_PER_DAY
:
rcParams
[
'date.autoformatter.microsecond'
],
}
label
=
x
.
strftime
(
fmt
)
label
=
label
.
rstrip
(
"0"
)
label
=
label
.
rstrip
(
"."
)
return
label
formatter
.
scaled
[
1
/
(
24
*
60
)]
=
my_format_function
dateutil.tz
defaultfmt : str
The default format to use if none of the values in self.scaled
are greater than the unit returned by locator._get_unit().
To enable/disable the use of TeX's math mode for rendering the
results of the formatter. If any entries in self.scaled are set
as functions, then it is up to the customized function to enable or
disable TeX's math mode itself.
The interval is used to specify multiples that are appropriate for
the frequency of ticking. For instance, every 7 days is sensible
for daily ticks, but for minutes/seconds, 15 or 30 make sense.
When customizing, you should only modify the values for the existing
keys. You should not add or delete entries.
Example for forcing ticks every 3 hours:
locator=AutoDateLocator()locator.intervald[HOURLY]=[3]# only show every 3 hours
maxticks : int
The maximum number of ticks desired; controls the interval between
ticks (ticking every other, every 3, etc.). For fine-grained
control, this can be a dictionary mapping individual rrule
frequency constants (YEARLY, MONTHLY, etc.) to their own maximum
number of ticks. This can be used to keep the number of ticks
appropriate to the format chosen in AutoDateFormatter. Any
frequency not specified in this dictionary is given a default
value.
interval_multiples : bool, default: True
Whether ticks should be chosen to be multiple of the interval,
locking them to 'nicer' locations. For example, this will force
the ticks to be at hours 0, 6, 12, 18 when hourly ticking is done
at 6 hour intervals.
>>>
print
(
loc
())
[1, 2, 3, 4]
dates.num2date
formats : list of 6 strings, optional
Format strings for 6 levels of tick labelling: mostly years,
months, days, hours, minutes, and seconds. Strings use
the same format codes as strftime. Default is
['%Y','%b','%d','%H:%M','%H:%M','%S.%f']
zero_formats : list of 6 strings, optional
Format strings for tick labels that are "zeros" for a given tick
level. For instance, if most ticks are months, ticks around 1 Jan 2005
will be labeled "Dec", "2005", "Feb". The default is
['','%Y','%b','%b-%d','%H:%M','%H:%M']
offset_formats : list of 6 strings, optional
Format strings for the 6 levels that is applied to the "offset"
string found on the right side of an x-axis, or top of a y-axis.
Combined with the tick labels this should completely specify the
date. The default is:
To enable/disable the use of TeX's math mode for rendering the
results of the formatter.
dateutil.tz
dateutil.tz
>>>
print
(
loc
())
[1, 2, 3, 4]
print
(
loc
())
[1, 2, 3, 4]
'UTC'
Ticks timezone. If a string, tz is passed to dateutil.tz.
=
x
,
arg2
=
y
,
arg3
=
z
...
)
year
,
month
,
day
,
hour
,
minute
,
second
,
microsecond
:
Absolute
information
(
argument
is
singular
);
adding
or
subtracting
a
relativedelta
with
absolute
information
does
not
perform
an
arithmetic
operation
,
but
rather
REPLACES
the
corresponding
value
in
the
original
datetime
with
the
value
(
s
)
in
relativedelta
.
years
,
months
,
weeks
,
days
,
hours
,
minutes
,
seconds
,
microseconds
:
Relative
information
,
may
be
negative
(
argument
is
plural
);
adding
or
subtracting
a
relativedelta
with
relative
information
performs
the
corresponding
arithmetic
operation
on
the
original
datetime
value
with
the
information
in
the
relativedelta
.
weekday
:
One
of
the
weekday
instances
(
MO
,
TU
,
etc
)
available
in
the
relativedelta
module
.
These
instances
may
receive
a
parameter
N
,
specifying
the
Nth
weekday
,
which
could
be
positive
or
negative
(
like
MO
(
+
1
)
or
MO
(
-
2
))
.
Not
specifying
it
is
the
same
as
specifying
+
1.
You
can
also
use
an
integer
,
where
0
=
MO
.
This
argument
is
always
relative
e
.
g
.
if
the
calculated
date
is
already
Monday
,
using
MO
(
1
)
or
MO
(
-
1
)
won
't change the day. To effectively make it absolute, use
it
in
combination
with
the
day
argument
(
e
.
g
.
day
=
1
,
MO
(
1
)
for
first
Monday
of
the
month
)
.
leapdays
:
Will
add
given
days
to
the
date
found
,
if
year
is
a
leap
year
,
and
the
date
found
is
post
28
of
february
.
yearday
,
nlyearday
:
Set
the
yearday
or
the
non
-
leap
year
day
(
jump
leap
days
)
.
These
are
converted
to
day
/
month
/
leapdays
information
.
There are relative and absolute forms of the keyword
arguments. The plural is relative, and the singular is
absolute. For each argument in the order below, the absolute form
is applied first (by setting each attribute to that value) and
then the relative form (by adding the value to the attribute).
The order of attributes considered when this relativedelta is
added to a datetime is:
Year
Month
Day
Hours
Minutes
Seconds
Microseconds
Finally, weekday is applied, using the rule described above.
First, the day is set to 1 (the first of the month), then 25 hours
are added, to get to the 2nd day and 14th hour, finally the
weekday is applied, but since the 2nd is already a Monday there is
no effect.
normalized()
Return a version of this object represented entirely using integer
values for the relative attributes.