如何直接从javascript访问和修改已有的Bokeh图形元素



我正在使用Bokeh和Flask开发一个应用程序。使用服务器端python代码,它生成一个嵌入网页中的绘图,该网页包含各种用户输入元素,旨在配置绘图。

我知道从Bokeh v0.12.x开始,有一个API允许直接从javascript创建和操作绘图。

这里我缺少的一点是,Bokehjavascript对象开始,我如何列出和访问已经实例化的图形对象(figurelineColumnDataSource…)使用BokehJS API,我将能够编写javascript代码,将网页用户事件(复选框、按钮单击、文本输入…)转换为绘图上的操作(更改线条颜色、隐藏线条、更新数据点值…)。

考虑一下这个非常基本的例子。我希望它能让你开始。

两个滑块改变中间点的xy坐标。

from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import file_html
from bokeh.models import ColumnDataSource
from jinja2 import Template
source = ColumnDataSource(data=dict(x=[1, 2, 3],
y=[3, 2, 1]),
name='my-data-source')
p = figure()
l1 = p.line("x", "y", source=source)
# copied and modified default file.html template used for e.g. `file_html`
html_template = Template("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ title|e if title else "Bokeh Plot" }}</title>
{{ bokeh_css }}
{{ bokeh_js }}
<style>
html {
width: 100%;
height: 100%;
}
body {
width: 90%;
height: 100%;
margin: auto;
}
</style>
<script>
function change_ds_value(name, idx, value) {
var ds = Bokeh.documents[0].get_model_by_name('my-data-source');
ds.data[name][idx] = value;
ds.change.emit();
}
</script>
</head>
<body>
<div>
{{ plot_div|indent(8) }}
{{ plot_script|indent(8) }}
<input type='range' min='-5' max='5'
onchange='change_ds_value("x", 1, this.value)'/>
<input type='range' min='-5' max='5'
onchange='change_ds_value("y", 1, this.value)'/>
</div>
</body>
</html>
""")
html = file_html(p, CDN, template=html_template)
with open('test.html', 'wt') as f:
f.write(html)

最新更新