Interactive Selections and Brushing in Altair

Add brushing, click selections, clickable legends, and dropdown filters to Altair charts with selection_interval() and selection_point().

To add interaction in Altair, create a selection with alt.selection_interval() (drag a box) or alt.selection_point() (click), attach it with .add_params(), and use it in a condition or a filter. It all runs in the browser, so it works in notebooks and saved HTML files without a Python server. The code here targets Altair 6.2.

Quick Example

Drag across the scatter plot below. The bar chart recounts only the rides inside your box.

import altair as alt
import numpy as np
import pandas as pd

# Sample data: 300 bike share rides.
rng = np.random.default_rng(22)
n = 300
rider = rng.choice(["Member", "Casual", "Student"], n, p=[0.5, 0.3, 0.2])
speed = pd.Series(rider).map({"Member": 13.5, "Casual": 9.5, "Student": 11.5})
distance = (rng.gamma(3.0, 0.9, n)
            * pd.Series(rider).map({"Member": 0.9, "Casual": 1.3, "Student": 0.8}))
rides = pd.DataFrame({
    "rider": rider,
    "bike": rng.choice(["Classic", "Electric"], n, p=[0.65, 0.35]),
    "distance_km": distance.round(2),
    "minutes": (distance / (speed + rng.normal(0, 1.8, n)) * 60 + 2).round(1),
})

brush = alt.selection_interval()

points = alt.Chart(rides, width=480, height=280).mark_circle(size=55).encode(
    x=alt.X("distance_km:Q", title="Distance (km)"),
    y=alt.Y("minutes:Q", title="Duration (minutes)"),
    color=alt.when(brush).then("rider:N").otherwise(alt.value("#d9d9d9")),
    tooltip=["rider", "bike", "distance_km", "minutes"],
).add_params(brush)

counts = alt.Chart(rides, width=480, height=90).mark_bar().encode(
    x=alt.X("count():Q", title="Rides selected"),
    y=alt.Y("rider:N", title=None),
    color="rider:N",
).transform_filter(brush)

linked = points & counts
linked

Interactive Altair scatter plot of ride distance against duration with a box brushed over mid-length rides, linked to a bar chart counting the selected rides by rider type

Three lines do the work. add_params(brush) makes the scatter plot listen for drags, alt.when(brush) colors the points inside the box, and transform_filter(brush) keeps only those rows in the bar chart. With nothing selected, an Altair selection matches every row, so the charts start fully colored. Double-click to clear the box.

How Do I Brush Along One Axis Only?

Pass encodings=["x"] to selection_interval() to select a range of x values at any height. Give it a value to start with a range already selected.

x_brush = alt.selection_interval(encodings=["x"], value={"x": [2, 5]})

band = alt.Chart(rides, width=480, height=280).mark_circle(size=55).encode(
    x=alt.X("distance_km:Q", title="Distance (km)"),
    y=alt.Y("minutes:Q", title="Duration (minutes)"),
    color=alt.when(x_brush).then(alt.value("#7b2d8b")).otherwise(alt.value("#d9d9d9")),
).add_params(x_brush)
band

Altair scatter plot with a vertical band selected from 2 to 5 kilometers, points inside colored purple and the rest gray

value uses data units, not pixels. This is a good default when you want to pick a window of time on a line chart.

Select Points by Clicking

selection_point() selects what you click. With fields=["rider"], clicking one bar selects that rider type, and any chart that uses the selection responds. Shift-click selects more than one.

pick = alt.selection_point(fields=["rider"])

bars = alt.Chart(rides, width=150, height=260, title="Click a bar").mark_bar().encode(
    x=alt.X("rider:N", title=None, axis=alt.Axis(labelAngle=0)),
    y=alt.Y("count():Q", title="Rides"),
    color=alt.Color("rider:N", legend=None),
    opacity=alt.when(pick).then(alt.value(1.0)).otherwise(alt.value(0.3)),
).add_params(pick)

