Bokeh
Bokeh treats a plot as a tree of live Python objects rather than a static picture, so you can keep a reference to a figure’s data and widgets and change them directly, with no separate bokeh serve process.

Box-selecting the lighter, more fuel-efficient cars in one plot highlights the same cars in the other. Try the app.
Installation
pip install 'shinywidgets[bokeh]'
That installs bokeh and jupyter_bokeh (which serves its JavaScript locally, so apps work offline). Nothing else to configure – output_widget() (Shiny Core) or a bare @render_bokeh function (Shiny Express) is all the UI needs.
Quick start
A figure() with no explicit size fills its card:
# Uses bokeh's own sample-data package (downloaded on first use):
# pip install bokeh_sampledata
from bokeh.plotting import figure
from bokeh.sampledata.autompg import autompg as df
from shiny.express import ui
from shinywidgets import render_bokeh
ui.page_opts(title="Bokeh quickstart", fillable=True)
with ui.card(full_screen=True):
ui.card_header("Fuel economy vs. weight (1970-82 cars)")
@render_bokeh
def plot():
p = figure(title="EPA mileage drops as cars get heavier")
p.xaxis.axis_label = "weight (lbs)"
p.yaxis.axis_label = "mpg"
p.scatter(df.weight, df.mpg, size=8, alpha=0.6)
return p
Return a figure, a layout (row, column, gridplot), any other LayoutDOM, or a jupyter_bokeh.BokehModel you built yourself, and it fills its card.
Overview
A look at what you can build. Click any of them to open the app, with its code, in Shinylive.
Link a periodic table to a scatter plot
Two linked scatter plots feeding a table
Brush one plot, highlight another
Tap a station for its detail
Box-select rows into a table
A selection drives a matplotlib histogram
Drag points to edit the data
Bokeh’s own Select and DataTable widgets
200,000 points, WebGL vs. canvas
A built-in Bokeh theme
A slider with no round trip to Python
A 2x2 grid that fills its card
The raw tap coordinates
Reacting to interaction
Every @render_bokeh output has accessors that report what the user did: plot.selected_rows(), plot.tapped(), and more. Call one from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the user does it again. For anything else, Bokeh’s own on_change()/on_event() callbacks work directly inside a reactive context – including Bokeh’s own widgets (Slider, Select, DataTable) and editing tools like PointDrawTool.
Tap for details
tapped() reports a click location in data units, not a row index, so look up the nearest point yourself:
import numpy as np
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny import req
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Tap for details", fillable=True)
rng = np.random.default_rng(7)
n = 40
src = ColumnDataSource(
{
"x": rng.uniform(0, 10, n),
"y": rng.uniform(0, 10, n),
"city": [f"Station {i}" for i in range(n)],
"temp": rng.normal(18, 5, n),
}
)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_bokeh
def plot():
p = figure(tools="tap", title="Tap a station")
p.scatter("x", "y", source=src, size=12)
return p
with ui.card():
ui.card_header("Nearest station")
@render.ui
def detail():
t = req(plot.tapped())
x, y = np.asarray(src.data["x"]), np.asarray(src.data["y"])
i = int(np.argmin((x - t.x) ** 2 + (y - t.y) ** 2))
return ui.TagList(
ui.h5(src.data["city"][i]),
ui.p(f"temperature: {src.data['temp'][i]:.1f}C"),
ui.p(f"location: ({x[i]:.1f}, {y[i]:.1f})"),
)

Select rows into a table
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="selected_rows()", fillable=True)
src = ColumnDataSource(
{
"x": [1, 2, 3, 4, 5],
"y": [2, 4, 1, 3, 5],
"name": list("abcde"),
}
)
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
@render_bokeh
def plot():
p = figure(
x_range=(0, 6),
y_range=(0, 6),
tools="tap,box_select",
active_drag="box_select",
title="Box-select some points",
)
p.scatter("x", "y", source=src, size=20)
return p
with ui.card():
ui.card_header("plot.selected_rows()")
@render.data_frame
def rows():
return plot.selected_rows()

