Back to Bokeh

Continuous Updating

examples/output/jupyter/push_notebook/Continuous Updating.ipynb

3.10.0.dev41.7 KB
Original Source
python
import time

import numpy as np
from bokeh.io import push_notebook, show, output_notebook
from bokeh.models import HoverTool
from bokeh.plotting import figure
output_notebook()
python
N = 1000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 2
colors = [f"#{int(r):02x}{int(g):02x}{150:02x}" for r, g in zip(50+2*x, 30+2*y)]
python
TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,tap,box_select,lasso_select"

p = figure(tools=TOOLS)
p.axis.major_label_text_font_size = "24px"
hover = HoverTool(tooltips=None, mode="vline")
p.add_tools(hover)
r = p.circle(x,y, radius=radii,
             fill_color=colors, fill_alpha=0.6, line_color=None,
             hover_fill_color="black", hover_fill_alpha=0.7, hover_line_color=None)

python
# get and explicit handle to update the next show cell with
target = show(p, notebook_handle=True)
python
i = 0
while True:
    i +=1
    p.title.text = str(i)

    r.data_source.data['radius'] = radii * (2 + np.sin(i/5))

    x = r.data_source.data['x']
    y = r.data_source.data['y']
    d = np.sqrt((x-50)**2 + (y-50)**2)/100
    rand = 2 * (np.random.random(size=N) - 0.5)
    r.data_source.data['x'] = x + 2 * np.sin(d) * rand
    r.data_source.data['y'] = y + np.cos(d**2) * rand

    p.axis.major_label_text_color = r.data_source.data['fill_color'][int(i%N)]

    # push updates to the plot continuously using the handle (interrupt the notebook kernel to stop)
    push_notebook(handle=target)
    time.sleep(0.1)
python
# Update the hover glyph properties using the explicit handle (go hover over the plot)
r.hover_glyph.fill_color = "white"
r.hover_glyph.fill_alpha = 0.5
hover.mode = "vline"
push_notebook()