Search code examples
pythonplothoverdata-visualizationbokeh

How can I set custom datetime pattern on Bokeh hover formatter?


I'm trying to plot some values respect to the time using a line plot with Bokeh. My issue came when I tried to add a hover that shows the concrete value at some point of the plot.

I want to show a value, time data (it works fine), but I think a yyyy-mm-dd is imprecise for my purpose, so I want to redefine that pattern to add hours and minutes.

My code is something like that (you can download as a notebook here):

from datetime import datetime, timedelta

from bokeh.plotting import figure, show
from bokeh.models import HoverTool

import pandas as pd
import numpy as np


today = datetime.today()

date_range = pd.date_range(today, today + timedelta(days=1),
                           freq=timedelta(minutes=15))
values = np.random.randint(-10, 10, size=len(date_range)).cumsum()
data = pd.DataFrame({'date': date_range, 'value': values})


hover = HoverTool(tooltips=[('value',   '@value'), ('date', '@date{%F}')],
                  formatters={'date': 'datetime'})

plt = figure(x_axis_type='datetime', tools=[hover])

plt.line(x='date', y='value', source=data)

show(plt)

The output is like that:

Plot

So my question is as follows:

Can anyone explain me how to modify the datetime format pattern on the hover?


Solution

  • You can add the time in hours and minutes by adding %H:%M to @date, like this:

    hover = HoverTool(tooltips=[('value',   '@value'), ('date', '@date{%F %H:%M}')],
                      formatters={'date': 'datetime'})
    

    The scales are described in the DatetimeTickFormatter documentation.