selected_rows() already turns the plot’s ColumnDataSource into a DataFrame and indexes it for you – nothing to join by hand.
Updating in place
Because a Bokeh plot is a tree of live objects, you rarely need to rebuild it to change what it shows. Keep a Python reference to the pieces you’ll change (a module- or session-level ColumnDataSource, as in the examples above), and mutate them from a @reactive.effect that runs independently of the render function. This matters because re-rendering gives the user a brand new plot – their zoom, pan, and selection all reset to the plot’s defaults – while an in-place update leaves all of it alone and sends a small patch instead of the whole document again:
import numpy as np
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Update in place", fillable=True)
rng = np.random.default_rng(4)
full_x, full_y = rng.normal(size=200), rng.normal(size=200)
src = ColumnDataSource({"x": full_x, "y": full_y})
with ui.card(full_screen=True):
ui.input_slider("n", "Number of points", min=20, max=200, value=200, step=20)
@render_bokeh
def plot():
p = figure(title="Pan or zoom, then move the slider")
p.scatter("x", "y", source=src, size=6, alpha=0.6)
return p
@reactive.effect
def _():
# Mutates the existing ColumnDataSource instead of returning a new
# figure, so the user's current zoom/pan survives the update.
n = input.n()
src.data = {"x": full_x[:n], "y": full_y[:n]}Panned and zoomed (top-left), then the slider cut the point count to 100 – the view didn’t reset:


src.data = {...} replaces the whole source, src.data["col"] = arr patches a single column, and src.patch() updates specific rows. If an effect reads an input that shouldn’t itself trigger the update, wrap just that read in with reactive.isolate(): ....
Linking widgets
Give two figures the same ColumnDataSource and return them together from one @render_bokeh function (a source can belong to only one Bokeh document, so linked plots can’t come from separate outputs).
Linked brushing
The link itself is instant and entirely in the browser; Python still sees the selection through selected_rows(), so a sidebar can summarize it live:
# Uses bokeh's own sample-data package (downloaded on first use):
# pip install bokeh_sampledata
from bokeh.layouts import row
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.sampledata.autompg import autompg
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Linked brushing", fillable=True)
src = ColumnDataSource(autompg)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_bokeh
def plots():
tools = "box_select,lasso_select,reset"
left = figure(
title="weight vs. mpg", tools=tools, active_drag="box_select",
sizing_mode="stretch_both",
)
left.scatter("weight", "mpg", source=src, size=6, alpha=0.6)
right = figure(
title="horsepower vs. mpg", tools=tools, active_drag="box_select",
sizing_mode="stretch_both",
)
right.scatter("hp", "mpg", source=src, size=6, alpha=0.6, color="firebrick")
return row(left, right, sizing_mode="stretch_both")
with ui.card():
ui.card_header("Selection summary (Python)")
@render.text
def summary():
rows = plots.selected_rows()
if len(rows) == 0:
return "Box- or lasso-select cars in either plot."
return (
f"{len(rows)} selected\n"
f"mean mpg: {rows['mpg'].mean():.1f}\n"
f"mean weight: {rows['weight'].mean():,.0f} lbs"
)

Selection drives a histogram
selected() is just a Python list once you have it, so nothing ties it to Bokeh on the receiving end. Here a box-select in a Bokeh scatter plot drives a live matplotlib histogram of the selected points – the same pattern works for render_reactable, render_itables, or any other output:
import matplotlib.pyplot as plt
import numpy as np
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny.express import render, ui
from shinywidgets import render_bokeh, render_matplotlib
ui.page_opts(title="Bokeh selection -> matplotlib histogram", fillable=True)
rng = np.random.default_rng(6)
src = ColumnDataSource({"x": rng.normal(size=400), "y": rng.normal(size=400)})
with ui.layout_columns():
with ui.card(full_screen=True):
@render_bokeh
def scatter():
p = figure(
title="Box-select a region",
tools="box_select,reset",
active_drag="box_select",
)
p.scatter("x", "y", source=src, size=6, alpha=0.6)
return p
with ui.card(full_screen=True):
@render_matplotlib
def hist():
indices = scatter.selected() or []
fig, ax = plt.subplots()
ax.hist(np.asarray(src.data["y"])[indices], bins=15)
ax.set_title(f"y-distribution of the {len(indices)} selected points")
return fig

