Skip to content
Advertisement

In Altair equality condition doesn’t work

I’m trying to build a scatterplot in Altair where the color of the points is determined by a slider. In this example, I want to color in orange only the carse whose cylinders are equal to the one selected by the slider. The operator == inside the Altair condition doesn’t work. I tried different operators, the ones working are > >= < <= the ones not working are == !=

Here’s a non-working code:

slider = alt.binding_range(min=3, max=8, step=1, name='cyl')
selection = alt.selection_single(fields=['Cylinders'],
                                bind=slider, init={'Cylinders': 3})

alt.Chart(cars).mark_circle(size=60).encode(
    x="Miles_per_Gallon",
    y="Displacement",
    color=alt.condition(alt.datum.Cylinders == selection.Cylinders, 
                        alt.value('#f26414'), alt.value('lightgray'),
                       ),
).add_selection( 
    selection
)

How can I make equality works?

Advertisement

Answer

For equality, you can check if points are in the selection without using an operator:

color=alt.condition(selection, alt.value('#f26414'), alt.value('lightgray'))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement