Altair - Interactive Legend to only show selected elements

Viewed 494

I've got the following code

brush = alt.selection_interval()
selection = alt.selection_multi(fields=['Sex'])
color = alt.condition(selection,
                      alt.Color('Sex:N', legend=None),
                      alt.value('white'))

scatter = alt.Chart(abaloneData).mark_circle().encode(
    alt.X(alt.repeat("column"), type='quantitative'),
    alt.Y(alt.repeat("row"), type='quantitative'),
    color=color
).properties(
    width=140,
    height=140
).repeat(
    row= ['Ring Number', 'Diameter',  'Shell Length', 'Height'],
    column=['Whole Wt', 'Shucked Wt', 'Viscera Wt', 'Shell Wt']
    #try switching these to see which wa looks better 
).add_selection(
    brush
)
legend = alt.Chart(abaloneData).mark_point().encode(
    y=alt.Y('Sex:N', axis=alt.Axis(orient='right')),
    color=color
).add_selection(
    selection
)
scatter | legend

But I wanted to find a way to make the other elements in my plot disappear when a user selects to filter by sex from the legend. Is there any way that I can do this? I know that there's a way to do it with radio buttons and a dropdown filter but I just wanted to know if it was also possible to do it with the legend.

Thanks

1 Answers

You could use a native interactive legend and condition the opacity on the selection. Something like this (untested because you did not provide any example data):

selection = alt.selection_multi(fields=['Sex'], bind='legend')

scatter = alt.Chart(abaloneData).mark_circle().encode(
    alt.X(alt.repeat("column"), type='quantitative'),
    alt.Y(alt.repeat("row"), type='quantitative'),
    color=alt.Color('Sex:N'),
    opacity=alt.condition(selection, alt.value(1.0), alt.value(0.0))
).properties(
    width=140,
    height=140
).repeat(
    row= ['Ring Number', 'Diameter',  'Shell Length', 'Height'],
    column=['Whole Wt', 'Shucked Wt', 'Viscera Wt', 'Shell Wt']
    #try switching these to see which wa looks better 
).add_selection(
    selection
)
Related