How to use DateTimeTickFormatter for formatting datetime ticks

Okay I have a problem in that i dont understand how the DateTimeTickFormatter works for different scales and how to set it based on different scales.
for example I have one chart which is a daily chart ie temperature data with the following desired output [wed jan 1,Thu jan 2, Fri jan 3, Sat jan 4,…]. For this I chose this code the following scale
DatetimeTickFormatter(
days=["%a %b %d"],
)
This works and I get my output as desired,

Now I have a second graph which needs to have the following output [Jan-01, Feb-01, Mar-01, Apr-01…], for that I do
DatetimeTickFormatter(
days=["%b %d"],
)
and this works.

Now i am curious why is it if use months ie the below one fails for me it will display numbers such as 01/20 along those lines ?
DatetimeTickFormatter(
months=["%b %d"],
)

link to the doc

thanks

1 Like

Hi amitsandhel,

You can think of it this way: a DateTime axis has multiple different tickers, and which one is active depends upon the scale of your current view of the figure. Since I don’t have your data, I’m not sure how wide a span you have, but here’s an example you can run to observe:

from bokeh.models import ColumnDataSource, DatetimeTickFormatter
from bokeh.plotting import figure, show
import pandas as pd

df = pd.DataFrame(data={
    'string_date': ['2019-01-01', '2019-02-01', '2019-03-01', '2019-04-01', '2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01', '2019-11-01', '2019-12-01'],
    'min_temp': [28, 26, 38, 49, 55, 72, 83, 84, 82, 70, 48, 30]
    })
df['date'] = pd.to_datetime(df['string_date'])
source = ColumnDataSource(df)

p = figure(width=1100, height=500)
p.xaxis[0].formatter = DatetimeTickFormatter(months=["%b %d"])
p.line(source=source, x='date', y='min_temp', color='orange')

show(p)

My data spans a year, so it’s reasonable that the x-axis should be at the “months” scale, and so my DatetimeTickFormatter months argument works fine at the default zoom. If you zoom in, though, so that the x-axis only shows a few days, you’ll see that it’s back to the unformatted version (e.g. ‘11/03’) because I haven’t told the plot what to do at the days level.

The code for the DatetimeTicker is here:
tickers.py
DatetimeTicker is down at the bottom, and shows that it’s a CompositeTicker, made up of several different tickers for different scales-- and you can specify a format for each.

1 Like

Thanks so much that makes a lot of sense now and I will test your code. This definitely will help me in optimising the current code I have thanks

1 Like

what is the meaning of this? I checked the code but still I cannot understand…

“Formats for displaying datetime values in the months range”: formatters — Bokeh 2.4.2 Documentation

1 Like