Embedding (high quality interactive) plots and data into HTML documents with Bokeh

I am trying to learn a bit of Bokeh to embed plots and data into HTML documents. It looks simple enough, yet the results are pretty impressive. The example below, for instance (which is verbatim from bokeh’s own documentation), took a mere few lines of code in python.

Start with a few calls:

import numpy as np

from bokeh.plotting import figure
from bokeh.embed import components

To generate the plot, issue these simple numpy commands:

N = 4000

x = np.random.random(size=N)*100
y = np.random.random(size=N)*100
radii = np.random.random(size=N)*1.5
colors = ["#%02x%02x%02x" % (r,g,150) for r,g in zip(np.floor(50+2*x), np.floor(30+2*y))]

plot = figure()
plot.circle(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)

And that’s it! Generate the needed code to be embedded in the web page by issuing components:

plot_script, plot_div = components(plot)

Note, for example, the output stored in the variable plot_div:

<div class="bk-root">
    <div class="plotdiv" id="592e3dfb-14ec-4b7f-80af-f6420469c2d3"></div>
</div>

Now, in any webpage where you’d like to embed this plot, start by loading BokehJS.

<link rel="stylesheet" href="https://cdn.pydata.org/bokeh/release/bokeh-0.12.1.min.css" type="text/css" />
        
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-0.12.1.min.js"></script>
<script type="text/javascript"> Bokeh.set_log_level("info"); </script>

Add to that preamble the script from the output of plot_script above. Whenever you’d like to embed the plot, simply drop the contents of plot_div, and you are done!