Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 31 ยท Altair and Vega-Lite

Altair and the Grammar of Graphics

Learn how Altair describes charts declaratively: Chart, mark and encode, the four data types Q, N, O and T, and the Vega-Lite spec every chart turns into.

Plotly and Bokeh both let you build a chart by creating objects and adjusting their properties. Altair takes a different road. You do not say "draw a bar here, then an axis there". You say what the data means and let the library work out the drawing: this column goes on the x position, that column decides the color, and the mark is a bar. Everything else (axes, scales, legends, sensible defaults) follows from those few statements.

This style is called declarative, and it comes from the grammar of graphics, an idea that a chart is a small sentence made of data, a mark and a set of encodings. Altair is a Python library that lets you write that sentence. It does not draw anything itself. It produces a JSON document in the Vega-Lite format, and a JavaScript library in the browser turns that document into pixels. Understanding this split is the key to the whole Altair family of lessons.

Altair, Vega-Lite and a browser renderer cannot run on this site. The Altair code below is read-only. The runnable examples are honest stand-ins: small Python classes that mimic how Altair builds a specification, so you can see the idea working. When a stand-in differs from the real library, the text says so.

The three-part sentence

Every Altair chart has the same three parts.

Python
import altair as alt
import pandas as pd

sales = pd.DataFrame({
    "city": ["Oslo", "Lima", "Kyoto", "Cairo"],
    "revenue": [120, 95, 150, 80],
})

chart = (
    alt.Chart(sales)           # 1. the data
    .mark_bar()                # 2. the mark: what shape to draw
    .encode(                   # 3. the encodings: which column drives which visual channel
        x="city",
        y="revenue",
    )
)
chart  # in a notebook, this displays the chart
  • Data is usually a pandas DataFrame, but a list of dictionaries, a URL to a CSV or JSON file, or a Polars frame also works.
  • Mark is the geometric shape: mark_bar, mark_line, mark_point, mark_circle, mark_area, mark_rect, mark_text, mark_boxplot and a few more.
  • Encode links channels (x, y, color, size, shape, opacity, tooltip, text, row, column) to columns of the data.

Notice what is missing. You never created an axis, picked a scale or computed a pixel position. In Plotly Express the call px.bar(sales, x="city", y="revenue") looks similar for a simple chart, but the moment you need to change the design, the two libraries diverge: Altair keeps asking you to change the encoding, while Plotly asks you to change traces and layout.

flowchart LR
    D["Python data<br/>(DataFrame)"] --> A["Altair<br/>Chart + mark + encode"]
    A --> S["Vega-Lite spec<br/>(JSON)"]
    S --> V["Vega-Lite in the browser<br/>(vega-embed)"]
    V --> P["SVG or canvas pixels"]

Altair only builds the JSON in the middle. A JavaScript runtime draws the chart.

Method chaining and immutability

Altair objects are immutable in practice: methods such as mark_bar(), encode() and properties() return a new chart and leave the original untouched. That is why chains are written one method per line, and why you can reuse a base chart safely.

Python
base = alt.Chart(sales).encode(x="city", y="revenue")

bars = base.mark_bar()
points = base.mark_point(size=120, color="crimson")

Both bars and points share the same encodings, but changing one never affects the other. Later lessons on layering and faceting rely on this habit.

Marks accept properties that apply to the whole mark, such as mark_bar(color="steelblue", cornerRadiusEnd=4). Chart-wide settings go in .properties(width=400, height=250, title="Revenue by city").

Data types: Q, N, O and T

Choosing a scale for a column depends on what kind of values it holds. Vega-Lite names four data types, and each has a one-letter shorthand.

Type Shorthand Meaning Typical examples Default scale
Quantitative Q Numbers you can add, subtract and measure revenue, temperature, age continuous linear
Nominal N Categories with no order city, product, color discrete, distinct hues
Ordinal O Categories with a meaningful order small / medium / large, grade A to F discrete, ordered
Temporal T Dates and times order date, timestamp time axis

The type changes the result a lot. The number 2024 as a quantitative field gives a continuous axis with ticks like 2,000 and 2,020. As an ordinal or temporal field it becomes a sequence of years. A zip code is a number, but it should be nominal, because averaging zip codes is meaningless.

You declare a type with a shorthand suffix, or with an explicit encoding class:

Python
# Shorthand: "column:TYPE"
alt.Chart(sales).mark_bar().encode(x="city:N", y="revenue:Q")

