Altair Basics & Chart Object
π¦ Install
pip install altair vega_datasetsimport altair as alt
import pandas as pd
from vega_datasets import data # built-in sample datasetsπ§± The core pattern
alt.Chart(df).mark_point().encode(
x="col1",
y="col2"
)| Piece | Role |
|---|---|
Chart(df) | wraps a pandas DataFrame |
.mark_X() | how to draw each row β point, bar, line, etc. |
.encode(...) | which columns map to which visual channels (x, y, colorβ¦) |
Nothing renders until
.encode()is called βmark_point()alone just sets the shape,encode()is what actually connects data to the chart.
π Sample datasets
df = data.cars()
df = data.iris()
df = data.stocks()ποΈ Displaying a chart
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
chart # Jupyter: auto-displays last expression in a cell
chart.show() # opens in browser, works outside Jupyter tooπ€ Shorthand vs explicit encoding
# shorthand β column name as a plain string, Altair infers the type
alt.Chart(df).mark_bar().encode(x="category", y="value")
# explicit β wrap in alt.X()/alt.Y() for full control
alt.Chart(df).mark_bar().encode(
x=alt.X("category", type="nominal", title="Category"),
y=alt.Y("value", type="quantitative", title="Value")
)Start with shorthand strings for speed. Switch to
alt.X(...)/alt.Y(...)the moment you need to set a title, sort order, scale, or explicit type. See Altair Data Types & Transformations for the type shorthand codes (:Q,:N, etc).
π Type shorthand suffix
alt.Chart(df).mark_bar().encode(
x="category:N", # nominal
y="value:Q" # quantitative
)Covered fully in Altair Data Types & Transformations.
π Chart size
alt.Chart(df).mark_point().encode(x="a", y="b").properties(width=400, height=300)π·οΈ Title
alt.Chart(df).mark_bar().encode(x="a", y="b").properties(title="My Chart")
alt.Chart(df).mark_bar().encode(x="a", y="b").properties(
title=alt.TitleParams("My Chart", subtitle="A subtitle here")
)π Next
Altair Marks & Encodings Β· Altair Data Types & Transformations