在 Bokeh HoverTool 中格式化 Pandas 日期时间

Tim*_*hes 4 python pandas bokeh

我试图让工具提示有一个格式很好的日期时间值,它是微秒精度。使用以下代码,我总是得到一个TB%明显不正确的测量值。我希望工具提示中的“日期”以与数据框中“date_time”字段相同的格式显示。

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)
Run Code Online (Sandbox Code Playgroud)

截屏

Hei*_*him 7

如果您的 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',
   },
)
Run Code Online (Sandbox Code Playgroud)

  • 这个答案适用于 bokeh 2.2.3。上面的答案缺少“格式化程序”下的“@”前缀。 (3认同)

big*_*dot 6

您的格式化程序规范在以下几个方面是错误的:

  • 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',
    },
)
Run Code Online (Sandbox Code Playgroud)

你得到:

在此处输入图片说明

如果你需要更专业的东西,还有CustomJSHoverin Bokeh >= 0.13 它允许你通过提供一段 JavaScript 来完全控制任意格式来做你需要的任何事情。