ISOM 675 · Data Visualization
Altair is a declarative visualization library in Python, built on top of Vega-Lite.
Python specification
Vega-Lite specification
Rendered chart
Data → mark → encoding → chart properties
Input data · df
| Category | Value | Group | |
|---|---|---|---|
| 0 | A | 5 | East |
| 1 | B | 8 | West |
| 2 | C | 3 | East |
Wide form
One row per Month (independent variable). Metadata appears in row and column labels.
Input data · wide_sales
| North | South | |
|---|---|---|
| Month | ||
| 1 | 12 | 9 |
| 2 | 18 | 13 |
| 3 | 15 | 17 |
Wide to long with melt()
Long form
One row per observation. Metadata appears as values in the table.
Reshaped data · long_sales
| Month | Region | Sales | |
|---|---|---|---|
| 0 | 1 | North | 12 |
| 1 | 2 | North | 18 |
| 2 | 3 | North | 15 |
| 3 | 1 | South | 9 |
| 4 | 2 | South | 13 |
| 5 | 3 | South | 17 |
It’s easier to work with long-form data in Altair. Why?
Priority is ranked 1–3. N uses distinct hues; O uses ordered shades.
| Type | Data type |
|---|---|
Q |
Quantitative: measured amounts |
N |
Nominal: categories without an order |
O |
Ordinal: categories with an order |
T |
Temporal: dates and times |
Input data · priority_points
| Hours | Impact | Priority | |
|---|---|---|---|
| 0 | 2 | 3 | 1 |
| 1 | 3 | 7 | 2 |
| 2 | 4 | 5 | 3 |
| 3 | 5 | 8 | 1 |
| 4 | 6 | 4 | 2 |
| 5 | 7 | 9 | 3 |
| Channel Type | Channels | Effect |
|---|---|---|
| Position | x, y, x2, y2, longitude, latitude, xOffset, yOffset |
Places a mark or defines its span |
| Color | color, fill |
Changes the hue or interior |
| Shape | shape |
Selects a symbol |
| Size | size |
Changes mark area or thickness |
| Facet | facet, row, column |
Repeats a view by group |
| Sequence | order |
Controls draw or stack order |
x and yx2 and y2Order sets stack position or the connection sequence within each line series.
priority_order = {"Low": 1, "Medium": 2, "High": 3}
product_segments["PriorityOrder"] = (
product_segments["Priority"].map(priority_order)
)
stack_base = alt.Chart(product_segments).mark_bar()
stack_base = stack_base.encode(
x="Product:N", y="Value:Q", color="Priority:N",
)
priority_stack = stack_base.encode(
order="PriorityOrder:Q",
color=alt.Color("Priority:N", legend=alt.Legend(
values=["High", "Medium", "Low"],
)),
)Input data · Product A
| Product | Priority | Value | PriorityOrder | |
|---|---|---|---|---|
| 0 | A | Low | 8 | 1 |
| 1 | A | Medium | 5 | 2 |
| 2 | A | High | 3 | 3 |
Facet: one chart template, split by a field. Concat: explicitly combine charts.
legend = alt.Legend(orient="right")
chart_title = alt.Title(
"Monthly sales",
subtitle="North and South, January–June",
anchor="start",
)
polished = (
base_line.encode(
x=alt.X(
"Date:T", title="Month",
axis=alt.Axis(format="%b"),
),
y=alt.Y("Sales:Q", title="Sales ($000)"),
color=alt.Color(
"Region:N", legend=legend,
),
tooltip=["Region:N", "Date:T", "Sales:Q"],
)
.properties(
width=390, height=250, title=chart_title,
)
)