histogram = alt.Chart(rides, width=300, height=260, title="Ride duration").mark_bar(
    color="#4c78a8"
).encode(
    x=alt.X("minutes:Q", bin=alt.Bin(step=5), title="Minutes"),
    y=alt.Y("count():Q", title="Rides"),
).transform_filter(pick)

click_chart = bars | histogram
click_chart

Interactive Altair bar chart of rides by rider type linked to a histogram of ride duration that filters to the clicked bar

Without fields, a point selection picks the individual mark you click. For line charts, add nearest=True and on="pointerover" to select whatever is closest to the mouse.

Highlight Series From the Legend

Add bind="legend" and the legend becomes the control. Clicking an entry fades the other series.

legend_pick = alt.selection_point(fields=["rider"], bind="legend")

legend_chart = alt.Chart(rides, width="container", height=300).mark_circle(size=60).encode(
    x=alt.X("distance_km:Q", title="Distance (km)"),
    y=alt.Y("minutes:Q", title="Duration (minutes)"),
    color=alt.Color("rider:N", title="Click to focus"),
    opacity=alt.when(legend_pick).then(alt.value(0.9)).otherwise(alt.value(0.08)),
).add_params(legend_pick)
legend_chart

Interactive Altair scatter plot of ride distance against duration where clicking a legend entry fades the other rider types

Filter With a Dropdown, Radio Buttons, or Slider

Bind a selection or variable to an HTML input. binding_select makes a dropdown, binding_radio makes radio buttons, and binding_range makes a slider.

bike_menu = alt.binding_select(options=[None, "Classic", "Electric"],
                               labels=["All", "Classic", "Electric"], name="Bike ")
bike_pick = alt.selection_point(fields=["bike"], bind=bike_menu)

max_km = alt.param(value=9, bind=alt.binding_range(min=1, max=9, step=0.5,
                                                    name="Max distance (km) "))

filtered = alt.Chart(rides, width="container", height=280).mark_circle(size=55).encode(
    x=alt.X("distance_km:Q", title="Distance (km)", scale=alt.Scale(domain=[0, 9])),
    y=alt.Y("minutes:Q", title="Duration (minutes)",
            scale=alt.Scale(domain=[0, 70])),
    color="rider:N",
).add_params(bike_pick, max_km).transform_filter(bike_pick).transform_filter(
    alt.datum.distance_km <= max_km
)
filtered

Altair scatter plot of rides with a bike type dropdown and a maximum distance slider underneath

The None option clears the dropdown selection, which shows all rows. Fixing both axis domains keeps the axes from jumping around as you filter. alt.param() creates a plain variable, which you can use in an expression like alt.datum.distance_km <= max_km.

Pan and Zoom

For pan and zoom alone, call .interactive() on a chart: drag to move and scroll to zoom. To zoom only along x, write .interactive(bind_y=False).

zoomable = alt.Chart(rides, width=480, height=280).mark_circle(size=55).encode(
    x="distance_km:Q", y="minutes:Q", color="rider:N",
).interactive()
zoomable

A drag can only mean one thing, so don't combine .interactive() with an interval brush on the same chart.

Which Selection Should I Use?

Goal Code
Drag a box over points selection_interval()
Drag a range on one axis encodings=["x"]
Click bars or points selection_point()
Follow the mouse selection_point(nearest=True)
Click the legend selection_point(bind="legend")
Dropdown or radio filter bind=alt.binding_select(...)
Slider bind=alt.binding_range(...)
Pan and zoom .interactive()

Practical Tips

  • Use the selection in alt.when() to restyle marks and in transform_filter() to remove rows.
  • selection_single, selection_multi, and add_selection are from Altair 4. Use selection_point and add_params.
  • alt.when() was added in Altair 5.5. Older code writes alt.condition(brush, "rider:N", alt.value("gray")), which still works.
  • Pass empty=False to a selection if nothing should match until the user selects something.
  • Interaction needs the HTML or notebook output. A PNG export shows only the starting state, so save the chart as HTML to share it.
  • Python can't read these selections from a plain chart. In Streamlit, st.altair_chart(..., on_select="rerun") returns them; see charts in Streamlit.

Similar Topics