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
