Reputation: 499
I have a dataframe for which I want to sub-select a set of rows based on a dropdown. So Given the following code:
import pandas as pd
import altair as alt
from vega_datasets import data
cars = pd.melt(data.cars(), ['Horsepower', 'Origin', 'Name', 'Year'])
cars.head()
select_box = alt.binding_select(options=list(cars['variable'].unique()))
selection = alt.selection_single(name='d_axis', fields=['variable'], bind=select_box)
alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='value',
color='Origin',
tooltip='Name'
).add_selection(
selection
).transform_filter(
selection
)
Instead of changing the X values, I want to only select cars where Origin is 'USA'.
So in effect something where
alt.Chart(cars).mark_point().encode(
becomes:
alt.Chart(cars[cars['Origin'] == selection]).mark_point().encode(
Thanks, Stephen
Upvotes: 2
Views: 1087
Reputation: 86433
You can tie the selection to the field you want to filter:
import altair as alt
from vega_datasets import data
cars = data.cars()
select_box = alt.binding_select(options=list(cars['Origin'].unique()))
selection = alt.selection_single(fields=['Origin'], bind=select_box)
alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon'
).add_selection(
selection
).transform_filter(
selection
)
Upvotes: 2