bokeh Documentation Notes

Taking some notes on the bokeh documentation. I am looking for a better way to integrate charts / graphs into this site, and I haven't found anything that really works for me yet.

1 25

Bokeh is a Python library for creating interactive visualizations for modern web browsers. It helps you build beautiful graphics, ranging from simple plits to complex dashboards with streaming datasets. With Bokeh, you can create JavaScript-powered visualizations without writing any JavaScript yourself.

References

Installation

$ pip install bokeh
!pip install bokeh
out[2]

Requirement already satisfied: bokeh in /usr/local/lib/python3.10/dist-packages (3.6.2)
Requirement already satisfied: Jinja2>=2.9 in /usr/local/lib/python3.10/dist-packages (from bokeh) (3.1.4)
Requirement already satisfied: contourpy>=1.2 in /usr/local/lib/python3.10/dist-packages (from bokeh) (1.3.1)
Requirement already satisfied: numpy>=1.16 in /usr/local/lib/python3.10/dist-packages (from bokeh) (1.26.4)
Requirement already satisfied: packaging>=16.8 in /usr/local/lib/python3.10/dist-packages (from bokeh) (24.2)
Requirement already satisfied: pandas>=1.2 in /usr/local/lib/python3.10/dist-packages (from bokeh) (2.2.2)
Requirement already satisfied: pillow>=7.1.0 in /usr/local/lib/python3.10/dist-packages (from bokeh) (11.0.0)
Requirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.10/dist-packages (from bokeh) (6.0.2)
Requirement already satisfied: tornado>=6.2 in /usr/local/lib/python3.10/dist-packages (from bokeh) (6.3.3)
Requirement already satisfied: xyzservices>=2021.09.1 in /usr/local/lib/python3.10/dist-packages (from bokeh) (2024.9.0)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from Jinja2>=2.9->bokeh) (3.0.2)
Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.10/dist-packages (from pandas>=1.2->bokeh) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas>=1.2->bokeh) (2024.2)
Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.10/dist-packages (from pandas>=1.2->bokeh) (2024.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.8.2->pandas>=1.2->bokeh) (1.17.0)

With just a few lines of Python code, Bokeh enables you to create interactive, JavaScript-powered visualizations displayable in a web browser. The basic idea of Bokeh is a two-step process: First, you select from Bokeh's building blocks to create your visualization. Second, you customize these building blocks to fit your needs. To do this, Bokeh combines two elements:

  • A Python library for defining the content and interactive functionalities of your visualization.
  • A JavaScript library called BokehJS that is working in the background to display your interactive visualizations in a web browser.

Based on your Python code, Bokeh automatically generates all the necessary JavaScript and HTML code for you. In its default setting, Bokeh automatically loads any additional JavaScript code from Bokeh's CDN.

from bokeh.plotting import figure, show
from bokeh.io import output_notebook
# prepare some data
output_notebook()
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
# create a new plot with a title and axis labels
p = figure(title="Simple line example", x_axis_label='x', y_axis_label='y')
# add a line renderer with legend and line thickness to the plot
p.line(x, y, legend_label="Temp.", line_width=2)
# show the results - generates graph and opens web browser to display the generated HTML file
show(p)
out[4]

Introduction

To add more line graphs to your plot, all you need to do is call the line() function multiple times.

Multiple Line Graph Example

The basic steps that most basic visualizations with Bokeh's bokeh.plotting interface require:

  1. Preparing the data: You can use a Python plain list but other forms of serialized data work as well.
  2. Calling the figure() function: This creates a plot with the most common default options. You can customize various properties of your plot, such as its title, tools, and axes labels.
  3. Adding renders: You used line() to create a line. Renderes have various options to specify visual attribute such as colors, legends, and widths.
  4. Asking Bokeh to show() or save() the results: These functions either save your plot to an HTML file or display it in a browser.

Bokeh's plotting interface supports many different glyphs, such as lines, bars, hex tiles, or other polygons. You can use the circle() function instead of line() to render circles. You can use the vbar() function to render vertical bars. The different renderer functions accept various arguments to control what your glyphs look like.

In Bokeh, you can specify colors in several ways. For example:

  • Use one of the named CSS colors
  • Use hexadecimal values, prefaced with a #
  • Use a 3-tuple for RGB colors
  • Use a 4-tuple for RGBA colors

If you want to change any property after creating an object, you can define and overwrite an object's attributes directly. You can add a legend, headline, and annotations to your graphs.

