matplotlib

Table Of Contents

Previous topic

matplotlib colors

Next topic

matplotlib figure

This Page

matplotlib dates

matplotlib.dates

Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python datetime, the add-on modules pytz and dateutils. datetime objects are converted to floating point numbers which represent the number of days since 0001-01-01 UTC. The helper functions date2num(), num2date() and drange() are used to facilitate easy conversion to and from datetime and numeric ranges.

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.

All the matplotlib date converters, tickers and formatters are timezone aware, and the default timezone is given by the timezone parameter in your matplotlibrc file. If you leave out a tz timezone instance, the default from your rc file will be assumed. If you want to use a custom time zone, pass a pytz.timezone instance with the tz keyword argument to num2date(), plot_date(), and any custom date tickers or locators you create. See pytz for information on pytz and timezone handling.

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 tickers

Most of the date tickers can locate single or multiple values. For example:

# tick on mondays every week
loc = WeekdayLocator(byweekday=MO, tz=tz)

# tick on mondays and saturdays
loc = WeekdayLocator(byweekday=(MO, SA))

In addition, most of the constructors take an interval argument:

# tick on mondays every second week
loc = WeekdayLocator(byweekday=MO, interval=2)

The rrule locator allows completely general date ticking:

# tick every 5th easter
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
loc = RRuleLocator(rule)

Here are all the date tickers:

Date formatters

Here all all the date formatters:

matplotlib.dates.date2num(d)

d is either a datetime instance or a sequence of datetimes.

Return value is a floating point number (or sequence of floats) which gives number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC.

matplotlib.dates.num2date(x, tz=None)

x is a float value which gives number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC.

Return value is a datetime instance in timezone tz (default to rcparams TZ value).

If x is a sequence, a sequence of datetime objects will be returned.

matplotlib.dates.drange(dstart, dend, delta)
Return a date range as float Gregorian ordinals. dstart and dend are datetime instances. delta is a datetime.timedelta instance.
matplotlib.dates.epoch2num(e)
Convert an epoch or sequence of epochs to the new date format, that is days since 0001.
matplotlib.dates.num2epoch(d)
Convert days since 0001 to epoch. d can be a number or sequence.
matplotlib.dates.mx2num(mxdates)
Convert mx datetime instance (or sequence of mx instances) to the new date format.
class matplotlib.dates.DateFormatter(fmt, tz=None)

Bases: matplotlib.ticker.Formatter

Tick location is seconds since the epoch. Use a strftime() format string.

Python only supports datetime strftime() formatting for years greater than 1900. Thanks to Andrew Dalke, Dalke Scientific Software who contributed the strftime() code below to include dates earlier than this year.

fmt is an strftime() format string; tz is the
tzinfo instance.
set_tzinfo(tz)
strftime(dt, fmt)
class matplotlib.dates.IndexDateFormatter(t, fmt, tz=None)

Bases: matplotlib.ticker.Formatter

Use with IndexLocator to cycle format strings by index.

t is a sequence of dates (floating point days). fmt is a strftime() format string.

class matplotlib.dates.DateLocator(tz=None)

Bases: matplotlib.ticker.Locator

tz is a tzinfo instance.

datalim_to_dt()
nonsingular(vmin, vmax)
set_tzinfo(tz)
viewlim_to_dt()
class matplotlib.dates.RRuleLocator(o, tz=None)

Bases: matplotlib.dates.DateLocator

autoscale()
Set the view limits to include the data range.
class matplotlib.dates.YearLocator(base=1, month=1, day=1, tz=None)

Bases: matplotlib.dates.DateLocator

Make ticks on a given day of each year that is a multiple of base.

Examples:

# Tick every year on Jan 1st
locator = YearLocator()

# Tick every 5 years on July 4th
locator = YearLocator(5, month=7, day=4)

Mark years that are multiple of base on a given month and day (default jan 1).

autoscale()
Set the view limits to include the data range.
class matplotlib.dates.MonthLocator(bymonth=None, bymonthday=1, interval=1, tz=None)

