如何实现JavaScript回调来更改Bokeh图表标题

3
我希望您能够更改Bokeh图表的标题,以下是我尝试过的最简代码示例。问题在于如何进行回调。"Original Answer"翻译成"最初的回答"。

from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import CustomJS, Button

fig = figure(title='title')
fig.line(x=[1,2,3], y=[1,2,3])


callback = CustomJS(args={'title':fig.title}, code="""title.text = text_input.get('value');
""")

text_input = TextInput(title="Add graph title", value='', callback=callback)


widgets_layout = column(text_input)


figures_layout = row(fig)


page_layout = row(widgets_layout, fig)


script, div = components(page_layout)
return render_to_response('fig.html', {'script': script, 'div': div})



我没有收到任何错误信息,但当我在TextInput字段中输入新标题时,没有任何反应。有什么想法吗?

有什么建议吗?

1个回答

7

.get(...) 语法已经很久以前被删除。在任何比较新的 Bokeh 版本中,只需直接访问例如 .value 即可。另外,为了在回调函数内定义 text_input,你需要将它传递到 args 中。以下是您代码的更新版本:

from bokeh.io import show
from bokeh.layouts import column, row
from bokeh.models import CustomJS, TextInput
from bokeh.plotting import figure


fig = figure(title='title')
fig.line(x=[1,2,3], y=[1,2,3])

text_input = TextInput(title="Add graph title", value='')
text_input.js_on_change('value', CustomJS(
    args={'title': fig.title, 'text_input': text_input},
    code="title.text = text_input.value"
))

widgets_layout = column(text_input)

figures_layout = row(fig)

show(row(widgets_layout, fig))

然而,使用Bokeh >=1.1版本,你可以直接使用js_link,避免创建CustomJS

text_input = TextInput(title="Add graph title", value='')
text_input.js_link('value', fig.title, 'text')

如果您在上面的代码中遇到标题问题,请不要忘记在图中指定标题。我的意思是不要让图表没有标题。我以前就犯过这种错误 :) - kağan hazal koçdemir
是的,将title字符串传递给figure实际上是为了向绘图添加一个Title注释的快捷方式,这才是实际必须链接的内容。 - bigreddot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接