Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 31 ยท Altair and Vega-Lite

Reading and Writing Vega-Lite JSON

Learn the structure of a Vega-Lite specification: data, mark, encoding, transform and scale. Read any Altair chart as JSON and embed it with vega-embed.

Every Altair chart ends up as a Vega-Lite JSON document. If you can read that document, you can debug any Altair chart, copy examples from non-Python sources, hand a chart to a JavaScript developer and write charts without Python at all. Vega-Lite is a small language: a spec is an object with a handful of top-level keys, and almost every chart you will meet uses the same five.

This lesson walks through those keys, shows how a spec becomes a chart in a web page with vega-embed, and then lets you run a deliberately tiny renderer so you can watch a spec turn into SVG shapes. The previous lesson introduced the Python side; here you work with the JSON directly.

Vega-Lite and vega-embed are loaded from a CDN in a real page, and the TryIt sandbox here does not fetch them. The JSON and HTML in the plain code blocks are read-only. The runnable examples use a small renderer written for this lesson. It understands only a few marks and encodings, and it does not behave exactly like Vega-Lite.

The five keys you will always see

A minimal spec:

JSON
{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Revenue by city",
  "data": {
    "values": [
      { "city": "Oslo", "revenue": 120 },
      { "city": "Lima", "revenue": 95 },
      { "city": "Kyoto", "revenue": 150 }
    ]
  },
  "mark": "bar",
  "encoding": {
    "x": { "field": "city", "type": "nominal" },
    "y": { "field": "revenue", "type": "quantitative" }
  }
}
Key Role
$schema Names the language version. Editors use it for validation and autocomplete; vega-embed uses it to pick the right compiler.
data Where the rows come from: inline values, a url, or a named dataset.
mark The shape. A string ("bar") or an object with properties ({"type": "bar", "color": "teal"}).
encoding Maps visual channels to fields: x, y, color, size, shape, opacity, tooltip, text, and more.
transform An ordered list of data steps (filter, calculate, aggregate, bin...) that run before encoding.

Other common top-level keys are title, width, height, config (global styling), params (interaction), and the composition operators layer, hconcat, vconcat, facet and repeat.

Data: values, url and named datasets

Vega-Lite treats data as a table of records.

JSON
{ "data": { "values": [ { "a": 1 }, { "a": 2 } ] } }
JSON
{ "data": { "url": "data/sales.csv", "format": { "type": "csv" } } }

Inline values make a spec fully self-contained, which suits small charts and tests. A url keeps the spec small and lets the browser fetch fresh data, but the file must be reachable (and allowed by CORS). A named dataset ({"name": "table"}) leaves the data out of the spec; the host page supplies it at run time. Altair uses this form: its output puts rows in a top-level datasets object and refers to them by name.

When you load a CSV by URL, every value starts as text. Vega-Lite tries to guess numbers and other simple types, but guessing can go wrong (a column of IDs, or dates in an unusual format). When it matters, say so explicitly with a format.parse setting for the column, and declare the right type on the encoding.

Mark: the shape

A mark is one of a fixed list: bar, line, area, point, circle, square, tick, rect, rule, text, boxplot and a few others. Marks are drawn once per data row, except line and area, which connect rows into a single path per group. Properties change the look: "mark": {"type": "point", "filled": true, "size": 80}.

Encoding: channels and field definitions

Each channel holds a field definition:

JSON
"y": {
  "field": "revenue",
  "type": "quantitative",
  "aggregate": "sum",
  "title": "Revenue (k$)",
  "axis": { "format": "~s", "grid": false },
  "scale": { "domain": [0, 200], "nice": true }
}
  • field names the column. Use "value": ... instead for a constant, as in "color": {"value": "tomato"}.
  • type is required for a field, one of quantitative, ordinal, nominal or temporal (you met the shorthands Q, N, O and T in the last lesson). Altair adds it for you; plain JSON needs it written out.
  • aggregate, bin and timeUnit do light data work right inside the channel.
  • axis and legend change the guide; scale changes the mapping from data to pixels or colors.

Scales

A scale is the function that turns a data value into a visual value. Vega-Lite picks one automatically from the type, and you adjust it with scale:

JSON
"x": { "field": "population", "type": "quantitative", "scale": { "type": "log" } },
"color": { "field": "score", "type": "quantitative", "scale": { "scheme": "viridis" } },
"y": { "field": "price", "type": "quantitative", "scale": { "zero": false, "domain": [90, 110] } }