Accessor reference
| accessor | returns | before any interaction | across re-render | default rate policy |
|---|---|---|---|---|
selected() |
list[int]: row indices into the plot’s ColumnDataSource |
[] |
re-seeded from the new plot’s current selection ([] for a fresh plot) |
debounce, 250 ms |
selected_rows() |
pandas.DataFrame: source.to_df().iloc[indices] |
empty frame | follows selected() |
follows selected(); the source.data part isn’t rate-limited |
tapped() |
bokeh.events.Tap (.x, .y in data units, .model) |
None |
kept – holds the previous plot’s last tap until the new plot is tapped | none – every tap re-runs readers |
zoomed() |
bokeh.events.RangesUpdate (.x0, .x1, .y0, .y1, .model) |
seeded from the plot’s default ranges when they hold real values, else None |
re-seeded from the new plot’s default ranges | none |
selected() and selected_rows() need a plot (or layout) with exactly one ColumnDataSource. All four accessors attach the moment the plot renders, whether or not anything has read them yet; no warm-up read is needed. What happens to a value on a re-render differs by what it tracks: tapped() is a record of something the user did, so it’s kept until they tap the new plot; selected() and zoomed() describe the plot’s own current state, so they re-seed from the new plot. None of the four can be read inside the same @render_bokeh function that builds the plot – that raises RuntimeError; read them from a @reactive.effect instead.
selected()
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="selected()", fillable=True)
src = ColumnDataSource(
{"x": [1, 2, 3, 4, 5], "y": [2, 4, 1, 3, 5], "name": list("abcde")}
)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_bokeh
def plot():
p = figure(
x_range=(0, 6),
y_range=(0, 6),
tools="tap,box_select,lasso_select",
active_drag="box_select",
title="Tap, box, or lasso",
)
p.scatter("x", "y", source=src, size=20)
return p
with ui.card():
ui.card_header("plot.selected()")
@render.code
def selected():
return str(plot.selected())

zoomed()
import numpy as np
from bokeh.plotting import figure
from shiny import req
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="zoomed()", fillable=True)
rng = np.random.default_rng(3)
x = rng.normal(size=300)
y = rng.normal(size=300)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_bokeh
def plot():
p = figure(tools="pan,wheel_zoom,reset", active_scroll="wheel_zoom")
p.scatter(x, y, size=6, alpha=0.6)
return p
with ui.card():
ui.card_header("plot.zoomed()")
@render.text
def ranges():
z = req(plot.zoomed())
return (
f"x: [{z.x0:.2f}, {z.x1:.2f}]\n"
f"y: [{z.y0:.2f}, {z.y1:.2f}]"
)

