我想将BoxAnnotation添加到具有日期时间x轴的绘图中。如何将BoxAnnotation的左右限制设置为日期时间或日期对象。这是我的目标,但是没有用。
from bokeh.sampledata.glucose import data
from bokeh.models import BoxAnnotation
from datetime import *
# output_file("box_annotation.html", title="box_annotation.py example")
TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
#reduce data size
data = data.ix['2010-10-06':'2010-10-13']
p = figure(x_axis_type="datetime", tools=TOOLS)
p.line(data.index.to_series(), data['glucose'],
line_color="gray", line_width=1, legend="glucose")
left_box = BoxAnnotation(plot=p, right=date(2010,10,7), fill_alpha=0.1, fill_color='blue')
mid_box = BoxAnnotation(plot=p, left=date(2010,10,8), right=date(2010,10,9), fill_alpha=0.1, fill_color='yellow')
right_box = BoxAnnotation(plot=p, left=date(2010,10,10), fill_alpha=0.1, fill_color='blue')
p.renderers.extend([left_box, mid_box, right_box])
p.title = "Glucose Range"
p.xgrid[0].grid_line_color=None
p.ygrid[0].grid_line_alpha=0.5
p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'Value'
show(p)
最佳答案
当前的BoxAnnotation实现仅接受NumberSpec类型(浮点数和整数)作为输入。当前的解决方法是将datetime对象转换为时间戳(并将其缩放1e3,因为Bokeh内部使用微秒精度,没有毫秒)
因此,它就像:(使用python3 datetime.timestamp
方法)
from datetime import datetime as dt
...
left_box = BoxAnnotation(plot=p, right=dt(2010,10,7).timestamp()*1000, fill_alpha=0.1, fill_color='blue')
mid_box = BoxAnnotation(plot=p, left=date(2010,10,8).timestamp()*1000, right=date(2010,10,9).timestamp()*1000, fill_alpha=0.1, fill_color='yellow')
right_box = BoxAnnotation(plot=p, left=date(2010,10,10).timestamp()*1000, fill_alpha=0.1, fill_color='blue')
p.renderers.extend([left_box, mid_box, right_box])
...
将对datetime对象的支持添加为参数似乎确实是一项有价值的功能。我已经打开了一个Github问题,您可以对此发表评论/关注:
https://github.com/bokeh/bokeh/issues/2944