Common options are type (linear, log, sqrt, time...), domain (the data range to show), range (the output range), zero (whether to include zero), nice (round the ends) and scheme (a named color scheme). By default bar charts include zero for a quantitative axis, which is the honest choice, so turn it off with care. The color and accessibility lesson returns to schemes.

Transform: data steps before drawing

JSON
"transform": [
  { "filter": "datum.revenue > 90" },
  { "calculate": "datum.revenue * 1.1", "as": "forecast" },
  { "aggregate": [{ "op": "mean", "field": "forecast", "as": "avg" }], "groupby": ["city"] }
]

Transforms run in order, each reading the output of the one before. Expressions use a small JavaScript-like language where datum is the current row. The transforms lesson covers every common step.

flowchart LR
    DATA["data<br/>rows"] --> TR["transform<br/>(in order)"]
    TR --> SC["scales<br/>data to visual values"]
    SC --> MK["mark<br/>one shape per row"]
    EN["encoding<br/>channel to field"] --> SC
    MK --> OUT["axes, legend,<br/>drawing"]

The order in which Vega-Lite processes a spec: data, transforms, scales built from encodings, then marks.

Embedding with vega-embed

To show a spec in a page, load three scripts and call vegaEmbed with a CSS selector:

HTML
<div id="chart"></div>

<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
<script>
  const spec = { /* the JSON from above */ };
  vegaEmbed("#chart", spec, { actions: false, renderer: "svg" });
</script>

vega is the runtime, vega-lite compiles a Vega-Lite spec into a lower-level Vega spec, and vega-embed is the glue that does both and adds the "..." menu (export PNG/SVG, view source). The options object can switch renderer between "svg" and "canvas", hide the menu with actions: false, and set a theme. In production, pin exact versions instead of using a floating major version, so a release upstream cannot change your charts.

chart.save("chart.html") in Altair writes a page like this for you, and chart.to_json() gives the spec when you want to embed it yourself.

A small renderer to see the idea

The page below contains a stand-in: about forty lines of JavaScript that read a spec and draw SVG. It handles bar, point and line marks, a nominal or quantitative x, a quantitative y (with an optional scale.domain) and a nominal color. It ignores everything else. Edit the specs in the script, and watch the picture change.

A tiny spec-to-SVG renderer

Changing mark: "bar" to "point" in the first spec keeps the encodings and redraws the same data with different shapes, which is the declarative idea in action. The real Vega-Lite also draws axis titles, legends, tooltips and many more details, and it chooses scales more carefully than this stand-in.

Checking a spec in code

Because a spec is data, you can check it before drawing. Real tools do this with the JSON Schema that Vega-Lite publishes. The stand-in below checks only a few rules by hand (a mark, an encoding, the right type names, fields that exist in the data) to show the kind of mistake that is caught early.

JS Validating a spec by hand

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

No output.

In practice you rarely write this check yourself. Altair validates against the real schema when you call to_dict(), and the Vega-Lite editor (a web page) highlights errors as you type.

Reading someone else's spec

When you meet an unfamiliar spec, read it in the order Vega-Lite does: look at data (what are the rows?), then transform (how are they changed?), then mark and encoding (what is drawn and which fields drive it). A surprising picture usually comes from one of three places: a type that does not match the data, a scale setting (such as zero: false or a log type), or a transform that dropped or reshaped rows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which key lists the data steps, such as filter and calculate, that run before the chart is drawn?

    transform is an ordered list of data steps. Each step receives the rows produced by the previous one.
  2. 2. A spec uses a CSV file through data.url. What must be true for the browser to load it?

    The browser fetches the URL, so normal web rules apply: the file has to be served and, if it is on another origin, CORS must allow it.
  3. 3. What is the job of the scale option in an encoding?

    A scale is the mapping function. Options such as type, domain, zero and scheme change that mapping.
  4. 4. Which package in a vega-embed page compiles a Vega-Lite spec into a lower-level Vega spec?

    vega-lite compiles the high-level spec; vega runs the result; vega-embed ties them together and adds the actions menu.

Summary

  • A Vega-Lite spec is JSON with data, mark, encoding and optionally transform, plus title, width, height, config and composition keys.
  • Data can be inline values, a url, or a named dataset supplied at run time (which is what Altair writes).
  • Each encoding channel has a field definition with field, type and optional aggregate, axis, legend and scale.
  • Scales map data to visuals; change type, domain, zero and scheme deliberately.
  • vegaEmbed(selector, spec) renders a spec in a page; pin library versions in production.
  • The renderer and validator in this lesson are stand-ins that show the shape of the process, not the real Vega-Lite behaviour.

Next: Altair Transforms and Aggregation