liveBook · Manning

Condition

As explained in Data Storytelling with Altair and AI

A condition in a visualization is a criterion-dependent rule that determines values or visual properties for different data cases.

A condition is a rule that changes a chart’s visual encoding or mark according to data values. In Altair, conditions make charts more informative by distinguishing cases such as regions, countries, or categories. section 3.2 section 3.4

Build a condition by specifying:

  • The criterion to test, such as whether the Region field equals Europe. section 3.2.3
  • The value to apply when the criterion is true, such as red. section 3.2.3
  • The value to apply when the criterion is false, such as blue. section 3.2.3
  • The encoding channel that receives the rule, such as color. section 3.2.3
Listing 3.15 Using the alt.condition() method
import altair as alt
import pandas as pd

df = pd.DataFrame(
    {"Country": ["Japan", "USA", "Germany", "Spain", "France", "Italy"], 
     "Medals": [4, 6, 10, 3, 7, 8], 
     "Region":["Asia","Americas","Europe","Europe","Europe","Europe"]}) 

chart = alt.Chart(df).mark_bar().encode(
    x='Medals',
    y='Country',
    color=alt.condition(
        alt.datum.Region == 'Europe',
        alt.value('red'),      #1
        alt.value('blue')      #2
    )
)

chart.save('chart.html')

A bar chart colors European countries red and all other countries blue with alt.condition(), using alt.datum to access the Region column. section 3.2.3

Country-specific highlighting

Apply a condition to a bar chart’s color encoding: set the color to red when Country equals IT and green when Country equals FR. A practical exercise uses data3.csv, with category on x and value on y, and asks for these conditional colors through Copilot instructions. section 4.4.4

Conditions can also be built through transformations and selections, supporting interconnected charts that update synchronously. These approaches are treated separately from the basic if-else form. section 3.2.3

How Data Storytelling with Altair and AI covers it

How deep it goes
Explains alt.condition() with a criterion, true value, false value, and datum access, while deferring transformations and selections.
Examples
Demonstrates European bars in red versus blue and country-specific IT and FR colors in a bar-chart exercise.
What it assumes
Assumes basic Altair chart construction and introduces conditions alongside encodings, marks, and other chart components.
What you can do after
Apply it via Altair’s alt.condition() method to create criterion-based chart encodings.
How it connects
Connects conditions with encodings, marks, transformations, selections, interactivity, and compound charts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Storytelling with Altair and AI. The section links point to the parts of the book it draws on.