Several ColumnDataSources
A plot (or layout) with more than one ColumnDataSource can’t use selected()/selected_rows() – they raise TypeError. Wire each source’s own on_change into a reactive.value instead, addressed to the specific source you care about:
from bokeh.layouts import row
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Several ColumnDataSources", fillable=True)
west = ColumnDataSource({"x": [1, 2, 3], "y": [1, 2, 1], "name": list("abc")})
east = ColumnDataSource({"x": [1, 2, 3], "y": [2, 1, 2], "name": list("def")})
# plot.selected() would raise TypeError here (two sources). Wire each
# source's own callback into a reactive.value instead.
picked = reactive.value(None)
west.selected.on_change("indices", lambda attr, old, new: picked.set(("west", new)))
east.selected.on_change("indices", lambda attr, old, new: picked.set(("east", new)))
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_bokeh
def plot():
left = figure(
title="west",
tools="tap,box_select",
active_drag="box_select",
x_range=(0, 4),
y_range=(0, 3),
sizing_mode="stretch_both",
)
left.scatter("x", "y", source=west, size=20)
right = figure(
title="east",
tools="tap,box_select",
active_drag="box_select",
x_range=(0, 4),
y_range=(0, 3),
sizing_mode="stretch_both",
)
right.scatter("x", "y", source=east, size=20, color="firebrick")
return row(left, right, sizing_mode="stretch_both")
with ui.card():
ui.card_header("Last selection (either source)")
@render.code
def selection():
return str(picked())

Tuning accessors
Reading on demand
Every accessor is live the moment its plot renders, so it’s safe to read one somewhere that only runs occasionally, like a download handler: the value it gets back is whatever the user last did, even on the handler’s very first run.
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Reading an accessor on demand", fillable=True)
src = ColumnDataSource(
{"x": [1, 2, 3, 4, 5], "y": [2, 4, 1, 3, 5], "name": list("abcde")}
)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
ui.card_header("Box-select some points, then download them -- no need to click anything first")
@render_bokeh
def plot():
p = figure(
x_range=(0, 6),
y_range=(0, 6),
tools="box_select",
active_drag="box_select",
)
p.scatter("x", "y", source=src, size=20)
return p
with ui.card():
@render.download_button(
filename="selection.csv", label="Download selection as CSV"
)
def download():
# plot.selected_rows() is live the moment the plot renders, so
# this reads whatever is currently selected -- even if the
# download handler itself has never run before.
yield plot.selected_rows().to_csv(index=False)

Rate limiting
selected() debounces by default (rate_policy="debounce", rate_delay=0.25), so a slow lasso only reports its final shape. Pass rate_delay=0 to @render_bokeh to see every intermediate selection as the user drags. tapped() and zoomed() aren’t rate-limited at all (Bokeh already reports once per gesture), so there’s nothing to tune for them.
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Rate limiting selected()", fillable=True)
def points():
return ColumnDataSource({"x": [1, 2, 3, 4, 5], "y": [2, 4, 1, 3, 5]})
def scatter(title):
p = figure(
x_range=(0, 6),
y_range=(0, 6),
tools="box_select",
active_drag="box_select",
title=title,
)
p.scatter("x", "y", source=points(), size=20)
return p
with ui.layout_columns():
with ui.card(full_screen=True):
@render_bokeh # default: debounced 250ms
def default_plot():
return scatter("default (debounce 250ms)")
@render.code
def default_selected():
return str(default_plot.selected())
with ui.card(full_screen=True):
@render_bokeh(rate_delay=0) # report every change immediately
def instant_plot():
return scatter("rate_delay=0")
@render.code
def instant_selected():
return str(instant_plot.selected())The same box-select gesture, same instant (no-wait) screenshot: the default plot hasn’t caught up yet (still [], its seeded empty value), the rate_delay=0 plot already has:


