Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Bokeh Cheat Sheet

Bokeh is a newly introduced Python library which is used for interactive data visualization targeting web browsers.

Jan 23, 2020 • 10 Minute Read

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:

      # 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)
    

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.

      from bokeh.plotting import figure
    

Importing the API, if we want to use Columndatasource :

      from bokeh.models import ColumnDataSource
    

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

      from bokeh.io import output_notebook, show
    

We can also import figure and output_notebook simultaneously .

      from bokeh.plotting import figure, output_file, show
    

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

      from bokeh.layouts import gridplot
    

Data Preparation

  • In Bokeh, we can provide data directly, as in thisexample:
      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)
    

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

      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)
    

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 .

      # importing the output_file() function
from bokeh.io import output_file
output_file("name.html")
    

export_png()

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

      # importing the export_png() function
from bokeh.io import export_png

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

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 .

      # 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")
    

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() .

      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)
    

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

      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)
    

Multi-line Glyph

      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)
    

Circle Glyph

      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)
    

Gridplot Layout

      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)
    

Wedge Layout

      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)
    

Scatter Plot

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

      # 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)
    

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:

      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)
    

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.

      #importing the show() function
from bokeh.io import output_file, show
#naming the output file
output_file("test.html")
# show results
show(obj)
    

save()

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

      # importing the save() function
from bokeh.io import output_file, save
# naming the output file
output_file("test.html")
# save result
save(obj)
    

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.