Chuck
Chuck

Reputation: 145

Running python code by clicking a button in Bokeh

Does anyone have an example of how to run python code in jupyter by clicking a button in Bokeh?

Upvotes: 2

Views: 5206

Answers (1)

mdurant
mdurant

Reputation: 28673

UPDATE The original answer was very out of date. The answer has been updated to reflect changes since Bokeh 0.11 which was released in January of 2016.

A complete example pared from the sliders demo, that uses features from Bokeh 0.12.4:

from numpy import linspace, pi, sin

from bokeh.io import curdoc
from bokeh.layouts import row, widgetbox
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure

# Set up data
x = linspace(0, 4*pi, 200) 
y = sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))

# Set up plot
plot = figure(x_range=(0, 4*pi), y_range=(-2.5, 2.5))
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

# Set up widgets
amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1)

# Set up callbacks
def update(attrname, old, new):
    # Get the current slider values
    a = amplitude.value
    k = freq.value

    # Update the data for the new curve
    source.data = dict(x=x, y=a*sin(k*x))

amplitude.on_change('value', update)
freq.on_change('value', update)

# Set up layout and add to document
inputs = widgetbox(amplitude, freq)
curdoc().add_root(row(inputs, plot, width=1200))

Run with bokeh serve --show <filename> and get the following responsive web app in your browser:

Simplified Bokeh Sliders demo

Upvotes: 8

Related Questions