English 中文(简体)
Bokeh - Embedding Plots and Apps
  • 时间:2024-11-05

Bokeh - Embedding Plots and Apps


Previous Page Next Page  

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

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 plots and documents backed by Bokeh server can also be embedded. Such documents contain Python callbacks that run on the server.

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.pne([1,2,3,4,5], [3,4,5,2,3])
string = file_html(plot, CDN, "my plot")

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

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.pne([1,2,3,4,5], [3,4,5,2,3])
item_text = json.dumps(json_item(fig, "myplot"))

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 apppcations 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 accomppshed with the server_document() function. It accepts the URL to a Bokeh server apppcation, and returns a script that will embed new sessions from that server any time the script is executed.

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


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

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


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