How to Link Plots in Bokeh: Shared Axes, Selections and Sliders

Pan several Bokeh plots together, select points in one and highlight them in another, share a crosshair, and add a slider that runs in the browser.

To link plots in Bokeh, share objects between them. Give a second figure x_range=first.x_range and the two pan and zoom together. Draw both from the same ColumnDataSource and selecting points in one highlights them in the other. Neither needs a Python server. This post uses Bokeh 3.10.

Quick Example

Two views of the same 150 sample trail runs. Drag a box over points in either chart and the same runs light up in the other.

import numpy as np
from bokeh.layouts import row
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show

rng = np.random.default_rng(31)
distance = rng.uniform(5, 30, 150)
climb = distance * rng.uniform(10, 65, 150)
pace = 5.4 + 0.045 * climb / distance + 0.025 * distance + rng.normal(0, 0.25, 150)
heart = 128 + 5.5 * (pace - 5) + 0.5 * distance + rng.normal(0, 4, 150)
source = ColumnDataSource(dict(distance=distance, climb=climb, pace=pace, heart=heart))

tools = "box_select,lasso_select,reset"
style = dict(source=source, size=8, color="#0c8599",
             selection_color="#e8590c", nonselection_alpha=0.15)

left = figure(width=340, height=340, sizing_mode="scale_width", tools=tools,
              x_axis_label="Distance (km)", y_axis_label="Climb (m)")
left.scatter("distance", "climb", **style)

right = figure(width=340, height=340, sizing_mode="scale_width", tools=tools,
               x_axis_label="Pace (min/km)", y_axis_label="Heart rate (bpm)")
right.scatter("pace", "heart", **style)

source.selected.indices = np.flatnonzero((distance > 20) & (climb > 900)).tolist()

layout = row(left, right, sizing_mode="stretch_width")
show(layout)

Two linked scatter plots of trail runs; the long hilly runs selected in the distance and climb plot are also highlighted in the pace and heart rate plot

The script starts with the long, hilly runs selected (over 20 km and 900 m of climbing). In the right chart they cluster toward slower paces and higher heart rates. The reset button clears the selection.

source.selected.indices only sets the starting state. Delete that line to start with nothing selected.

Pass one figure's range to another. Here three stacked charts of server metrics share the x-axis, so zooming into a spike in one zooms all of them.

import pandas as pd
from bokeh.layouts import column

times = pd.date_range("2026-05-04", periods=288, freq="5min")
requests = 300 + 220 * np.sin(np.linspace(-1.8, 4.4, 288)) + rng.normal(0, 18, 288)
requests[170:185] += 330  # a traffic spike
latency = 80 + 0.18 * requests + rng.normal(0, 6, 288)
errors = rng.poisson(np.clip((requests - 450) / 40, 0.2, None))
metrics = ColumnDataSource(dict(time=times, requests=requests, latency=latency, errors=errors))

panels = []
for name, label, color in [("requests", "Requests/s", "#1c7ed6"),
                           ("latency", "Latency (ms)", "#7048e8"),
                           ("errors", "Errors", "#e03131")]:
    shared = {"x_range": panels[0].x_range} if panels else {}
    fig = figure(height=170, sizing_mode="stretch_width", x_axis_type="datetime",
                 y_axis_label=label, tools="xpan,xwheel_zoom,reset",
                 active_scroll="xwheel_zoom", **shared)
    fig.line("time", name, source=metrics, color=color, line_width=2)
    panels.append(fig)

dashboard = column(*panels, sizing_mode="stretch_width")
show(dashboard)

Three stacked line charts of requests, latency and errors sharing a time axis, all jumping during the same afternoon traffic spike

The traffic spike in the afternoon shows up in latency and errors at the same time. The x-prefixed tools (xpan, xwheel_zoom) leave the y-axes alone. To link the y-axes too, share y_range, which only makes sense when the plots use the same units.

Share a Crosshair Across Plots

A CrosshairTool can take a Span as its overlay. Give the same span to several plots and the vertical line follows the mouse through all of them.

from bokeh.models import CrosshairTool, Span

