Use Locators with data (independent of Axes object)

Is there a way to use the various tick locators (in particular I am mainly interesting in the various date and/or time tick locators) by passing the data to them instead of creating and using an Axes object that contains the data?

You can call locator.tick_values(vmin, vmax)

Note for dates we have a bit of a hodgepodge, and you need to pass as datetime objects:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

loc = mdates.AutoDateLocator()
# must convert to datetime, I'm afraid:
vmin = np.datetime64('2001-01-01T00:00').tolist()
vmax = np.datetime64('2001-02-01T00:00').tolist()
print(vmin, vmax)
ticks = loc.tick_values(vmin, vmax)
print(mdates.num2date(ticks))
1 Like

Perfect. Exactly what I was looking for. Thanks!

Wondering if this is a bug or expected behavior:

import matplotlib.dates as mdates
from   dateutil import parser as dp

vmin = dp.parse('2021-02-01 09:30')
vmax = dp.parse('2021-02-01 16:00')

loc = mdates.MinuteLocator(30,interval=1)

ticks = loc.tick_values(vmin, vmax)
print('ticks=')
for dt in mdates.num2date(ticks):
    print(dt)

As expected, the output from the above code is:

ticks=
2021-02-01 09:30:00+00:00
2021-02-01 10:30:00+00:00
2021-02-01 11:30:00+00:00
2021-02-01 12:30:00+00:00
2021-02-01 13:30:00+00:00
2021-02-01 14:30:00+00:00
2021-02-01 15:30:00+00:00

However, setting interval=2 gives the same result:

loc = mdates.MinuteLocator(30,interval=2)

ticks = loc.tick_values(vmin, vmax)
print('ticks=')
for dt in mdates.num2date(ticks):
    print(dt)

ticks=
2021-02-01 09:30:00+00:00
2021-02-01 10:30:00+00:00
2021-02-01 11:30:00+00:00
2021-02-01 12:30:00+00:00
2021-02-01 13:30:00+00:00
2021-02-01 14:30:00+00:00
2021-02-01 15:30:00+00:00

Whereas, I was hoping to get:

ticks=
2021-02-01 09:30:00+00:00
2021-02-01 11:30:00+00:00
2021-02-01 13:30:00+00:00
2021-02-01 15:30:00+00:00

Am I doing something wrong?
Did I misunderstand the documentation


It’s interesting to note that the following does work as I expect based on the documentation:

loc = mdates.MinuteLocator([0,15,30,45],interval=1)
# results in:
ticks=
2021-02-01 09:30:00+00:00
2021-02-01 09:45:00+00:00
2021-02-01 10:00:00+00:00
2021-02-01 10:15:00+00:00
2021-02-01 10:30:00+00:00
2021-02-01 10:45:00+00:00
...

And the same, with interval=2:

loc = mdates.MinuteLocator([0,15,30,45],interval=2)
# results in:
ticks=
2021-02-01 09:30:00+00:00
2021-02-01 10:00:00+00:00
2021-02-01 10:30:00+00:00
2021-02-01 11:00:00+00:00
2021-02-01 11:30:00+00:00
2021-02-01 12:00:00+00:00
...

Just as I expect. So why doesn’t the first case of interval=2 work?