Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 31 ยท Bokeh

Bokeh Tools, Hover and Widgets

Add pan, zoom and selection tools to Bokeh charts, build HoverTool tooltips, connect sliders and dropdowns with CustomJS, and link views with a shared source.

A static chart answers one question. An interactive chart lets the reader ask the next one: "what is that outlier?", "what happens if I look only at this group?", "what if the parameter is higher?". Bokeh builds this interactivity from three kinds of parts: tools in the toolbar (pan, zoom, select), hover tooltips that show the data behind a mark, and widgets (sliders, dropdowns) that you connect to your charts with small JavaScript callbacks.

All of these work in a plain HTML file, without a Python process running. Everything happens in the browser. This lesson builds on the figure, glyph and ColumnDataSource ideas from Bokeh Fundamentals.

Bokeh itself cannot run on this site, so the Bokeh code below is read-only. The runnable examples are stand-ins in plain JavaScript that reproduce the mechanisms: a shared selection between two views, tooltip templates with @column fields, and a widget callback that changes data and redraws. They are not Bokeh's code.

Tools in the toolbar

A figure's toolbar is controlled with the tools argument, a comma-separated string of tool names:

Python
from bokeh.plotting import figure

p = figure(
    height=400,
    tools="pan,wheel_zoom,box_zoom,box_select,lasso_select,reset,save",
    active_scroll="wheel_zoom",
)

The most useful names are:

  • pan and wheel_zoom, box_zoom: navigate the plot.
  • box_select, lasso_select, tap: select marks. Selected marks stay as they are; the others fade (you can style that).
  • hover: tooltips on mouse-over (configured below).
  • reset: return to the original view; save: download a PNG of the current view.

active_scroll, active_drag and similar arguments choose which tool is active by default. Without active_scroll="wheel_zoom", the mouse wheel scrolls the page and the zoom tool needs a click in the toolbar first. This avoids trapping the page scroll on a long article.

A selection tool does not do anything by itself with the data except mark rows as selected. What happens next depends on how glyphs are styled and what else is connected to the same data source.

Hover tooltips

HoverTool shows a small box with values from the row under the pointer. Tooltips are a list of (label, template) pairs, and templates use @column to read a column of the data source:

Python
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.plotting import figure, show

source = ColumnDataSource(data={
    "name": ["Ada", "Bo", "Cy", "Di", "Ed"],
    "height": [158, 171, 183, 165, 177],
    "weight": [52.5, 68.0, 81.2, 59.9, 74.5],
    "age": [31, 45, 52, 28, 39],
    "group": ["a", "b", "b", "a", "b"],
})

p = figure(height=380, tools="pan,wheel_zoom,box_select,reset",
           x_axis_label="Height (cm)", y_axis_label="Weight (kg)")
dots = p.scatter("height", "weight", size=12, source=source)

p.add_tools(HoverTool(
    renderers=[dots],
    tooltips=[
        ("Name", "@name"),
        ("Height", "@height cm"),
        ("Weight", "@weight{0.0} kg"),
        ("Cursor", "($x, $y)"),
    ],
))
show(p)

Two kinds of fields appear in the templates. @name and @weight come from the data source columns. $x and $y are special variables such as the cursor position. A format spec in braces, like @weight{0.0}, controls numbers ({0,0} adds thousands separators, {$0,0.00} shows currency). Passing renderers=[dots] limits the tooltip to that glyph; without it a hover tool considers every renderer in the figure. For line charts, mode="vline" shows the value of the line at the vertical position of the cursor, which is friendlier than needing to hit a thin line exactly.

The first stand-in builds the template engine. It takes the same @column and @column{format} syntax and fills it from a row.

