Filtering Data
Filtering means showing a subset of your data: selecting points with the mouse, applying a range slider, or driving visibility from a dropdown. In Bokeh the pattern is the same everywhere - a ColumnDataSource holds the full data, and you update a second "view" source (or the CDS itself) with the filtered rows.
Selection-Driven Filtering
import pandas as pd
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, BoxSelectTool
df = pd.DataFrame({
"x": [1, 2, 3, 4, 5, 6, 7, 8],
"y": [5, 3, 6, 2, 7, 4, 8, 3],
})
source = ColumnDataSource(df)
p = figure(tools="pan,box_select,reset")
p.circle("x", "y", source=source, size=10)
# a second plot showing only the selected points
sel = figure(title="Selected")
sel_src = ColumnDataSource(data={"x": [], "y": []})
sel.circle("x", "y", source=sel_src, size=10)
box = p.select(type=BoxSelectTool)
def on_selection():
idx = box.selected.indices
if idx:
sel_src.data = {"x": df["x"].iloc[idx].tolist(),
"y": df["y"].iloc[idx].tolist()}
box.on_select_event = on_selection
Range Slider Filtering
from bokeh.models import RangeSlider
slider = RangeSlider(start=0, end=100, value=(0, 100),
title="Value range", step=1)
def update(attr, old, new):
lo, hi = new
mask = (df["x"] >= lo) & (df["x"] <= hi)
source.data = df[mask].to_dict()
slider.on_change("value", update)
Categorical Filtering (Dropdown)
from bokeh.models import Select
select = Select(value="A", options=["A", "B", "C"], title="Group")
def update(attr, old, new):
source.data = df[df["grp"] == new].to_dict()
select.on_change("value", update)
Server-Side Filtering (Bokeh Server)
For large data, keep the full DataFrame in the server app and sync only the filtered rows to the browser CDS. The server callback pattern (covered in the Bokeh Server chapter) is the scalable version of the same idea.
Tips
- Filter by updating source.data (or a view CDS) rather than re-creating glyphs.
- Use boolean masks on the DataFrame; convert with .to_dict() for the CDS.
- Reset tools should restore the full dataset.
Summary
Filter Bokeh plots by updating a ColumnDataSource with a subset of the data: mouse selection via BoxSelectTool's selected indices, a RangeSlider for numeric bounds, or a Select for categorical values. For large data, run the filter server-side and sync only the visible rows to the browser.