Create Better Graphs with Bokeh

This guide walks through the process of creating better graphs with bokeh. The coolest thing about bokeh is that it lets you create interactive plots. We will test out this functionality below.

Basic Plotting

As always, lets begin by importing the libraries that we will be using for this tutorial.


In [1]:
import numpy as np
from scipy.integrate import odeint
from bokeh.plotting import figure, show
from bokeh.io import output_notebook

You'll notice that we didn't import the entire bokeh library, rather, we imported specific modules and methods. This is to prevent your python script from using up more computation time and memory than is necessary. Bokeh is a large library, and importing the entire package is rather reckless.

The first thing that we are going to do is allow the bokeh library to produce graphs in a python notebook.


In [2]:
output_notebook()


Loading BokehJS ...

Now lets plot something pretty. To start with, we are going to plot a Lorenz System. The code below is taken from a bokeh demo


In [3]:
sigma = 10
rho = 28
beta = 8.0/3
theta = 3 * np.pi / 4

def lorenz(xyz, t):
    x, y, z = xyz
    x_dot = sigma * (y - x)
    y_dot = x * rho - x * z - y
    z_dot = x * y - beta* z
    return [x_dot, y_dot, z_dot]

initial = (-10, -7, 35)
t = np.arange(0, 100, 0.006)

solution = odeint(lorenz, initial, t)

x = solution[:, 0]
y = solution[:, 1]
z = solution[:, 2]
xprime = np.cos(theta) * x - np.sin(theta) * y

colors = ["#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C", "#08306B",]

p = figure(title="lorenz example")

p.multi_line(np.array_split(xprime, 7), np.array_split(z, 7),
             line_color=colors, line_alpha=0.8, line_width=1.5)
show(p)  # open a browser


Interactive Plotting

In order to make these plots interactive in a jupyter notebook, we make one more import.


In [1]:
from ipywidgets import interact
from bokeh.io import push_notebook

In [ ]: