Sunday, April 9, 2017

Embed Javascript in Bokeh

In the same spirit of pragmatism, my approach to embed JavaScript in Bokeh is to embed whole JavaScript files into Bokeh, rather than embedding JavaScript fragments. The reasons are:

  1.  It is difficult to write grammar-correct JavaScript fragments in Bokeh – Pycharm doesn’t help, and you can’t blame it. 
  2.  It is difficult to debug JavaScript.

With JQuery, and some creative maneuvering, you can do many things with Bokeh graphs. 

Here is how to embed JavaScript files into Bokeh:

from jinja2 import Template

from bokeh.embed import file_html

from bokeh.resources import INLINE

from bokeh.util.string import decode_utf8
import os, io

script_in_header='\n    <link rel="stylesheet" href="" type="text/css" />'+\

                 '\n     <script type="text/javascript" src=""></script>'+\

                 '\n    <link rel="stylesheet" href="" type="text/css" />'+\

                 '\n    <script type="text/javascript" src=""></script>'+\

                 '\n    <script type="text/javascript" src=jquery-3.2.0.min.js"></script>'+\

                 '\n    <link rel="stylesheet" href="">'

template = Template("""
    <!doctype html>
    <html lang="en">
        <meta charset="utf-8">
        script_in_header  +
        {{ plot_script }}
        {{ plot_div }} """
        script_end +

def save_graph(graph, output):


    destDir = os.path.dirname(output)


    html = file_html(graph, INLINE, template=template)

    with, "w", encoding="utf-8") as f:


One caveat, the graph elements are generated by Bokeh JavaScript at runtime, so do not count that some elements will be definitely there in $(document).ready.

No comments:

Post a Comment