JS Tooltip templates with @column fields (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last field shows what a typo in a column name looks like in a simple engine. In Bokeh a missing column shows as ??? in the tooltip, which is a common sign that you misspelled a name.

Linked brushing

If two figures use the same ColumnDataSource, a selection in one is automatically shown in the other. This is linked brushing, and it needs no callback at all, because the selection is stored in the source:

Python
from bokeh.layouts import row

left = figure(height=350, width=350, tools="box_select,lasso_select,reset", title="Height vs weight")
left.scatter("height", "weight", source=source, size=10)

right = figure(height=350, width=350, tools="box_select,reset", title="Height vs age")
right.scatter("height", "age", source=source, size=10)

show(row(left, right))

Select a few points on the left, and the same rows are highlighted on the right, even though the right figure shows different columns. The rows are identified by their index in the source. If you give each figure its own ColumnDataSource, nothing is shared and the figures stay independent.

flowchart LR
    A["Figure A<br/>box_select"] -->|"writes selected indices"| S["Shared ColumnDataSource<br/>selected: [1, 3]"]
    S -->|"change event"| B["Figure B<br/>redraws highlighted rows"]
    S -->|"change event"| A

The selection lives in the shared source, so every figure that uses it updates.

The second stand-in is a small model of exactly this: one source object with a selection and a list of subscribers, and two views that draw different columns of the same rows.

JS Linked selection across two views (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Square brackets mark the selected names. Each box selection writes a new set of indices to the shared source, and both views redraw from that one place.

Widgets and CustomJS callbacks

Widgets are controls that live next to the chart: Slider, RangeSlider, Select (dropdown), Checkbox/CheckboxGroup, RadioButtonGroup, TextInput, DatePicker, Button and DataTable. They come from bokeh.models and are arranged with row and column from bokeh.layouts.

A widget does nothing alone. You connect it to the chart with a callback. In a standalone HTML file the callback is written in JavaScript with CustomJS:

Python
import numpy as np
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.plotting import figure, show

x = np.linspace(0, 10, 200)
source = ColumnDataSource(data={"x": x, "y": np.sin(x)})

p = figure(height=300, width=600, y_range=(-2, 2))
p.line("x", "y", source=source, line_width=2)

freq = Slider(start=0.5, end=5, value=1, step=0.1, title="Frequency")

callback = CustomJS(args=dict(source=source, freq=freq), code="""
    const x = source.data.x;
    const y = source.data.y;
    for (let i = 0; i < x.length; i++) {
        y[i] = Math.sin(freq.value * x[i]);
    }
    source.change.emit();
""")
freq.js_on_change("value", callback)

show(column(freq, p))

args is a dictionary of Python models that become JavaScript variables inside the code string. When the slider's value changes, the browser runs the code, which rewrites the y column in place and calls source.change.emit() to tell Bokeh that the data changed so it redraws. The page works as a plain file, even offline once BokehJS is available, which is a big advantage over server-based dashboards. The cost is that the logic must be JavaScript, and large computations happen in the browser.

A dropdown works the same way, with Select(title="Group", value="all", options=["all", "a", "b"]) and select.js_on_change("value", callback). A callback can also be attached to a selection: source.selected.js_on_change("indices", callback) runs when the user changes the selection, for example to recompute a summary of the selected rows.

Bokeh also supports Python callbacks (widget.on_change(...)), but those need a running Bokeh server. That is the topic of Bokeh Server and Streaming Data. If you only need small interactions, CustomJS keeps the deployment simple: just an HTML file.

The last stand-in follows the slider example: a widget with an on("value", ...) hook, a source with a column rewritten in place, and a change signal that makes views redraw.

JS A slider callback that rewrites a column (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Moving the slider changes the number of waves in the sparkline. The structure is the same as in Bokeh: a widget fires an event, a callback edits the source, and the source tells every view to redraw.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you make two Bokeh figures select together (linked brushing)?

    Selection is stored in the data source as row indices. Figures that use the same source object share that selection automatically.
  2. 2. In a HoverTool, what does @weight{0.0} do?

    The @ prefix reads a column of the data source and the braces give a format. 0.0 means one decimal place.
  3. 3. What must a CustomJS callback call after changing source.data in place?

    In-place changes are not detected automatically, so you announce them with source.change.emit(). Bokeh then redraws every glyph that uses the source.
  4. 4. Why use CustomJS instead of Python callbacks for a small interaction?

    Python callbacks need a running Bokeh server process. CustomJS code travels inside the page and runs locally.
  5. 5. Which tools argument value gives pan, mouse-wheel zoom and rectangular selection?

    tools takes a comma-separated string of tool names. Add active_scroll='wheel_zoom' if the wheel should zoom by default.

Summary

  • The tools string controls the toolbar; active_scroll and similar arguments choose defaults.
  • HoverTool tooltips are (label, template) pairs; @column{format} reads source columns and $x/$y give cursor values.
  • Figures sharing a ColumnDataSource share selections: linked brushing needs no code.
  • Widgets (Slider, Select, Checkbox and more) connect to charts with CustomJS; call source.change.emit() after changing data in place.
  • CustomJS runs in the browser and works in plain HTML; Python callbacks need the Bokeh server.
  • The Bokeh code is read-only here; the runnable examples are JavaScript stand-ins for the mechanisms.

Next: Bokeh Server and Streaming Data.