在我看来,最简单的方法是在前端使用BokehJS,在后端使用 Bokeh.embed.json_item。典型的流程是:
在您的后端(在您的情况下为 Flask):
- 像往常一样在 python 中生成散景图。按照任何在线文档获取您想要显示的可视化效果
- 将生成的 Bokeh 绘图对象传递给 json_item 函数调用,该函数调用有两个参数:实际绘图对象和字符串唯一标识符。此唯一 ID 可以匹配您前端中 DIV 的 HTML ID,但这不是绝对必要的。
- 使用标准 python JSON 库将结果转储为 JSON 字符串
一个简单的例子如下:
@app.route('/plot1')
def plot1():
# copy/pasted from Bokeh Getting Started Guide
x = linspace(-6, 6, 100)
y = cos(x)
p = figure(width=500, height=500, toolbar_location="below",
title="Plot 1")
p.circle(x, y, size=7, color="firebrick", alpha=0.5)
# following above points:
# + pass plot object 'p' into json_item
# + wrap the result in json.dumps and return to frontend
return json.dumps(bokeh.embed.json_item(p, "myplot"))
在前端,确保您导入了必要的 javascript 和 CSS 文件(我为此使用了 CDN),然后简单地向上述端点发出 AJAX GET 请求。将响应解析为 json 对象并调用 Bokeh.embed.embed_item,类似于以下内容:
handlePlot1 = () => {
Axios.get("http://localhost:5000/plot1")
.then(resp =>
window.Bokeh.embed.embed_item(resp.data, 'testPlot')
)
}
// in your render function
<Button
variant="contained"
style={{margin: 10}}
color="primary"
onClick={this.handlePlot1}
>
Get Plot 1
</Button>
<div id='testPlot' className="bk-root"></div>
这应该足以让您入门。我写了一个more complete blog-post about this subject,其中还包含指向github repo containing sample code的链接