Can a condition be based on both a selection and a predicate?

Viewed 109

Is it possible to combine a selection and a predicate in a condition? I would like to color points on a scatterplot only if the group is selected and above a certain value.

import altair as alt
from vega_datasets import data

source = data.cars()

selection = alt.selection_multi(fields=['Origin'])
color = alt.condition(
    selection & (alt.datum.Miles_per_Gallon > 18),
    alt.Color('Origin:N'),
    alt.value('lightgray')
)

alt.Chart(source).mark_circle().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color=color,
    tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
).add_selection(
    selection
)

Trying to compound the selection and the predicate raises:

Javascript Error: Cannot find a selection named "(datum.Miles_per_Gallon > 18)".

The code works with either just the selection or the condition, but not both. The only solution I can think of is layering a scatterplot on top with all the data points below the threshold colored gray. Appreciate any help, thanks!

1 Answers

It looks like the & operator does not work properly between a selection and an expression (tracked by this issue in the Altair repository). You can work around this by using the underlying schema object instead:

color = alt.condition(
    alt.LogicalAndPredicate(**{'and': [selection, '(datum.Miles_per_Gallon > 18)']}),
    alt.Color('Origin:N'),
    alt.value('lightgray')
)

The resulting chart looks like this when the selection is empty: enter image description here

Related