Bokeh 简明教程

Bokeh - Embedding Plots and Apps

以独立文档或 Bokeh 应用程序的形式显示图和数据也可以嵌入 HTML 文档中。

Plots and data in the form of standalone documents as well as Bokeh applications can be embedded in HTML documents.

独立文档是 Bokeh 图或未由 Bokeh 服务器支持的文档。此类图中的交互纯粹以自定义 JS 形式进行,而不是 Pure Python 回调。

Standalone document is a Bokeh plot or document not backed by Bokeh server. The interactions in such a plot is purely in the form of custom JS and not Pure Python callbacks.

由 Bokeh 服务器支持的 Bokeh 图和文档也可以嵌入。此类文档包含在服务器上运行的 Python 回调。

Bokeh plots and documents backed by Bokeh server can also be embedded. Such documents contain Python callbacks that run on the server.

在独立文档的情况下,可以通过 file_html() 函数获取表示 Bokeh 图的原始 HTML 代码。

In case of standalone documents, a raw HTML code representing a Bokeh plot is obtained by file_html() function.

from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import file_html
fig = figure()
fig.line([1,2,3,4,5], [3,4,5,2,3])
string = file_html(plot, CDN, "my plot")

file_html() 函数的返回值可以保存为 HTML 文件,也可以通过 Flask 应用程序中的 URL 路由来渲染。

Return value of file_html() function may be saved as HTML file or may be used to render through URL routes in Flask app.

在独立文档的情况下,可以通过 json_item() 函数获取其 JSON 表示。

In case of standalone document, its JSON representation can be obtained by json_item() function.

from bokeh.plotting import figure
from bokeh.embed import file_html
import json
fig = figure()
fig.line([1,2,3,4,5], [3,4,5,2,3])
item_text = json.dumps(json_item(fig, "myplot"))

此输出可以用一个网页上的 Bokeh.embed.embed_item 函数 -

This output can be used by the Bokeh.embed.embed_item function on a webpage −

item = JSON.parse(item_text);
Bokeh.embed.embed_item(item);

Bokeh 服务器上的 Bokeh 应用程序也可以嵌入,以便每次加载页面时创建一个新会话和文档,以便加载特定的现有会话。这可以使用 server_document() 函数来完成。它接受一个 Bokeh 服务器应用程序的 URL,并返回一个脚本,该脚本将在每次执行该脚本时从该服务器嵌入新会话。

Bokeh applications on Bokeh Server may also be embedded so that a new session and Document is created on every page load so that a specific, existing session is loaded. This can be accomplished with the server_document() function. It accepts the URL to a Bokeh server application, and returns a script that will embed new sessions from that server any time the script is executed.

server_document() function 接受 URL 参数。如果设置为“默认”,将使用默认 URL [role="bare"] [role="bare"]http://localhost:5006/

The server_document() function accepts URL parameter. If it is set to ‘default’, the default URL [role="bare"]http://localhost:5006/ will be used.

from bokeh.embed import server_document
script = server_document("http://localhost:5006/sliders")

server_document() 函数返回以下脚本代码 −

The server_document() function returns a script tag as follows −

<script
   src="http://localhost:5006/sliders/autoload.js?bokeh-autoload-element=1000&bokeh-app-path=/sliders&bokeh-absolute-url=https://localhost:5006/sliders"
   id="1000">
</script>