Dynamically updating or deleting Layouts


I am trying to create a line chart using Bokeh server with a dynamically moving BoxAnnotation when a button is pressed in the UI. I am wondering if there is a way to amend the beginning and end values of a BoxAnnotation (left and right) dynamically as it doesn’t look like the annotation has a data source in the same way that a line would. In my current version, I can create new boxes that move along the line chart using add_layout, but the problem is that the existing boxes remain on the chart so I end up with lots of overlaying boxes. Is it possible to update or delete annotations? (I don’t think I came across an example in the documentation where annotations are actually deleted or amended). Sample code below. Thanks.

from datetime import timedelta as td
import time

from bokeh.layouts import column
from bokeh.plotting import figure, curdoc
from bokeh.models import BoxAnnotation
from bokeh.models import Button

tools = 'pan,wheel_zoom,box_zoom,reset,save'
box_size = 40

current_data_load = {} # dictionary containing datetimes and corresponding values to plot static line

q = figure(x_axis_type='datetime', tools=tools, plot_width=1000)
q.line(current_data_load['Date'], current_data_load['Value'], color='navy', alpha=0.5)

dates = [] # list containing dates to plot a dynamically changing box on top of line

i = 0

def callback():
    global i

    date = dates[i]
    right_box_bound = time.mktime(date.timetuple()) * 1000
    left_box_bound = time.mktime((date - td(minutes=5 * int(box_size))).timetuple()) * 1000
    mid_box = BoxAnnotation(left=left_box_bound, right=right_box_bound, fill_alpha=0.1, fill_color='green')
    i += 1

button = Button(label="Click")

curdoc().add_root(column(button, q))