Bokeh - Jupyter Notebook



Displaying Bokeh figure in Jupyter notebook is very similar to the one created in Bokeh - Getting Started Chapter. The only change you need to make is to import output_notebook instead of output_file from bokeh.plotting module.

from bokeh.plotting import figure, output_notebook, show

The figure() function creates a new figure for plotting.

The output_notebook() function is used to specify a Jupyter Notebook to store output.

The show() function displays the Bokeh figure in notebook.

Next, set up two numpy arrays where second array is sine value of first.

import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

To obtain a Bokeh Figure object, specify the title and x and y axis labels as below −

p = figure(title = "sine wave example", x_axis_label = 'x', y_axis_label = 'y')

The Figure object contains a line() method that adds a line glyph to the figure. It needs data series for x and y axes.

p.line(x, y, legend_label = "sine", line_width = 2)

Finally, Call to output_notebook() function sets Jupyter notebooks output cell as the destination for show() function as shown below −

output_notebook()
show(p)

This will render the line plot and will be displayed in the jupyter Notebook.

Example - Usage of Bokeh to render a Line

main.py

from bokeh.plotting import figure, output_notebook, show
import numpy as np
import math

x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

output_notebook()

p = figure(title = "sine wave example", x_axis_label = 'x', y_axis_label = 'y')
p.line(x, y, legend_label = "sine", line_width = 2)

show(p)

Output

Run the code and verify the output in the jupyter notebook.

(myenv) D:\bokeh\myenv>py main.py
Advertisements