Chuyển đến nội dung

Bài 17 · Altair and Vega-Lite

Selections and Interactive Altair Charts

Make Altair charts interactive with selection_interval, selection_point, bindings, conditions, linked views and tooltips, and see how selections are just predicates.

A static chart answers one question. An interactive chart lets the reader ask the next one: what is in this cluster? what happens if I hide the third group? which row is this point? Altair offers a compact vocabulary for interaction, and all of it runs in the browser through Vega-Lite, without a Python server. Once the chart has been saved or embedded, the interactions keep working with no Python process behind them.

The central idea is the selection (called a parameter in current Vega-Lite and Altair 5). A selection remembers what the user picked, such as a rectangle they dragged or the points they clicked. Then you use that memory in two ways: to change how marks look (a condition) or to filter data (a transform). This lesson covers both, plus bindings to widgets, linked views and tooltips.

Altair and Vega-Lite do not run on this site, so the chart code is read-only. The runnable examples are JavaScript stand-ins that show how a selection becomes a yes-or-no test on each row. They are simplified and are not the real Vega implementation.

Two selection types

Python
import altair as alt

brush = alt.selection_interval()                         # drag a rectangle
pick = alt.selection_point(fields=["species"])           # click marks to choose
  • selection_interval() creates a brush: the user drags a rectangle (or a horizontal band if you limit it with encodings=["x"]). The selection stores a range per encoded field.
  • selection_point() stores chosen values: click a mark to select it, shift-click to add more. With fields=["species"] it selects every row that shares the clicked mark's species, not only the clicked row.

Parameters are attached to a chart with .add_params(...). Without that call, the selection exists but nothing can trigger it.

Python
points = (
    alt.Chart(penguins)
    .mark_circle(size=70)
    .encode(x="bill_length:Q", y="body_mass:Q", color="species:N")
    .add_params(brush)
)

Dragging on this chart now draws a rectangle, yet nothing looks different. The rectangle is stored; no encoding uses it yet.

Conditions: highlight what is selected

alt.condition(selection, value_if_selected, value_if_not) switches an encoding on or off according to the selection. In Altair 5.4 and later, alt.when(selection).then(...).otherwise(...) reads the same way.

Python
points = (
    alt.Chart(penguins)
    .mark_circle(size=70)
    .encode(
        x="bill_length:Q",
        y="body_mass:Q",
        color=alt.condition(brush, "species:N", alt.value("lightgray")),
        opacity=alt.condition(brush, alt.value(1.0), alt.value(0.3)),
    )
    .add_params(brush)
)

Points inside the rectangle keep their species color; all others turn light gray. When there is no rectangle at all, Vega-Lite treats everything as selected, so the chart starts out in full color. This "empty selection selects all" rule is a default you can switch off with empty=False.

Filters: use the selection to subset data

A condition changes appearance; transform_filter(selection) removes rows. The chart doing the filtering is usually a different chart from the one that holds the selection. That is how linked views work.

Python
brush = alt.selection_interval()

scatter = (
    alt.Chart(penguins).mark_circle()
    .encode(x="bill_length:Q", y="body_mass:Q")
    .add_params(brush)
)

counts = (
    alt.Chart(penguins).mark_bar()
    .encode(x="species:N", y="count()")
    .transform_filter(brush)
)

scatter | counts

Both charts use the same data, and the second chart re-aggregates only the rows inside the brush. Drag the rectangle and the bars move. The two views never talk to Python: both read the same selection value in the browser.

flowchart LR
    U["User drags a brush"] --> S["selection value<br/>(ranges per field)"]
    S --> C1["condition<br/>colors the marks"]
    S --> F["transform_filter<br/>in another chart"]
    F --> V["bar chart updates"]

A selection is a stored value. Conditions and filters are two ways to read it.

Bindings: widgets as selections

A selection does not have to come from the mouse on the chart. Bindings connect a parameter to an input element that Vega-Lite generates beside the chart.

Python
slider = alt.binding_range(min=2700, max=6300, step=100, name="Minimum mass: ")
min_mass = alt.param(value=3500, bind=slider)

