Author avatar

Gaurav Singhal

Bokeh Cheat Sheet

Gaurav Singhal

  • Jan 23, 2020
  • 10 Min read
  • 128 Views
  • Jan 23, 2020
  • 10 Min read
  • 128 Views
Data
Bokeh

Introduction

Bokeh is a newly introduced Python library, like D3.js, which is used for interactive data visualization targeting web browsers. Bokeh distinguishes itself from other Python visualization libraries such as Matplotlib or Seaborn by providing precise and elegant construction of versatile graphics with high interactivity and high performance in large and streaming data sets. Bokeh can also be used to embed visualizations to Django and Flask.

In this cheat sheet, we will learn the basics of creating plots with the help of Bokeh's high-level module, bokeh.plotting.

Steps to Create a Plot Using Bokeh.plotting

Below are the steps for creating a plot. We will discuss each step in detail later.

  • Importing the library and its API

  • Preparing the data

  • Specifying how and where the file will be saved

  • Creating a new plot and adding renderers for your data with visual customizations

  • Showing or saving the results

Here is a simple example in Bokeh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Step1 = importing the library
from bokeh.plotting import figure, output_file, show

# Step2= preparing the data 
x = [1,5,3,4]
y = [1,2,3,5]

# Step3 = Specify name and location 
output_file('index.html')

# Step4 = create a new 
p = figure(plot_height=250, plot_width=300)

# adding a legend and line renderer with width
p.line(x,y, color = 'Red')

# Step 5 = show result 
show(p)
python

Importing the Library

We are working on how to plot using bokeh.plotting, a high-level module of the bokeh library. bokeh.plotting is mainly centered around the figure() class, so we will look at how to import this module.

1
from bokeh.plotting import figure
python

Importing the API, if we want to use Columndatasource :

1
from bokeh.models import ColumnDataSource
python

Importing of the bokeh.io, if we want to specify how and where our file will be saved:

1
from bokeh.io import output_notebook, show
python

We can also import figure and output_notebook simultaneously .

1
from bokeh.plotting import figure, output_file, show
python

For gridplot, we have to import gridplot function from bokeh.layouts .

1
from bokeh.layouts import gridplot
python

Data Preparation

  • In Bokeh, we can provide data directly, as in thisexample:
1
2
3
4
5
6
from bokeh.plotting import figure
x_values = [4, 2, 7, 4, 8]
y_values = [4, 5, 2, 6, 9]

p = figure()
p.circle(x=x_values, y=y_values)
python

The data we pass directly or by Pandas is converted to columndatasource, but we can also pass it directly.

1
2
3
4
5
6
7
8
9
10
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource

# passing data in columndatasource
data = {'x_values': [4, 2, 7, 4, 8],
   'y_values': [2, 6, 9, 3, 6]}
source = ColumnDataSource(data=data)

p = figure()
p.circle(x = 'x_values', y = 'y_values', source = source)
python

Specify Location

We can use bokeh.io API to name or to save our output file. It is advised to specify or name the file before adding the plot and render it to the plot.

output_file()

output_file() is called for naming the the file or to generate default output state when show() and save() functions are called .

1
2
3
# importing the output_file() function
from bokeh.io import output_file
output_file("name.html")
python

export_png()

export_png() is used to export the file as .png file type. This function usage is similar to save() and show functions .

1
2
3
4
5
# importing the export_png() function
from bokeh.io import export_png

# exporting the resulted file as png
export_png(plot, filename = "plot.png")  
python

export_svgs()

export_svgs() is used to export the file as .svg file type. This function usage is also similar to save() and show functions .

1
2
3
4
5
6
# importing the export_svgs() function
from bokeh.io import export_svgs

plot.output_backend = "svg"
# exporting the resulted file as svgs
export_svgs(plot, filename = "plot.svg") 
python

push_notebook()

By passing the push_notebook() function, we can make Bokeh show the results of show() calls on the Jupyter output cell since the last call of push_notebook() .

1
2
3
4
5
6
7
8
9
10
11
12
13
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show

output_notebook()

plot = figure(plot_height= 250, plot_width = 300)
plot.circle([1,2,3], [4,6,5], size = 10, color ='red')

handle = show(plot, notebook_handle=True)

# Update the plot title in the earlier cell
plot.title.text = "Test Title"
push_notebook(handle = handle)
python

In this screenshot, you can see the plot shown in the output cell of the Jupyter Notebook.

Creating Plots and Adding Renders

First, we have to create a new figure for plotting using figure() class. figure() objects have many glyph methods that can be used to draw different types of plots :

  • annulus()
  • annular_wedge(), wedge()
  • rect(), quad()
  • image(), image_rgba(), image_url()
  • patch().patches()
  • line(), multi_line()
  • circle(), oval()
  • ellipse(), arc()
  • quadratic(), bezier()

Simple Line Glyph

