如何使用Bokeh从Python调用JavaScript函数? [英] How can I call a JavaScript function from Python using Bokeh?
问题描述
我有这种情况:
- 我有一些数据(在pandas数据框中)用于绘制图
- 当我按下一个由bokeh小部件构建的按钮时,我可以调用回调方法,并使用python进行计算.
- 但是现在我想将计算的数据发送回用户,以便在向导中显示问题.所以我需要运行一些JavaScript函数.
我当时正在考虑创建一个虚拟按钮,并从python运行此按钮的click方法.但是我认为这是不可能的.
I was thinking of creating a dummy button and run the click method of this button from python. But I think this is not possible.
那么,如何直接从python运行JavaScript函数?
So, how can I run a JavaScript function directly from python?
推荐答案
As of Bokeh 0.12.6
, being able to make these kinds of "Remote Procedure Calls" is still an open feature request.
同时,最好的选择是添加 CustomJS
回调某个模型的某些属性. CustomJS
可以执行您想要的任何JS代码(包括调用其他JS函数),并会触发任何属性更新.
In the mean time, your best bet is to add a CustomJS
callback to some property of some model. The CustomJS
can execute whatever JS code you want (including calling other JS functions) and will trigger any the property is updated.
下面是一个示例,该示例显示在更改滑块时调用CustomJS
的情况.对于您的用例,您可以添加不可见的圆形字形,并将CustomJS
附加到字形的size
属性.更改glyph.size
是您可以调用"该功能的方法.
Here's an example that shows calling CustomJS
whenever a slider is changed. For your use case you might add an invisible circle glyph, and attach a CustomJS
to the glyph's size
attribute. Changing glyph.size
is how you can "call" the function.
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.plotting import Figure, output_file, show
output_file("js_on_change.html")
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)
callback = CustomJS(args=dict(source=source), code="""
var data = source.data;
var f = cb_obj.value
x = data['x']
y = data['y']
for (i = 0; i < x.length; i++) {
y[i] = Math.pow(x[i], f)
}
source.change.emit();
""")
slider = Slider(start=0.1, end=4, value=1, step=.1, title="power")
slider.js_on_change('value', callback)
layout = column(slider, plot)
show(layout)
这篇关于如何使用Bokeh从Python调用JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!