# The same thing, spelled out
alt.Chart(sales).mark_bar().encode(
    x=alt.X("city", type="nominal", title="City"),
    y=alt.Y("revenue", type="quantitative", title="Revenue (k$)"),
)

If you leave the suffix off and use a DataFrame, Altair infers the type from the column's dtype: floats and ints become Q, strings and categoricals become N, datetimes become T. Inference is convenient and sometimes wrong (a column of year integers), so make the type explicit whenever the meaning matters. Notice that the long-form encoding classes (alt.X, alt.Color) are where you attach titles, scales, sorting and axis options.

From chart to specification

Call chart.to_dict() (or chart.to_json()) and you get the Vega-Lite specification. For the chart above it looks roughly like this. The exact keys vary between Altair versions, so treat this as a sketch:

JSON
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": { "name": "data-1a2b3c" },
  "datasets": {
    "data-1a2b3c": [
      { "city": "Oslo", "revenue": 120 },
      { "city": "Lima", "revenue": 95 }
    ]
  },
  "mark": { "type": "bar" },
  "encoding": {
    "x": { "field": "city", "type": "nominal" },
    "y": { "field": "revenue", "type": "quantitative" }
  }
}

Real Altair stores the rows in a top-level datasets object and refers to them by a generated name, so several layers can share one copy of the data. Everything under mark and encoding is the grammar sentence written as JSON. This is why Altair charts are easy to save, diff, test and share: the chart is a data structure. The next lesson reads and writes that JSON directly.

A stand-in for Altair's builder

The following Python class is not Altair. It is a tiny imitation that shows the core mechanism: each method returns a new object holding a spec dictionary, and to_dict() returns the finished dictionary. The type-shorthand parser works the way Altair's does for the simple field:T form.

Python A mini Chart class that builds a Vega-Lite-style spec

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that base never gained a mark even though bars and points were both derived from it. That is the immutability from earlier. What the stand-in leaves out is large: real Altair validates every key against the Vega-Lite JSON schema, supports dozens of channels, infers types from DataFrames and manages the datasets block.

Type shorthand in practice

Beyond the type letter, Altair's shorthand can also carry an aggregate: "mean(revenue):Q" means "average the revenue for each group". The next TryIt extends the parser so you can see the rule: an optional function name, the field in parentheses, then an optional type.

Python Parsing aggregate shorthand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real Altair accepts more forms than this stand-in (for example count() with no field, which our parser handles as a special case, and the temporal-unit prefixes such as yearmonth(date)). The point is the grammar: a short string expands into a small JSON object. The transforms lesson shows the longer forms.

Reading a chart as a sentence

Once you see charts as sentences, you can translate between them quickly. "A scatter of weight against height, colored by species, sized by age" is:

Python
alt.Chart(animals).mark_circle().encode(
    x="height:Q", y="weight:Q", color="species:N", size="age:Q"
)

To switch to a bar chart of the average weight per species, you change the mark and the encodings (x="species:N", y="mean(weight):Q"). You never write a loop that groups the data. This is the real strength of the declarative approach, and the weakness too: when you need a very unusual chart, you must find a way to say it in the grammar rather than drawing it by hand.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Altair itself produce when you build a chart?

    Altair is a Python API for writing Vega-Lite specs. The drawing happens in the browser, usually through vega-embed.
  2. 2. Which data type should you use for a column of zip codes stored as integers?

    Zip codes are labels. They cannot be meaningfully added or averaged and have no order that matters, so they are nominal.
  3. 3. What happens when you call base.mark_bar() on an existing Altair chart called base?

    Altair methods return new chart objects, which makes it safe to share a base chart between several variations.
  4. 4. In the line x="mean(price):Q", what does mean(...) do?

    An aggregate in the shorthand tells Vega-Lite to compute the statistic for each group defined by the other encodings.

Summary

  • Altair is declarative: you describe data, a mark and encodings, and Vega-Lite works out axes, scales and legends.
  • A chart is built by chaining Chart(data).mark_*().encode(...), and every method returns a new object.
  • Vega-Lite has four data types: quantitative, nominal, ordinal and temporal (Q, N, O, T). Make the type explicit when inference could be wrong.
  • to_dict() returns the JSON spec, so charts are plain data you can save, test and share.
  • The Python classes in this lesson are stand-ins; the real library validates against the Vega-Lite schema and does much more.

Next: Reading and Writing Vega-Lite JSON