altair.when#
- altair.when(predicate=Undefined, *more_predicates, empty=Undefined, **constraints)#
Start a
when-then-otherwisecondition.The resulting predicate is an
&reduction overpredicateand optional*,**, arguments.- Parameters:
- predicate
A selection or test predicate.
strinput 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
Trueby default. Override this behavior, withempty=False.Note
When
predicateis aParameterthat 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:
WhenA partial state which requires calling
When.then()to finish the condition.
Notes
Directly inspired by the
when-then-otherwisesyntax used in 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-elseconditions translate directly towhen-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
constraintscan 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")