THINK FIRST·CODE LATER

← Interactive Information Visualization
Chapter 7 · Week 7

The Grammar of Graphics: Tables, Time and Distributions

Before You Start: What You Must Be Able to Do

Before the questions, make sure you can: explain the components of the grammar of graphics and map them to Altair code; choose an idiom for a table from its numbers of keys and values; write Altair charts with transforms and verify what they compute with pandas; choose idioms for time series (including cyclic patterns with time units) and for distributions, and explain how bin width changes a histogram; compose charts with layers, concatenation and facets and read the resulting specification; and handle datasets larger than Altair's default limit.

The Big Idea

A grammar turns chart-making from choosing among named chart types ("bar chart, pie chart, line chart") into composing a few independent components — data, transformations, marks, encodings, scales, coordinates and facets. With a grammar you can build charts no menu offers, explain exactly what each chart computes, and check (by reading its specification) what an AI generated. This chapter is the hands-on core of the course: Altair as a grammar, applied to the three most common data situations — tables of values, time, and distributions.

The grammar of graphics

Leland Wilkinson's The Grammar of Graphics (1999) described charts as compositions of components; Hadley Wickham's ggplot2 (R) made the idea popular, and Vega-Lite (2017) brought it to the web with interaction. In Altair:

Component Altair
Data alt.Chart(df) (a tidy DataFrame, a URL or generated data)
Transforms .transform_filter, .transform_aggregate, .transform_calculate, .transform_bin, .transform_timeunit, .transform_window, .transform_fold — or shorthand inside encodings: mean(pm25), bin=True, hours(timestamp)
Mark .mark_point(), .mark_line(), .mark_bar(), .mark_rect(), .mark_area(), .mark_rule(), .mark_text(), .mark_boxplot()
Encoding .encode(x=…, y=…, color=…, size=…, shape=…, tooltip=…, facet=…) with types Q N O T
Scale & guide alt.X("pm25:Q", scale=alt.Scale(zero=True), axis=alt.Axis(title="PM2.5 (µg/m³)"))
Composition a + b (layer), `a

Transforms: in the chart or in pandas?

Vega-Lite computes transforms in the browser: the chart carries raw rows and the specification says filter → aggregate → calculate. Advantages: interaction can change the computation (Chapter 8) and one dataset feeds many views. Disadvantages: every row is embedded in the page (slow for large data), and the computation is hidden inside the spec.

Rule of thumb: reduce in pandas or SQL (filter to the period, aggregate millions of rows to thousands), keep in the chart what interaction must change. In both cases verify: the numbers a chart shows must match an independent pandas computation (Lab V7.2).

Altair refuses DataFrames with more than 5,000 rows by default (MaxRowsError) to protect the browser. Options: aggregate first (best); enable the VegaFusion data transformer (alt.data_transformers.enable("vegafusion")), which pre-computes transforms in Python and sends only what is drawn; or disable the limit (alt.data_transformers.disable_max_rows()) and accept huge, slow pages.

Arranging tables: keys and values

Munzner classifies table idioms by the number of keys (categorical/ordinal attributes that index regions) and values (attributes encoded by magnitude):

Keys Values Idiom CityPulse example
0 2 scatter plot (position, position) temperature vs. PM2.5 per reading
1 1 bar chart / dot plot (regions along one axis, length/position) mean PM2.5 per district
1 many grouped/stacked bars, parallel coordinates trips by district split by rider type
2 1 heat map (rectangles in a grid, colour) trips per weekday × hour
0–1 1 (ordered key) line chart PM2.5 over time

Arrangement choices: express values with position, separate items into regions, order regions (sort bars by value to support ranking and locating extremes; keep natural order for ordinal keys), and align regions to a common baseline (Chapter 5). Sorting is one of the cheapest, most effective improvements: alt.X("district:N", sort="-y").

Time

  • Line charts connect ordered values — use them only when the x attribute is ordered (time, ordered categories), never for unordered categories.
  • Aspect ratio changes perceived slopes; Cleveland recommended "banking to 45°" — choose a width/height so that the important slopes are near 45°.
  • Cyclic patterns (hour of day, weekday, season) are hidden in a long line; reveal them with time units: a calendar/cycle heat map of weekday × hour (x="hours(start_time):O", y="day(start_time):O", color="count():Q") shows commuter peaks at 8:00 on weekdays and late-morning use at weekends (Lab V7.3). In Vega-Lite, day means day of the week, date means day of the month.
  • Small multiples of time series (one per district) beat one line chart with many colours when there are more than about 4–5 series.
  • Mark gaps (missing data) instead of drawing lines across them.

Distributions

  • Histogram: bins of equal width, bar length = count. The bin width changes the story: trip durations 4–31 min binned by 20 min look unimodal (9 and 7), binned by 5 min they show two groups — short campus hops and longer cross-town trips (Lab V7.1). Try several widths; rules of thumb (Sturges, Freedman–Diaconis) are starting points, not answers.
  • Box plot (Tukey): median, quartiles, whiskers to 1.5 × IQR, outliers as points — compact for comparing many groups, but hides multimodality.
  • Violin/density plots show the shape (smoothed), strip plots (with jitter) show every point for small data, the ECDF shows cumulative proportions without binning choices.

Composition

  • Layer (+): marks on the same axes — a line plus a reference rule for the guideline plus text annotations.
  • Concatenate (|, &): different charts side by side, e.g., a line chart and a bar chart (a mini-dashboard).
  • Facet (.facet(column="district:N")): the same chart repeated per category (small multiples) with shared scales by default.
  • Repeat: the same chart for several fields (e.g., a scatter-plot matrix).

Reading the specification tells you the structure: a layered chart has a top-level layer list, a facet has facet + spec, concatenations have hconcat/vconcat (Lab V7.4).

Industry spotlight

Grammar-based tools dominate modern analytics: Vega-Lite powers charts in Jupyter, Observable, Databricks and many BI tools; ggplot2 is the standard in R; Tableau's VizQL is itself a grammar. Learning the grammar once transfers across tools — and lets you read and repair the specifications AI assistants now generate.

Research spotlight

Grammars make visualization machine-readable, which enables automated design: recommender systems such as Voyager and Draco search the space of Vega-Lite specifications using perceptual rules, and NL2VIS systems translate questions into Vega-Lite. Benchmarks for these systems (e.g., nvBench) compare generated specifications with reference ones — an evaluation only possible because charts are data.

Key takeaways

  • Grammar: data + transforms + marks + encodings + scales/guides + composition; Altair = Python for Vega-Lite.
  • Transforms run in the browser; reduce big data in pandas/SQL first; verify chart numbers independently; 5,000-row limit (aggregate, VegaFusion).
  • Keys and values: 0 keys/2 values → scatter; 1 key/1 value → bars (sorted); 2 keys/1 value → heat map; ordered key → line.
  • Time: lines only for ordered x, aspect ratio, time units for cycles (day = weekday), small multiples for many series, show gaps.
  • Distributions: histogram (bin width matters), box plot, violin/density, strip, ECDF.
  • Composition: + layer, |/& concat, facet, repeat — visible in the spec.

Ready? Close the notes and practise.

30 questions. Predict the output before you check — that is the skill the exam measures.