Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Pandas datetime in Bokeh HoverTool

I am trying to get the tooltip to have a nicely formatted datetime value which is to microsecond precision. With the following code I always get a measurement that is in TB% which is obviously incorrect. I would like the "Date" in the tooltip to display in the same format as in the "date_time" field in the dataframe.

import pandas as pd
from bokeh.models import HoverTool
from bokeh.models.formatters import DatetimeTickFormatter
from bokeh.plotting import figure, output_notebook, show


output_notebook()

p = figure(plot_width=400, plot_height=400, x_axis_type="datetime")


d = {
    'timestamp_micros': [1530479286336096,1530479286362156,1530479286472230,1530479286488213,1530479286495292], 
    'height': [6, 7, 2, 4, 5],
    'info': ['foo','bar','baz','qux','quux'],
}
df = pd.DataFrame(data=d)
df['date_time'] = pd.to_datetime(df['timestamp_micros'], unit='us')
display(df)


p.circle(x='date_time', y='height', source=df, line_width=2, size=15, color="navy", alpha=0.5)
p.line(x='date_time', y='height', source=df, line_width=2, color="navy", alpha=0.5)

hover = HoverTool(
    tooltips = [
        ("Date", "@date_time{%Y-%m-%d %H:%M:%S.%f}"),
        ("Value", "@height{0.000000}"),
        ("info", "@info"),
    ],
    formatters={
        'Date': 'datetime',
        'Value' : 'printf',
    },    
)
p.add_tools(hover)

p.xaxis.formatter=DatetimeTickFormatter(
    microseconds = ['%Y-%m-%d %H:%M:%S.%f'],
    milliseconds = ['%Y-%m-%d %H:%M:%S.%3N'],
    seconds = ["%Y-%m-%d %H:%M:%S"],
    minsec = ["%Y-%m-%d %H:%M:%S"],
    minutes = ["%Y-%m-%d %H:%M:%S"],
    hourmin = ["%Y-%m-%d %H:%M:%S"],
    hours=["%Y-%m-%d %H:%M:%S"],
    days=["%Y-%m-%d %H:%M:%S"],
    months=["%Y-%m-%d %H:%M:%S"],
    years=["%Y-%m-%d %H:%M:%S"],
)
p.xaxis.major_label_orientation = math.pi/2

show(p)

screenshot

like image 915
Tim Hughes Avatar asked Dec 18 '22 21:12

Tim Hughes


1 Answers

Your formatters specification is wrong, in a couple of ways:

  • The formatters dict maps column names to formats, you have the tooltip labels as keys
  • The value of the printf format is not given correctly, it should be %0.00000f e.g.
  • There is no %f datetime format that I am aware of, maybe you mean %3N?

With these changes:

hover = HoverTool(
    tooltips = [
        ("Date", "@date_time{%Y-%m-%d %H:%M:%S.%3N}"),
        ("Value", "@height{%0.000000f}"),
        ("info", "@info"),
    ],
    formatters={
        'date_time': 'datetime',
        'height' : 'printf',
    },
)

You get:

enter image description here

If you need something more specialized, there is also the CustomJSHover in Bokeh >= 0.13 which allows you to completely control the formatting arbitrarily by providing a snippet of JavaScript to do the whatever you need.

like image 192
bigreddot Avatar answered Dec 26 '22 20:12

bigreddot