<< Go back to Tech

Including more two (or more) Bokeh plot with Jekyll





Introduction

Bokeh is a nice visualization tool, enabling to create interactive .html pages with data.

When making a website, you want the figures to be integrated in your page, not in a separated one.

The post is divided in three parts:

  • How to get an .html from Bokeh
  • How to embed it
  • How to embed several Bokeh documents.

Getting an HTML File from Bokeh

This might be easy for you.

You should have included in your code:

from bokeh.plotting  import output_file, show

[... my python code ...]

# p is your plot / figure

output_file(SAVE_PATH)
show(p)

output_file() sets the path where the figure must be stored, and show() creates the .html and open the created file in your browser. Here, nothing special.

Including a Document

To embed one Bokeh document, you need to store the .html generated by Bokeh in the _includes/ repository.

So, if my document is named bokeh_toto.html, it must be stored at _includes/bokeh_toto.html.

To include it in a page of your website, you just need to write:

{% include bokeh_toto.html %}

in the markdown file.

Ok, it should work. You may have the <!DOCTYPE html> header printed that you can remove it (from the file bokeh_toto.html).

Now, if you want to add a second bokeh document, it may not work.

There seems to be a conflict between div naming. I don’t know precisely the reason. I tried to change the IDs, sometimes it worked, sometimes it did not. It was confusing.

Including Several Document

To include multiple document, we should not include the full .html document. Instead, we must include only the <div> and the <script> which enable the stuff to run.

from bokeh.embed import components

[... my code ...]

# p is your plot / figure
script, div = components(p)

with open("tmp_div.txt", "w") as fp:
    fp.write(div)

with open("tmp_script.txt", "w") as fp:
    fp.write("<html>\n" + script + "</html>")

Here components() will generate the minimal material needed. You only need to save it in dedicated files.

For the <div>, you must save it raw without changes. For the <script> , if you include it without any changes, all its content would be printed in your web page, and the <div> would not show the Bokeh figure. To prevent from this issue, adding <html> before and </html> after do the job (I am not an html expert. If you have a cleaner idea, please let me know).

Last, you need to store tmp_div.txt and tmp_script.txt in the _include/ folder.

Finally, invoke them with the include command:

{% include tmp_div.txt %}

{% include tmp_script.txt %}

Normally, if you repeat the process for several figures, they must all show up.



>> You can subscribe to my mailing list here for a monthly update. <<