gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:17:19 25 4
gpt4 key购买 nike

我正在尝试让工具提示具有格式正确的日期时间值,精度为微秒。使用以下代码,我总是得到 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)

screenshot

最佳答案

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

  • 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

如果您需要更专业的东西,还有 CustomJSHover在 Bokeh >= 0.13 中,它允许您通过提供一段 JavaScript 来完全控制任意格式来执行您需要的任何操作。

关于python - 在 Bokeh HoverTool 中格式化 Pandas 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51496142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com