首页 > 解决方案 > 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?

标签: pythonplothoverdata-visualizationbokeh

解决方案


您可以通过添加%H:%M以小时和分钟为单位添加时间@date,如下所示:

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

DatetimeTickFormatter文档中描述了比例。


推荐阅读