Altair Basics & Chart Object

πŸ“¦ Install

pip install altair vega_datasets
import 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"
)
PieceRole
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