单击Bokeh中的按钮运行python代码

时间:2015-09-05 21:53:51

标签: python button bokeh jupyter

有没有人有一个如何通过单击Bokeh中的按钮在jupyter中运行python代码的示例?

1 个答案:

答案 0 :(得分:9)

更新原来的答案已经过时了。答案已更新,以反映自2016年1月发布的Bokeh 0.11以来的变化。

一个完整的示例,来自滑块演示,使用了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))

使用bokeh serve --show <filename>运行并在浏览器中获取以下响应式网络应用:

Simplified Bokeh Sliders demo