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
