liveBook · Manning

Transform_filter()

As explained in Data Storytelling with Altair and AI

transform_filter() is an Altair API method that filters data rows within a chart specification.

transform_filter() is an Altair method that keeps only rows matching a condition, letting one chart layer show a focused subset of data. It can respond to an interactive selection or use a fixed predicate. section 8.4.2 section 8.7.1

Use transform_filter() to:

  • Connect a slider selection to a chart so viewers see one selected year at a time. section 8.4.2
  • Overlay a visually emphasized layer containing only a category and year range. section 8.7.1
  • Place labels at the end of lines by retaining only December records. section 6.3.3

Filtering a focused line

base = alt.Chart(df).encode(...) chart = base.mark_line() focused = base.mark_line(strokeWidth=8).transform_filter( (alt.datum.CATEGORY == 'Salmon') & (alt.datum.YEAR_ID >= 1992) & (alt.datum.YEAR_ID <= 1998) ) section 8.7.1

Listing 8.5 Setting a slider
import pandas as pd
import altair as alt

df = pd.read_csv('data/population.csv')

# [...] 

color = '#80C11E'
slider = alt.binding_range(min=1960, max=2021,step=1)

select_year = alt.selection_point(name="Select", fields=['Year'],
                                   bind=slider)

chart = alt.Chart(df).mark_bar(
    color=color
).encode(
        y=alt.Y('Country Name:O', sort='-x', title=''),
        x=alt.X('Population:Q'),
).add_params(
    select_year
).transform_filter(
    select_year
) 

# [...]

chart.save('slider.html')

Inspect the complete slider pattern: bind a range to Year, add the selection as a chart parameter, and pass it to transform_filter(). section 8.4.2

How Data Storytelling with Altair and AI covers it

How deep it goes
Demonstrates selection-based and compound predicates with code, without detailing the underlying transformation specification.
Examples
Uses a population-by-year slider, a Salmon year-range highlight, and December labels on meal-type lines.
What it assumes
Assumes basic Altair charts, encodings, marks, and data fields while introducing selection binding through a slider.
What you can do after
Apply it via Altair to filter rows with selections or predicates and create focused chart layers.
How it connects
Connects data transformation with selections, sliders, layered charts, line charts, and interactive visualization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Storytelling with Altair and AI. The section links point to the parts of the book it draws on.