You can customize the file Bokeh creates for your visualization by importing and calling the output_file() function. output_file() accepts various file-related arguments, for example:

  • filename: the filename for the HTML file
  • title: the title for your document (to be used in the HTML's title tag)

If you don't use the output_file() function to define a custom file name, Bokeh defaults to using the file name of the currently running Python script for the filename of the HTML output. Bokeh creates the HTML file when you call the show() function. This function also automatically opens a web browser to display the HTML file. You need to import the save() and output_file() functions before using.If you use Jupyter Notebooks, call Bokeh's output_notebook() function in your code. Then, use the show() function to display the visualization right inside your notebook.

User Guide

Introduction

Glossary

  • Annotation: Visual aids that make reading the plot easier. This includes titles, legends, labels, or bands.
  • Application: A Bokeh application is a recipe for generating Bokeh documents. Typiclaly, this is Python code run by a Bokeh server whenever a new sessions is created
  • BokehJS: The JavaScript client library that actually renders the visuals and handles the UI interactions for Bokeh plots and widgets in the browser. In most cases, Bokeh handles all interactions with BokehJS automatically
  • Document: An organizing data structure for Bokeh applications. Documents contain all the Bokeh models and data needed to render an interactive visualization or application in the browser.
  • Embedding: Various methods that help with Bokeh plots and widgets in web apps, web pages, or Jupyter notebooks.
  • Glyph: API objetcs that draw vectorized graphics to represent data. Glyphs are the basic visual building blocks of Bokeh plots. This includes elements such as lines, rectangles, wedges, or the circles of a scatter plot.
  • Layout: A collection of Bokeh objects. This can be several plots and widgets, arranged in nested rows and columns.
  • Model: The lowest-level objects that Bokeh visualizations consist of. Bokeh's models are part of the bokeh.model interface. Most users will not use this level of interface to assemble plots directly.
  • Plot: Containers that hold all the various objects of a visualization.
  • Renderer*: General term for any method or function that draws elements of the plot.
  • Server: The Bokeh server is an optional component. You can use the Bokeh server to share and publish Bokeh plots and apps, to handle streaming of large data sets, or to enable complex user interactions based on widgets and selections.
  • Widgets: User interface elemenents that are not directly part of a Bokeh plot, such as sliders, drop-down menus, or buttons. You can use events and data from widgets in your Python code, or you can input widgets to update you Bokeh plot itself.

Output Methods

Bokeh offers a variety of ways to produce interactive output. The most common:

  • output_file(): Generate a simple standalone HTML documents for Bokeh visualizations
  • output_notebook(): Display Bokeh visualizations in Jupyter/Zeppelin notebooks.

These functionsare usually used together with show() or save().

Bokeh Settings

Theer are various global settings that influence how Bokeh operates. You can use several methods to change Bokeh's configuration: directly in Python code, in a YAML configuration file, or with environment variables. Some of the most useful settings are:

  • browser: Set this configuration value to the browser you want Bokeh to use.
  • resources: To display interactive visualizations in the browser, Bokeh needs to load BokehJS. Ser this configuration value to define where to load BokehJS from:
    • cdn: load BokehJS from Bokeh's Content Delivery Network (CDN)
    • server: load from a Bokeh server
    • relative: Load a local version relative to the given directory

Interfaces

Bokeh takes a layered approach and offers different programming interfaces appropraite to different users.

The bokeh.plotting Interface

This is the primary interface. This general-purpose interface is similar to plotting interface libraries such as Matlotlib or Matlab. It lets you focus on relating glyphs to data. It automatically assembles plots with default elements for you. The figure() function is at the core of the plotting interface. This function creates a figure() model that includes methods for adding different kinds of glyphs to a plot.

from bokeh.plotting import figure, output_notebook, show
# create a figure object
p = figure(width=300, height=300, tools="pan,reset,save")
output_notebook()
# add a Circle renderer to this figure
p.circle([1, 2.5, 3, 2], [2, 3, 1, 1.5], radius=0.3, alpha=0.5)
# display the figure
show(p)
out[6]

Calling the figure() fuction is all it takes to create a basic plot object. To add data renderers to your plot object, call a glyph method such as figure.circle.

The bokeh.models interface

With Bokeh's low-level bokeh.models interface, you have complete control over how Bokeh creates all elements of your visualization. However, Bokeh's low-level interface doesn't help you to addemble the various elements in meaningful or correct ways. It is entirely up to you to put them together. To be able to use the bokeh.models interface, you need to understand the basic principle by which Bokeh enables you to generate interactive, browser-based visualizations.

  • BokehJS, the JavaScript Library
    • BokehJS runs in the browser. This library handles rendering and user interactions. It takes a collection of declarative JSON objects as its input and uses them as instructions on how to handle the various aspects of visualization in a browser.
  • Bokeh, the Python Library
    • The Python library generates the JSON objects that BokehJS uses to render your visualization in the browser. At its lowest level, the Python library uses a set of model classes that exactly mirror the set of models that BokehJS creates in a browser.

Basic Plotting

from bokeh.plotting import figure, show

p = figure(title="Scatter",width=400, height=400)

# add a scatter circle renderer with a size, color, and alpha
p.scatter([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
# add a square scatter renderer with a size, color, and alpha
p.scatter([4, 3, 2, 1, 3], [3, 3, 8, 9, 1], marker="square",
          size=20, color="olive", alpha=0.5)
p.line([1, 2, 3, 4, 5], [1, 4, 8, 6, 2], line_width=2,color="orange")
p.step([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2, mode="center",color="red")
p.multi_line([[1, 3, 2], [3, 4, 6, 6]], [[2, 1, 4], [4, 7, 8, 5]],
             color=["firebrick", "navy"], alpha=[0.8, 0.3], line_width=4)
# show the results
show(p)
out[8]

Data Sources

The basis for any data visualization is the underlying data. You can use Python lists or NumPy arrays to provide data to a plotting function. The ColumnDataSource (CDS) is the core of most Bokeh plots. It provides the data to the glyphs of your plot. When you pass sequences like Python lists or NumPy arrays to a Bokeh renderer, Bokeh automatically creates a ColumnDataSource with this data for you. However, creating a ColumnDataSource yourself gives you access to more advanced options. Think of a ColumnDataSource as a collection of sequences of data that each have their own, unique column name.

To create a basic ColumnDataSource object, you need a Python dictionary to pass to the object's data parameter:

  • Bokeh uses the dictionary's keys as column names
  • The dictionary's values are used as the data values for your ColumnDataSource

The data you pass in as part of your dict can be any non-string ordered sequences of values, such as lists of arrays:

data = {'x_values': [1, 2, 3, 4, 5],
        'y_values': [6, 7, 2, 3, 6]}

source = ColumnDataSource(data=data)

To use ColumnDataSource with a render function, you need to pass at least three arguments:

  • x: the name of the ColumnDataSource's column that contains the data for the x values of your plot
  • y: the name of the COlumnDataSource's column that contains the data for the y values of your plot
  • source: the name of the ColumnDataSource that contains the columns you just referenced for the x and y arguments
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
# create a Python dict as the basis of your ColumnDataSource
data = {'x_values': [1, 2, 3, 4, 5],
        'y_values': [6, 7, 2, 3, 6]}
# create a ColumnDataSource by passing the dict
source = ColumnDataSource(data=data)
# create a plot using the ColumnDataSource's two columns
p = figure()
p.circle(x='x_values', y='y_values', source=source)

The data parameter can also be a pandas DataFrame or GroupBy object.

from numpy.random import standard_normal

from bokeh.plotting import figure, show
from bokeh.transform import linear_cmap
from bokeh.util.hex import hexbin

x = standard_normal(50000)
y = standard_normal(50000)

bins = hexbin(x, y, 0.1)

p = figure(tools="", match_aspect=True, background_fill_color='#440154')
p.grid.visible = False

p.hex_tile(q="q", r="r", size=0.1, line_color=None, source=bins,
           fill_color=linear_cmap('counts', 'Viridis256', 0, max(bins.counts)))

show(p)
out[10]
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
from bokeh.transform import linear_cmap

x = list(range(1, 11))
y = list(range(1, 11))

source = ColumnDataSource(dict(x=x,y=y))

p = figure(width=300, height=300, title="Linear color map based on Y")

# use the field name of the column source
cmap = linear_cmap(field_name='y', palette="Spectral6", low=min(y), high=max(y))

r = p.scatter(x='x', y='y', color=cmap, size=15, source=source)

# create a color bar from the scatter glyph renderer
color_bar = r.construct_color_bar(width=10)

p.add_layout(color_bar, 'right')

show(p)
out[11]

In addition to built-in transformation functions, you can use your own JavaScript code. Use the CustomJSTransform() function to add custom JavaScript code that is executed in the browser. The example below uses the CustomJSTranform() function with the argument vfunc. vfunc is short for "vectorized function". The JavaScript code you supply to vfunc needs to expect an array of inputs in the variable xs, and return a JavaScript array with transformed values:

v_func = """
    const first = xs[0]
    const norm = new Float64Array(xs.length)
    for (let i = 0; i < xs.length; i++) {
        norm[i] = xs[i] / first
    }
    return norm
"""
normalize = CustomJSTransform(v_func=v_func)

plot.line(x='aapl_date', y=transform('aapl_close', normalize), line_width=2,
          color='#cf3c4d', alpha=0.6,legend="Apple", source=aapl_source)

Bokeh has a few different mechanisms for including CSS styles in output. The Styles class can be used to configure inline style attribute of DOM elements directly:

style = Styles(
    display="grid",
    grid_template_columns="auto auto",
    column_gap="10px",
)
grid = Div(style=style)

It is also possible to define individual stylesheets in generated output.

Comments

You have to be logged in to add a comment

User Comments

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC