Altair heatmap with dropdown variable selector

Viewed 193

Consider this toy dataset:

import pandas as pd
import altair as alt

df = pd.read_json('https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json')
df = df.groupby(['Origin', 'Year'])[['Miles_per_Gallon', 'Weight_in_lbs', 'Displacement']].mean().reset_index()
df = pd.melt(df, id_vars=['Origin', 'Year'], value_vars=['Miles_per_Gallon', 'Weight_in_lbs', 'Displacement'])
df.head()


    Origin  Year    variable    value
0   Europe  1970-01-01  Miles_per_Gallon    25.20
1   Europe  1971-01-01  Miles_per_Gallon    28.75
2   Europe  1972-01-01  Miles_per_Gallon    22.00
3   Europe  1973-01-01  Miles_per_Gallon    24.00
4   Europe  1974-01-01  Miles_per_Gallon    27.00

I would like to make a heatmap where I can choose which variable I want to encode the fill color. From the docs, it seems like this would work, because the dropdown selector would subset the df according to the selected variable:

dropdown = alt.binding_select(options=list(df.variable.drop_duplicates()))
alt.Chart(df).mark_rect().encode(
    x='Origin:N', 
    y='Year:T', 
    color='value:Q',
).add_selection(
    alt.selection_single(fields=['variable'], bind=dropdown, name='Select')
)

This makes a heatmap, but the selector has no effect. What is the correct way to select the variable to use for the heatmap color encoding?

enter image description here

1 Answers

You would need to assign the selection to a variable name and both add it to the chart via add_selection as well as bind it to filter the data via transform_filter.

dropdown = alt.binding_select(options=list(df.variable.drop_duplicates()))
selection = alt.selection_single(fields=['variable'], bind=dropdown, name='Select')

alt.Chart(df).mark_rect().encode(
    x='Origin:N', 
    y='Year:T', 
    color='value:Q',
).add_selection(
    selection
).transform_filter(
    selection
)
Related