Datetime axis in Bokeh

心不动则不痛 提交于 2019-12-01 23:13:52

It seems the Bokeh annotations only take numbers, not Datetime or Time objects. A workaround is to convert your times to microseconds and use those to plot.

An example:

from bokeh.plotting import figure, show, output_notebook
from bokeh.models import Arrow
import datetime

def time_to_microseconds(t):
    dmin = datetime.datetime.min
    dummy_tdelta = (datetime.datetime.combine(dmin, t) - dmin)
    return dummy_tdelta.total_seconds()*1000

x_time = [datetime.time(0,0,1),
          datetime.time(0,0,2),
          datetime.time(0,0,3),
          datetime.time(0,0,4),
          datetime.time(0,0,5)]

top = figure(width=300, height=300, x_axis_type='datetime')

# a line works fine with time objects
top.line(x_time, range(len(x_time)))

# layout needs numbers
top.add_layout(Arrow(x_start=time_to_microseconds(datetime.time(0,0,2)), 
                     y_start=3,
                     x_end=time_to_microseconds(datetime.time(0,0,3)), 
                     y_end=2))

edit:

You can change the tick-formatting with:

from bokeh.models import DatetimeTickFormatter

top.xaxis.formatter = DatetimeTickFormatter(seconds=["%M:%S"],
                                            minutes=["%M:%S"],
                                            minsec=["%M:%S"],
                                            hours=["%M:%S"])
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!