1
2
3
4
5
6
from bokeh.plotting import figure, output_file, show

#plot creation and adding renders 
p = figure(plot_width = 250, plot_height = 300)
p.line([1,2,3], [2,3,4], line_width = 4)
show(p)
python

Multi-line Glyph

1
2
3
4
5
6
7
8
9
10
from bokeh.plotting import figure, output_file, show
x = [1,2,3,4]
y = [4,6,7,8]
x1 = [5,7,8,9]
y1 = [7,8,3,2]
# crearing a plot
p = figure()
# adding renders to the plot
p.multi_line([x, y], [x1, y1], color=["Red", "navy"], alpha=[0.8, 0.3], line_width=4)
show(p)
python

Circle Glyph

1
2
3
4
5
6
7
from bokeh.plotting import figure, output_file, show

# plot creation and adding renders
plot = figure(plot_width=300, plot_height=300)
plot.circle(x=[1, 2, 3], y=[1, 2, 3], size=20)

show(plot)
python

Gridplot Layout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import numpy as np
from bokeh.plotting import figure, output_file, show
# importing gridplot function 
from bokeh.layouts import gridplot

# prepare some data using numpy
x = np.linspace(0, 15, 80)
y = np.cos(x)
y1 = np.sin(x)
y2 = np.sin(x) + np.cos(x)

# outputfile
output_file("grid.html")

# Create a new plot
a1 = figure(width=250, plot_height=250, title=None)
a1.circle(x, y, size=10, color="yellow", alpha=0.5)

# New plot with same range
a2 = figure(width=250, height=250, x_range=a1.x_range, y_range=a1.y_range, title=None)
a2.triangle(x, y1, size=10, color="Grey", alpha=0.5)

# New plot with x axis same range
a3 = figure(width=250, height=250, x_range=a1.x_range, title=None)
a3.square(x, y2, size=10, color="green", alpha=0.5)

# NEW: put the subplots in a gridplot
p = gridplot([[a1, a2, a3]], toolbar_location=None)

#show result
show(p)
python

Wedge Layout

1
2
3
4
5
6
7
8
from bokeh.plotting import figure, output_file, show
# Adjusting the plot width and height
plot = figure(plot_width=250, plot_height=300)
# Rendering the glyph 
plot.wedge(x = [4, 5, 6], y = [2, 3, 4], 
           radius = 17, start_angle=0.8, end_angle=3.1,
           radius_units="screen", color="green")
show(plot)
python

Scatter Plot

There is also a scatter function that can be parameterized by marker type .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Import Bokeh Libraries
from bokeh.plotting import figure, output_file, show

# x-y coordinate data
x = [1.5, 2.5, 1]
y = [1, 1.8, 2.5]
#Specify fie name
output_file('scatter.html', title='Circle Glyphs')
#plot creation
p = figure(
  title='simple scatter plot',
  plot_height=250, plot_width=300
)
#using scatter function 
p.scatter(x,y, marker="square",size = 16, fill_color="red")
show(p)
python

We can paramaterize different types of markers with the scatter function.

Note: Every type of marker has a different number of parameters and keywords according to its properties:

  • asterisk()
  • circle()
  • circle_cross()
  • circle_x()
  • triangle()
  • cross()
  • diamond()
  • diamond_cross()
  • square_x() ● inverted_triangle()
  • square()
  • x()
  • square_cross()

Bar chart

There are also specialized glyphs for making bar charts in Bokeh:

1
2
3
4
5
6
from bokeh.plotting import figure, output_file, show

plot = figure(plot_width=250, plot_height=300)
# rendering the hbar glyph
plot.hbar(y = [1, 3, 6], height = 0.6, left = 0.1, right = [1,2,3], color = "red")
show(plot)
python

Other types of stack bars include:

  • Bars: hbar_stack(), vbar_stack()

  • Lines: hline_stack(), vline_stack()

  • Areas: harea_stack(), varea_stack()

Show or Save Result

This is the last step of creating a Bokeh plot after rendering and creating a plot.

show()

To display the file, show( ) function is used. We can call this multiple times in a single cell of Jupyter Notebook to display multiple objects.

1
2
3
4
5
6
#importing the show() function
from bokeh.io import output_file, show
#naming the output file
output_file("test.html")
# show results
show(obj)
python

save()

to save the file, save( ) function is used. We can call this multiple times in a single Jupyter Notebook to save multiple objects.

1
2
3
4
5
6
# importing the save() function
from bokeh.io import output_file, save
# naming the output file
output_file("test.html")
# save result
save(obj)
python

Conclusion

In this guide, we have gone through the basics to create a plot using Bokeh's high-level module bokeh.plotting. This cheat sheet aims to remind you of syntax rules, but also of important concepts as well. I hope itwill be really helpful when you’re trying a set of exercises related to a specific topic or working on a project. For further queries, contact me at CodeAlphabet.

0