首页 > 解决方案 > 在 reactjs 前端嵌入散景图

问题描述

我希望对嵌入散景图的最佳方式进行全面检查。

堆栈是主要服务于 JSON API 的 Flask,前端是 React.js 单页应用程序 (SPA)。所以,没有模板之类的东西。

在教育自己在Bokeh文档中嵌入绘图时,有一些选择。但广义上:

  1. 嵌入图
  2. 作为客户端连接到 Bokeh 服务器

首先 - 我倾向于将 Flask 中的位推到前端,以便它们是独立的。也就是说,对我来说似乎有意义的一种途径是在 Flask 中为情节生成 JS 并将 React 作为远程脚本推送。

上述角度似乎比以下替代方案更可取:(a) 导出 HTML 并烘焙到 iFrame,或 (b) 在前端运行 Bokeh 客户端。但是,我是从一个没有太多经验的地方讲的。

任何指针将不胜感激!

干杯!

标签: reactjsflaskbokeh

解决方案


在我看来,最简单的方法是在前端使用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>

这应该足以让你开始。我写了一篇关于这个主题的更完整的博客文章,其中还包含指向包含示例代码的 github 存储库的链接


推荐阅读