Formatting Pandas datetime in Bokeh HoverTool

时间:2018-07-24 10:19:15

标签: python pandas bokeh

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

2 个答案:

答案 0 :(得分:3)

您的格式化程序规范有两种错误:

  • formatters字典将列名映射为格式,您将工具提示标签作为键
  • 未正确给出printf格式的值,例如%0.00000f
  • 我知道没有%f日期时间格式,也许您是说%3N

进行以下更改:

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',
    },
)

您得到:

enter image description here

如果您需要更专业的内容,则Bokeh> = 0.13中还有CustomJSHover,它允许您通过提供JavaScript片段来完全控制格式,以执行所需的任何操作。

答案 1 :(得分:1)

如果您的DataColumn的格式为“ @something”,则还必须在格式化程序中指定该格式。否则,格式将不匹配,并且很有可能将格式字符串解释为百分比。因此,以上示例应为:

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',
   },
)