2017-04-14 161 views
1

我想了解如何使用Bokeh和CustomJS與Python函數在RadioButtonGroup中使用交互。我已經調整了the example provided at the Bokeh site來繪製y = x^f。我想在兩個冪之間切換,f = 0.5和f = 0.2,而不是使用功率f的滑塊。我遵循手冊並使用Jupyter筆記本在我的代碼中插入了RadioButtonGroup。按鈕顯示和響應,但我無法獲得任何回撥響應的切換按鈕。無法從Bokeh RadioButtonGroup獲取響應

任何幫助將不勝感激。

from math import pi 
 

 
from bokeh.io import output_file, show 
 
from bokeh.layouts import column 
 
from bokeh.models import ColumnDataSource, CustomJS, Slider, TextInput, RadioButtonGroup 
 
from bokeh.plotting import Figure, output_notebook 
 

 
output_notebook() 
 

 
x = [x*0.005 for x in range(0, 200)] 
 
y = x 
 

 
source = ColumnDataSource(data=dict(x=x, y=y)) 
 

 
plot = Figure(plot_width=400, plot_height=400) 
 
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) 
 

 
def callback(source=source, input1=input1, window=None): 
 
    data = source.data 
 
    m= input1.active 
 
    if m==0: 
 
     f=.5 
 
    else: 
 
     f=2 
 
     
 
    x, y = data['x'], data['y'] 
 
    for i in range(len(x)): 
 
     y[i] = window.Math.pow(x[i], f) 
 
    source.trigger('change') 
 

 
input1 = RadioButtonGroup(labels=["power = .5", "power = 2."], active=0) 
 

 
input1.button_type="success" 
 
input1.js_on_change('active', CustomJS.from_py_func(callback)) 
 

 
layout = column(input1, plot) 
 

 
show(layout)

回答

0

我不能讓bokeh.models.RadioButtonGroup產生回調,但bokeh.models.RadioGroup我可以(我使用背景虛化版本0.12.4也許一個新的版本有利於RadioButtonGroup生成一個回調)。此外,您在聲明之前參考input1。它不需要作爲你的回調函數的輸入,你可以使用cb_obj。請參閱:

import bokeh 
import bokeh.plotting 

bokeh.io.output_notebook() 

x = [x*0.005 for x in range(0, 200)] 
y = x 

source = bokeh.models.ColumnDataSource(data=dict(x=x, y=y)) 

plot = bokeh.plotting.figure(plot_width=400, plot_height=400) 
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) 

def callback(source=source, window=None): 
    data = source.data 
    m = cb_obj.active 
    if m==0: 
     f=.5 
    else: 
     f=2 

    x, y = data['x'], data['y'] 
    for i in range(len(x)): 
     y[i] = window.Math.pow(x[i], f) 
    source.trigger('change') 

input1 = bokeh.models.RadioGroup(labels=["power = .5", "power = 2."],active=0, 
        callback=bokeh.models.CustomJS.from_py_func(callback)) 

layout = bokeh.layouts.column(input1, plot) 

bokeh.io.show(layout) 

enter image description here

+1

非常感謝您指出了這一點。順便說一下,重新定位input1聲明使RadioButtonGroup在Bokeh 0.12.5中正常工作。 –

+0

謝謝。時間更新至0.12.5。 –