Bases: matplotlib.dates.RRuleLocator

Make ticks on occurances of each month month, eg 1, 3, 12.

Mark every month in bymonth; bymonth can be an int or sequence. Default is range(1,13), i.e. every month.

interval is the interval between each iteration. For example, if interval=2, mark every second occurance.

class matplotlib.dates.WeekdayLocator(byweekday=1, interval=1, tz=None)

Bases: matplotlib.dates.RRuleLocator

Make ticks on occurances of each weekday.

Mark every weekday in byweekday; byweekday can be a number or sequence.

Elements of byweekday must be one of MO, TU, WE, TH, FR, SA, SU, the constants from dateutils.rrule.

interval specifies the number of weeks to skip. For example, interval=2 plots every second week.

class matplotlib.dates.DayLocator(bymonthday=None, interval=1, tz=None)

Bases: matplotlib.dates.RRuleLocator

Make ticks on occurances of each day of the month. For example, 1, 15, 30.

Mark every day in bymonthday; bymonthday can be an int or sequence.

Default is to tick every day of the month: bymonthday=range(1,32)

class matplotlib.dates.HourLocator(byhour=None, interval=1, tz=None)

Bases: matplotlib.dates.RRuleLocator

Make ticks on occurances of each hour.

Mark every hour in byhour; byhour can be an int or sequence. Default is to tick every hour: byhour=range(24)

interval is the interval between each iteration. For example, if interval=2, mark every second occurrence.

class matplotlib.dates.MinuteLocator(byminute=None, interval=1, tz=None)

Bases: matplotlib.dates.RRuleLocator

Make ticks on occurances of each minute.

Mark every minute in byminute; byminute can be an int or sequence. Default is to tick every minute: byminute=range(60)

interval is the interval between each iteration. For example, if interval=2, mark every second occurrence.

class matplotlib.dates.SecondLocator(bysecond=None, interval=1, tz=None)

Bases: matplotlib.dates.RRuleLocator

Make ticks on occurances of each second.

Mark every second in bysecond; bysecond can be an int or sequence. Default is to tick every second: bysecond = range(60)

interval is the interval between each iteration. For example, if interval=2, mark every second occurrence.

class matplotlib.dates.rrule(freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False)
Bases: dateutil.rrule.rrulebase
class matplotlib.dates.relativedelta(dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None)

The relativedelta type is based on the specification of the excelent 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’s two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes:

relativedelta(datetime1, datetime2)

And the other way is to use the following keyword arguments:

year, month, day, hour, minute, second, microsecond:
Absolute information.
years, months, weeks, days, hours, minutes, seconds, microseconds:
Relative information, may be negative.
weekday:
One of the weekday instances (MO, TU, etc). 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.
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.

Here is the behavior of operations with relativedelta:

  1. Calculate the absolute year, using the ‘year’ argument, or the original datetime year, if the argument is not present.
  2. Add the relative ‘years’ argument to the absolute year.
  3. Do steps 1 and 2 for month/months.
  4. Calculate the absolute day, using the ‘day’ argument, or the original datetime day, if the argument is not present. Then, subtract from the day until it fits in the year and month found after their operations.
  5. Add the relative ‘days’ argument to the absolute day. Notice that the ‘weeks’ argument is multiplied by 7 and added to ‘days’.
  6. Do steps 1 and 2 for hour/hours, minute/minutes, second/seconds, microsecond/microseconds.
  7. If the ‘weekday’ argument is present, calculate the weekday, with the given (wday, nth) tuple. wday is the index of the weekday (0-6, 0=Mon), and nth is the number of weeks to add forward or backward, depending on its signal. Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won’t change the day.
matplotlib.dates.seconds(s)
Return seconds as days.
matplotlib.dates.minutes(m)
Return minutes as days.
matplotlib.dates.hours(h)
Return hours as days.
matplotlib.dates.weeks(w)
Return weeks as days.