altair.when#

altair.when(predicate=Undefined, *more_predicates, empty=Undefined, **constraints)#

Start a when-then-otherwise condition.

The resulting predicate is an & reduction over predicate and optional *, **, arguments.

Parameters:
predicate

A selection or test predicate. str input will be treated as a test operand.

Note

Accepts the same range of inputs as in condition().

*more_predicates

Additional predicates, restricted to types supporting &.

empty

For selection parameters, the predicate of empty selections returns True by default. Override this behavior, with empty=False.

Note

When predicate is a Parameter that is used more than once, alt.when(..., empty=...) provides granular control for each occurrence.

**constraints

Specify Field Equal Predicate’s. Shortcut for alt.datum.field_name == value, see examples for usage.

Returns:
When

A partial state which requires calling When.then() to finish the condition.

Notes

  • Directly inspired by the when-then-otherwise syntax used in polars.when.

References

polars.when

Examples

Setting up a common chart:

import altair as alt
from vega_datasets import data

source = data.cars()
brush = alt.selection_interval()
points = (
    alt.Chart(source)
    .mark_point()
    .encode(x="Horsepower", y="Miles_per_Gallon")
    .add_params(brush)
)
points

Basic if-then-else conditions translate directly to when-then-otherwise:

points.encode(color=alt.when(brush).then("Origin").otherwise(alt.value("lightgray")))

Omitting the .otherwise() clause will use the channel default instead:

points.encode(color=alt.when(brush).then("Origin"))

Predicates passed as positional arguments will be reduced with &:

points.encode(
    color=alt.when(
        brush, (alt.datum.Miles_per_Gallon >= 30) | (alt.datum.Horsepower >= 130)
    )
    .then("Origin")
    .otherwise(alt.value("lightgray"))
)

Using keyword-argument constraints can simplify compositions like:

verbose_composition = (
    (alt.datum.Name == "Name_1")
    & (alt.datum.Color == "Green")
    & (alt.datum.Age == 25)
    & (alt.datum.StartDate == "2000-10-01")
)
when_verbose = alt.when(verbose_composition)
when_concise = alt.when(Name="Name_1", Color="Green", Age=25, StartDate="2000-10-01")