This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Bokeh Interactive Data Visualization Cheat Sheet

A production-grade reference guide to modern Bokeh (3.x+): covering standard plotting workflows, ColumnDataSource data containers, essential glyphs, HoverTool interactive tooltips, color mapping, complex layouts, linked brushing, and web embedding.

· Published

Bokeh is a Python library designed for building interactive, web-ready data visualizations. It allows developers to construct rich charts in pure Python and render them directly in web browsers via the BokehJS runtime engine.

The core Bokeh construction equation:

$$\text{Figure (Canvas)} + \text{ColumnDataSource (Data)} + \text{Glyphs (Visual Markers)} = \text{Interactive Visualization}$$

🔗 Related Cheat Sheets: Pandas Cheat Sheet · NumPy Cheat Sheet · Scikit-Learn Cheat Sheet · Data Analysis Methods · Python Cheat Sheet


1. End-to-End Quickstart Example

The following script builds data, sets up a canvas, draws line and circle glyphs, configures interactive hover tooltips, and outputs a standalone HTML file:

from bokeh.plotting import figure, show
from bokeh.io import output_file
from bokeh.models import ColumnDataSource, HoverTool

# 1. Prepare data source
data = {
    'x': [1, 2, 3, 4, 5],
    'y': [6, 7, 2, 4, 8],
    'label': ['A', 'B', 'C', 'D', 'E']
}
source = ColumnDataSource(data=data)

# 2. Initialize figure canvas (Bokeh 3.x uses width/height)
p = figure(
    title="Daily Temperature Trend",
    x_axis_label="Day",
    y_axis_label="Temperature (°C)",
    width=700,
    height=400,
    tools="pan,wheel_zoom,box_zoom,reset,save"
)

# 3. Add glyphs (line and circle markers)
p.line(x='x', y='y', source=source, line_width=2, color="#1f77b4", legend_label="Observed")
circles = p.circle(x='x', y='y', source=source, size=10, fill_color="white", line_color="#1f77b4", line_width=2)

# 4. Attach HoverTool
hover = HoverTool(
    renderers=[circles],
    tooltips=[("Sample", "@label"), ("Day", "$x{0}"), ("Temp", "$y{0.0} °C")]
)
p.add_tools(hover)

# 5. Output and display
output_file("trend.html", title="Bokeh Trend Visualization")
show(p)

2. Core Data Container: ColumnDataSource

ColumnDataSource (CDS) is Bokeh's primary data wrapper. Wrapping data in a CDS enables cross-chart linking, streaming updates, and client-side brushing:

import pandas as pd
from bokeh.models import ColumnDataSource

# 1. Create from a Pandas DataFrame or dictionary
df = pd.DataFrame({
    'mpg': [18.0, 15.0, 18.0, 16.0],
    'hp': [130, 165, 150, 150],
    'origin': ['USA', 'USA', 'USA', 'Europe']
})
source = ColumnDataSource(df)

# 2. Access internal column arrays
mpg_values = source.data['mpg']

# 3. Stream new data (real-time dashboards / telemetry)
new_data = {'mpg': [20.0], 'hp': [140], 'origin': ['Japan']}
source.stream(new_data, rollover=1000) # rollover drops oldest entries beyond 1000

# 4. Patch in-place updates (avoids full re-render)
source.patch({
    'hp': [(0, 135)]  # Replaces index 0 hp value with 135
})

3. Canvas Configuration (figure())

⚠️ Note: Bokeh 3.0+ completely removed plot_width and plot_height. Always use width and height.

from bokeh.plotting import figure

p = figure(
    title="Main Chart",
    width=800,                    # Width in pixels
    height=500,                   # Height in pixels
    x_range=(0, 100),             # Axis range limits (or categorical list ['A', 'B'])
    y_range=(0, 50),
    x_axis_type="datetime",       # Axis type: "linear", "log", "datetime", "mercator"
    tools="pan,box_zoom,wheel_zoom,reset,save",
    toolbar_location="right",     # Location: "above", "below", "left", "right", None
    background_fill_color="#fafafa"
)

# Axis styling
p.xaxis.axis_label = "Timeline"
p.xaxis.axis_label_text_font_size = "12pt"
p.grid.grid_line_dashed = [4, 4]

4. Visual Glyphs Master Index

Glyph Category Method Syntax Key Parameters & Notes
Circle / Points p.circle(x, y, ...) size=10, fill_color, line_color, fill_alpha
Squares p.square(x, y, ...) size, fill_color
Generic Scatter p.scatter(x, y, marker="hex", ...) Unified scatter: marker can be 'circle', 'triangle', 'cross', 'star'
Line p.line(x, y, ...) line_width=2, line_color, line_dash="dashed"
Step Line p.step(x, y, mode="after", ...) Stepwise curves: mode can be 'before', 'after', 'center'
Multi-line p.multi_line(xs, ys, ...) xs=[[x1, x2], [x3, x4]], ys=[[y1, y2], [y3, y4]]
Vertical Bars p.vbar(x, width, top, bottom=0) Bar chart: x is center coordinate, top is bar height
Horizontal Bars p.hbar(y, height, right, left=0) Horizontal bar chart: y is center, right is length
Area Fill p.varea(x, y1, y2, ...) Filled area between two curves (error bounds, confidence bands)
Patch Polygon p.patch(x, y, ...) Closed 2D polygon fill

5. Color Mapping & Palettes (bokeh.transform)

5.1 Categorical Color Mapping (factor_cmap)

from bokeh.transform import factor_cmap
from bokeh.palettes import Category10

factors = ['USA', 'Asia', 'Europe']
palette = Category10[3] # 3-color palette

color_mapping = factor_cmap(
    field_name='origin',
    palette=palette,
    factors=factors
)

p.circle(
    x='mpg', y='hp', source=source,
    color=color_mapping,
    legend_field='origin',  # Automatically partitions legend by origin values
    size=9
)

5.2 Continuous Linear Color Mapping (linear_cmap & ColorBar)

from bokeh.transform import linear_cmap
from bokeh.palettes import Viridis256
from bokeh.models import ColorBar

mapper = linear_cmap(
    field_name='hp',
    palette=Viridis256,
    low=min(df['hp']),
    high=max(df['hp'])
)

p.circle(x='mpg', y='hp', source=source, color=mapper, size=8)

# Add side color bar scale
color_bar = ColorBar(color_mapper=mapper['transform'], width=12, location=(0, 0))
p.add_layout(color_bar, 'right')

6. Interactivity & Selection States

6.1 Custom Hover Tooltips (HoverTool)

from bokeh.models import HoverTool

hover = HoverTool(
    tooltips=[
        ("Origin", "@origin"),
        ("MPG", "@mpg{0.0}"),
        ("Horsepower", "@hp hp"),
        ("Pixel Coordinate", "($sx, $sy)")
    ],
    formatters={
        '@timestamp': 'datetime'
    },
    mode='mouse'                  # 'mouse' for point hover; 'vline' for vertical slice
)
p.add_tools(hover)

6.2 Selection & Non-Selection Styling

p.circle(
    x='mpg', y='hp', source=source,
    size=10,
    color="blue",
    selection_color="red",        # Selected points turn red
    nonselection_alpha=0.1        # Unselected points fade to 10% opacity
)

7. Legends & Click Policies

⚠️ Note: Bokeh 2.0+ and 3.x+ deprecated legend="xxx". Use legend_label="Label" for static names and legend_field="col" for grouped columns.

# 1. Legend positioning & layout
p.legend.location = "top_right"          # "top_left", "bottom_right", "center", etc.
p.legend.orientation = "horizontal"      # "vertical" or "horizontal"
p.legend.background_fill_alpha = 0.8
p.legend.border_line_color = "#e0e0e0"

# 2. Interactive toggle / mute (click legend item to hide/show layer)
p.legend.click_policy = "hide"           # Options: "hide" or "mute"

8. Multi-Plot Layouts & Linking

8.1 Grid Layouts (row, column, gridplot)

from bokeh.layouts import row, column, gridplot

# Horizontal row
layout_row = row(p1, p2, p3)

# Vertical column
layout_col = column(p1, p2)

# Nested grid
grid = gridplot([[p1, p2], [p3, p4]], width=350, height=300)

8.2 Tabs Layout (TabPanel & Tabs)

⚠️ Note: In Bokeh 3.0+, Panel (from bokeh.models.widgets) was removed and replaced by TabPanel directly in bokeh.models.

from bokeh.models import TabPanel, Tabs

tab1 = TabPanel(child=p1, title="Revenue")
tab2 = TabPanel(child=p2, title="User Growth")

tabs_layout = Tabs(tabs=[tab1, tab2])
show(tabs_layout)

8.3 Linking Plots

Linked Panning & Zooming

Assign one plot's range to another:

p2.x_range = p1.x_range
p3.x_range = p1.x_range

Linked Brushing

Share the same ColumnDataSource instance across multiple figures:

# p1 and p2 share `source`
p1 = figure(width=350, height=300, tools="box_select,lasso_select,reset")
p1.circle('mpg', 'hp', source=source)

p2 = figure(width=350, height=300, tools="box_select,lasso_select,reset")
p2.circle('mpg', 'weight', source=source)

# Selecting points in p1 automatically highlights matching points in p2
show(row(p1, p2))

9. Output, Web Embedding & Static Export

Target Environment / Framework Code Snippet
Jupyter Notebook Interactive notebook development from bokeh.io import output_notebook, show
output_notebook()
show(p)
Standalone HTML Offline distribution with CDN JS from bokeh.io import output_file, save
output_file("chart.html", mode='cdn')
save(p)
Web Apps (FastAPI/Flask/Django) Embed into HTML templates from bokeh.embed import components
script, div = components(p)
Static PNG Reports and documentation from bokeh.io import export_png
export_png(p, filename="plot.png")
Vector SVG High-DPI printing & publications from bokeh.io import export_svg
p.output_backend = "svg"
export_svg(p, filename="plot.svg")

Related topics