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="https://cdn.pydata.org/bokeh/release/bokeh-0.12.4.min.css" type="text/css" />'+\

                 '\n     <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-0.12.4.min.js"></script>'+\

                 '\n    <link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.4.min.css" type="text/css" />'+\

                 '\n    <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.4.min.js"></script>'+\

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

                 '\n    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">'

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

def save_graph(graph, output):

    output=os.path.realpath(output)

    destDir = os.path.dirname(output)

    



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

    with io.open(output, "w", encoding="utf-8") as f:

        f.write(decode_utf8(html))


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