dropdown = alt.binding_select(options=[None, "Adelie", "Gentoo"], labels=["All", "Adelie", "Gentoo"], name="Species: ")
species = alt.selection_point(fields=["species"], bind=dropdown)

chart = (
    alt.Chart(penguins).mark_circle()
    .encode(
        x="bill_length:Q",
        y="body_mass:Q",
        color=alt.condition(alt.datum.body_mass >= min_mass, "species:N", alt.value("lightgray")),
    )
    .add_params(min_mass, species)
)

Other bindings exist for checkboxes and radio groups. A particularly handy one is bind="legend": alt.selection_point(fields=["species"], bind="legend") makes the legend clickable, so readers can isolate a group by clicking its swatch. Finally, chart.interactive() is a shortcut that binds the x and y scales to the mouse wheel and drag, which gives pan and zoom.

Tooltips

Tooltips are not a selection; they are an encoding channel. Give tooltip a list of fields and hovering a mark shows them.

Python
.encode(
    x="bill_length:Q",
    y="body_mass:Q",
    tooltip=["species", "island", alt.Tooltip("body_mass:Q", format=",d", title="Mass (g)")],
)

Tooltips work by hovering, so they are unavailable to touch-only and keyboard-only users. Do not hide a fact that matters only in a tooltip; show important labels directly, as the color and accessibility lesson explains.

Selections are predicates

Behind all these names sits one simple concept: a selection is a function from a row to true or false. The interval brush says "is this row's x between x0 and x1, and its y between y0 and y1?". The point selection says "is this row's species in the chosen list?". A condition chooses between two values using that function; a filter keeps the rows where it returns true.

The first stand-in builds those predicate functions and applies them to a small data set.

JS Selections as predicates

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

No output.

The interval function accepts ranges for any set of fields, which mirrors how a real brush stores one range per encoded channel. A brush limited to the x channel (encodings=["x"]) would store only bill, and the same code would still work.

Interactive legend and slider stand-in

The next stand-in is a small page with a clickable legend and a slider. It is a miniature of alt.selection_point(bind="legend") plus a binding_range threshold with a condition that grays out the rows that fail it. Click the species names and move the slider.

A clickable legend and a threshold slider

The legend buttons behave like bind="legend": clicking one toggles that group. The gray points are the "else" branch of a condition. Pressing the buttons is only a visible stand-in for what Vega-Lite does with a point selection, and the page does not support multi-select with shift-click or touch gestures.

Practical advice

  • Add parameters to one chart and read them from the others. Adding the same brush to several charts is allowed but usually not what you intend.
  • Choose selection_interval for continuous data (time, measurements) and selection_point for categories.
  • Give selections a purpose: highlight, filter or drive another view. A selection nobody reads is dead weight.
  • Remember that all data lives in the page. Interactions are instant, but a huge dataset makes them sluggish; see the large datasets lesson.
  • Altair 5 changed the API from add_selection to add_params. Old tutorials with add_selection or selection(...) need updating.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What must you call so that a selection_interval actually appears on a chart?

    A selection is a parameter. It becomes active on a chart only when you attach it with add_params.
  2. 2. In alt.condition(brush, "species:N", alt.value("lightgray")), what happens when no brush exists yet?

    By default an empty selection matches all rows, so the chart starts fully colored. Pass empty=False to change that.
  3. 3. How do you make a bar chart show only the rows inside a brush that lives on a scatter plot?

    transform_filter keeps only the rows for which the selection is true. Using it on the second chart links the two views.
  4. 4. What kind of thing is a tooltip in Altair?

    tooltip is one of the encoding channels, like x or color. It does not store a selection.

Summary

  • A selection stores what the user picked: selection_interval stores ranges, selection_point stores chosen values.
  • Attach selections with add_params; read them with alt.condition (change appearance) or transform_filter (change which rows remain).
  • Linked views work because several charts read the same selection value in the browser.
  • Bindings such as binding_range, binding_select and bind="legend" turn widgets into parameters; .interactive() adds pan and zoom.
  • Tooltips are an encoding, not a selection, and they are not reachable for every user.
  • The JavaScript stand-ins model selections as predicates; the real implementation lives in Vega.

Next: Preparing Data: Tidy Format and Reshaping

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.