Beyond the accessors
reactive_read(plot.widget, ...) has nothing useful to read here: BokehModel’s own synced state doesn’t reflect selection, ranges, or anything else happening in the plot. Everything Bokeh reports arrives instead as ordinary Python-side changes to the Bokeh objects themselves (source.selected.indices, range.start, a Slider’s value, …) – the same bridge Bokeh’s own widgets and edit tools like PointDrawTool use. Wire a raw on_change()/on_event() callback into a reactive.value for anything the four accessors don’t cover:
from bokeh.models import ColumnDataSource, PointDrawTool
from bokeh.plotting import figure
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import render_bokeh
ui.page_opts(title="Editable plot", fillable=True)
edits = reactive.value(0)
src = ColumnDataSource({"x": [1, 2, 3], "y": [1, 2, 1]})
src.on_change("data", lambda attr, old, new: edits.set(edits() + 1))
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_bokeh
def plot():
p = figure(
x_range=(0, 5), y_range=(0, 5), title="Drag points, or add new ones"
)
renderer = p.scatter("x", "y", source=src, size=15, color="firebrick")
draw_tool = PointDrawTool(renderers=[renderer], add=True)
p.add_tools(draw_tool)
p.toolbar.active_tap = draw_tool
return p
with ui.card():
ui.card_header("Current points (from Python)")
@render.code
def points():
edits() # re-run whenever the source's data changes
return "\n".join(
f"({x:.1f}, {y:.1f})" for x, y in zip(src.data["x"], src.data["y"])
)

A single browser-driven change calls a hand-written callback twice; make it idempotent (setting a reactive.value is already idempotent, incrementing a counter isn’t) – the four built-in accessors already dedupe this for you.
Large data
figure(output_backend="webgl") draws glyphs on the GPU instead of the default HTML canvas 2D context. It’s a rendering-only switch: the two backends send the same ColumnDataSource data to the browser, so switching doesn’t change what crosses the wire – only how smoothly it pans and zooms once there are a lot of points on screen:
import numpy as np
from bokeh.plotting import figure
from shiny.express import ui
from shinywidgets import render_bokeh
rng = np.random.default_rng(0)
n = 200_000
x = rng.normal(size=n)
y = x * 0.5 + rng.normal(size=n)
ui.page_opts(title="WebGL vs. canvas at 200,000 points", fillable=True)
with ui.layout_columns():
with ui.card(full_screen=True):
ui.card_header('output_backend="webgl"')
@render_bokeh
def webgl_plot():
p = figure(output_backend="webgl", title="WebGL")
p.scatter(x, y, size=3, alpha=0.3)
return p
with ui.card(full_screen=True):
ui.card_header("default (canvas)")
@render_bokeh
def canvas_plot():
p = figure(title="Canvas")
p.scatter(x, y, size=3, alpha=0.3)
return p
At this scale, the WebGL panel settles into a smooth, fully-drawn scatter noticeably sooner than the canvas panel, and keeps pan/zoom smoother afterward. Below a few tens of thousands of points the difference isn’t noticeable, so default to canvas and switch only once panning or zooming starts to feel choppy.
This is the “draw it with the GPU in the browser” approach from Large data & performance. For data that doesn’t fit even on the GPU as raw points, see datashader (which renders through @render_holoviews/Bokeh) to summarize server-side instead.
Layout and sizing
- A
figurefills its output in any direction you don’t give it a size:figure()fills both ways, andfigure(height=300)fills the width at 300px tall. An explicitsizing_modeoraspect_ratioturns this off. - For a layout (
row,column,gridplot), setsizing_mode="stretch_both"on both the layout and each child figure. Setting it only on the outer layout leaves the children at Bokeh’s own default size, and the layout’s flex box then divides space unevenly between them rather than splitting it evenly. output_widget()(Shiny Core) or a plain@render_bokehfunction underui.card()(Express) is the same for Bokeh as for every other renderer; nothing Bokeh-specific to add.bokeh_dependency()is deprecated and unnecessary – BokehJS loads automatically with every Bokeh-based output, including ones created dynamically inside@render.ui.
Gotchas
- In Shiny Express, top-level code already runs once per session, so building figures and sources at module level is safe. In Shiny Core, build them inside
server()(or the render function) instead – a module-level figure would be shared by every visitor, selections included.
Learn more
- Bokeh user guide and reference
- jupyter_bokeh, the bridge
@render_bokehbuilds on - plotly: more chart types, smoother 3D
- altair: a declarative grammar of selections
- holoviews and panel: render through Bokeh, without accessors
- matplotlib: target of the cross-widget selection example above