# A new source: models already shown in one document can't join another.
metrics_copy = ColumnDataSource(dict(metrics.data))
cursor = Span(dimension="height", line_color="#495057", line_dash="dashed")
panels = []
for name, color in [("requests", "#1c7ed6"), ("latency", "#7048e8")]:
    shared = {"x_range": panels[0].x_range} if panels else {}
    fig = figure(height=200, sizing_mode="stretch_width", x_axis_type="datetime",
                 title=name.title(), toolbar_location=None, **shared)
    fig.line("time", name, source=metrics_copy, color=color, line_width=2)
    fig.add_tools(CrosshairTool(overlay=cursor))
    panels.append(fig)

crosshair = column(*panels, sizing_mode="stretch_width")
show(crosshair)

Requests and latency charts with a dashed vertical crosshair crossing both

Arrange Linked Plots With gridplot

gridplot() takes a list of rows and merges the plots' toolbars into one. Use None for an empty cell.

from bokeh.layouts import gridplot

columns = {"distance": "Distance (km)", "climb": "Climb (m)", "pace": "Pace (min/km)"}
names = list(columns)
shared_source = ColumnDataSource(dict(source.data))

grid = []
for i, y in enumerate(names[1:], start=1):
    cells = []
    for j, x in enumerate(names[:2]):
        if j >= i:
            cells.append(None)
            continue
        fig = figure(width=300, height=260, tools="box_select,reset",
                     x_axis_label=columns[x], y_axis_label=columns[y])
        fig.scatter(x, y, source=shared_source, size=6, color="#5f3dc4",
                    selection_color="#f08c00", nonselection_alpha=0.12)
        cells.append(fig)
    grid.append(cells)
fastest = pace < np.quantile(pace, 0.25)
shared_source.selected.indices = np.flatnonzero(fastest).tolist()

matrix = gridplot(grid, sizing_mode="scale_width")
show(matrix)

Triangle of three linked scatter plots of distance, climb and pace with the fastest runs highlighted in orange in each

The highlighted runs are the fastest quarter by pace. They average about 350 m of climbing against 820 m for the rest, while their distances cover a similar mix.

Add a Slider With CustomJS

A CustomJS callback runs JavaScript in the browser, so it keeps working in a saved HTML file. This slider changes the smoothing window of a line.

from bokeh.models import CustomJS, Slider

noisy = 50 + np.cumsum(rng.normal(0, 3, 200))
series = ColumnDataSource(dict(x=np.arange(200), raw=noisy, smooth=noisy.copy()))

fig = figure(height=320, sizing_mode="stretch_width", title="Rolling mean")
fig.line("x", "raw", source=series, color="#ced4da", legend_label="Raw")
fig.line("x", "smooth", source=series, color="#c2255c", line_width=3,
         legend_label="Smoothed")
fig.legend.location = "top_left"

slider = Slider(start=1, end=40, value=1, step=1, title="Window (points)")
slider.js_on_change("value", CustomJS(args=dict(series=series), code="""
    const raw = series.data.raw;
    const w = cb_obj.value;
    series.data.smooth = Array.from(raw, (_, i) => {
        let sum = 0, n = 0;
        for (let k = Math.max(0, i - w + 1); k <= i; k++) { sum += raw[k]; n++; }
        return sum / n;
    });
    series.change.emit();
"""))
slider.value = 12
kernel = [noisy[max(0, i - 11):i + 1].mean() for i in range(200)]
series.data["smooth"] = np.array(kernel)  # match the slider's starting value

smoother = column(slider, fig, sizing_mode="stretch_width")
show(smoother)

A noisy grey series and its smoothed rolling mean in red, under a slider set to a window of 12 points

Setting slider.value in Python doesn't run the JavaScript callback, which is why the code computes the starting line itself.

CustomJS or Bokeh Server?

CustomJS and shared objects Bokeh server (bokeh serve)
Code runs in The browser, in JavaScript A Python process
Works in a saved HTML file Yes No
Can call pandas, a database or a model No Yes
Use it for Linking, filtering and simple math on data already in the page Anything that needs Python after the page loads

Practical Tips

  • Linked selection matches rows by position, so both plots need to use the same ColumnDataSource. Two separate sources built from the same DataFrame don't link.
  • Sharing a source also means the data is stored once, however many plots draw it.
  • RuntimeError: Models must be owned by only a single document means you reused a source or plot in a second show(), save() or embed call in the same script. Create a new one, such as ColumnDataSource(dict(source.data)).
  • Add "tap" to tools to select single points with a click.

Similar Topics