Bokeh glyph coordinates with x_axis_type 'datetime'

2.8k views Asked by At

I am attempting to add a simple text string (glyph) to a Bokeh plot which uses x_axis_type='datetime'

My code (stripped to its essentials ) is as follows:

p = figure(plot_width=900, plot_height=380, x_axis_type='datetime')

dt  = date(2003, 3, 15)

p.line(xvals, yvals)

txt = Text(
     # x=some_formatting_function(dt), 
     x=1057005600000, 
     y=0.1, 
     text=["happy day!"],
     text_align="left", 
     text_baseline="middle",
     text_font_size="11pt", 
     text_font_style="italic", 
 )
p.add_glyph(txt)
show(p)

The x-axis range/values (ie dates) run from 2002 to 2006 and I'd like to add the text in, say, 2003. The x value I've shown in the code above (ie 1057005600000 -- which I've worked out by trial and error) drops the glyph in the right place.

But I cant work out how to use a datetime.date directly...

Is there a bokeh function (or a property of datetime.date) that will give me the value which the bokeh plot is expecting??

Many thanks.

N.B. I've tried using x = bokeh.properties.Date(dt) but this gives me:

ValueError: expected an element of either String, 
Dict(String, Either(String, Float)) or Float, got <bokeh.properties.Date object 
2

There are 2 answers

2
Luke Canavan On BEST ANSWER

When the x_axis_type attr is set to 'datetime', Bokeh will plot things along the x-axis according to seconds-since-epoch. The easiest solution is to use datetime.datetime (not .date) and then cast your dt object to seconds-since-epoch using the timestamp() method (which will give the ~1.50e9 number you're getting) then use that for your x-coordinate.

$ from datetime import datetime
$ dt = datetime.now()
$ dt
> datetime.datetime(2015, 6, 17, 10, 41, 34, 617709)
$ dt.timestamp()
> 1434555694.617709
0
user908094 On

See the following SO question/answer for the python2 answer to my problem:

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

Thank you @Luke Canavan for pointing me in the right direction(!)