Datasets

Declaring a dataset with @data, and reaching it whole, by column, row by row, over time, joined to regions and from packs.

On this page

#Declaring a dataset

@data declares a table of values under an id. Inline, the body is rows of cells separated by |, the first row naming the columns:

@data#islands{
    island     | area   | species
    Baltra     | 25.09  | 58
    Bartolomé  | 1.24   | 31
    Santa Cruz | 903.82 | 444
}

Attached, the implicit value names a .csv file whose header row names the columns: @data#survey:plants.csv. Nothing downstream can tell the two apart. The id is required — @data: requires an id — datasets are reached as `#id.column` — and a dataset is visible to the whole document, wherever it is written.

#Column names and cells

  • Column names are read in lower case, with spaces as hyphens: a header Species Count is the column species-count.
  • Every row has as many cells as the header — @data: row 1 has 3 cells; the header declares 2 — and a column name appears once — duplicate column name `a`.
  • An inline cell cannot contain |; there is no escape for it.
  • A cell is text until it is used, and is typed by what uses it: a number where an attribute or an operator wants a number, a word where it wants a word. A cell that cannot be read so is an error naming its row: `#islands.area`, row 3: `` is not a number and cannot be used in arithmetic.
  • A blank cell is the empty text, "", kept in its place. A position that takes text takes it; one that takes a number refuses it, naming the row.

#What a column reads as

A canvas mark bound to a column decides the column's kind for the whole column, ignoring blank cells, so a year of daily readings lands on a year of positions rather than on one:

  • numeric — every cell a number;
  • date — every cell an ISO date, 2024-03-15 or 2024-03, read as a fractional year: the first of January is the whole year, a month is year + (month − 1) / 12;
  • complex — every cell a complex literal such as 4+2i, plain numbers allowed among them;
  • text — anything else.

Each consumer reads the kind its own way. A graph axis places numbers and dates as positions and text as named categories (graph); a choropleth's value: shades numbers, and a column of words draws nothing.

#Data from a URL

A dataset can be read from a web address instead of a file. The URL takes the file name's place, and format: says what it returns, since a URL rarely ends in an extension: csv or json for a table, geojson for boundaries.

@data#stouts:https://api.sampleapis.com/beers/stouts(format: json; path: rating)

graph{
    scatter(x: #stouts.reviews; y: #stouts.average)
}

#Declaring one

  • The URL must be https://; any other scheme is refused.
  • format: is required on a URL and refused on a file, whose extension already says what it holds.
  • A URL holding a space, a bracket of any kind, ; or | is refused, naming the character and how to write it percent-encoded: [ as %5B.
  • A URL built from a {{…}} value is written as src:, since the implicit value takes none.

Once its data has arrived, a URL dataset is like any other: its columns bind, splice and loop exactly as an attachment's do.

#Reading JSON

A JSON response is read as rows of objects, each object's keys naming the columns. A response that is an array of objects is the rows as it stands. When the rows sit deeper, path: names where, as a dotted path; every array on the way is stepped into, so in this response path: results.questions.answers gives one row per answer:

{ "total": 822,
  "results": [
    { "pollster": "Emerson",
      "questions": [
        { "sampleSize": 1000,
          "answers": [ { "party": "DEM", "pct": 48 }, { "party": "REP", "pct": 46 } ] } ] } ] }
  • A row carries the plain fields of every object above it: here each answer row has total, pollster and samplesize beside party and pct.
  • Where two levels share a key, the deeper one wins.
  • A key that ever holds an object or an array is not a column, and naming one is refused as any unknown column is. path: reaches inside it instead: the stouts above keep their ratings in a rating object, so path: rating makes average and reviews columns.
  • Keys are named as a header's are, in lower case with spaces as hyphens: sampleSize is the column samplesize.
  • A missing key or a null is the empty text; a number or a boolean is its text.
  • A response that is not JSON, or a path: that reaches no objects, does not compile. At a publish the author is told, and readers keep the rows fetched before.

#Following pages

An API that returns its rows a page at a time says in each response where the next page is. next: names that field, as a dotted path. A URL there is fetched as the next page; any other value is sent back as a query parameter named after the path's last part, so next: meta.cursor asks for ?cursor=…. Pages are followed until the field is empty, up to 25, and every page's rows are read in order. A CSV has no field to name, so it is never paged.

#Keys

Some APIs need a key. key: names one the author has saved under Preferences, API keys, and it is sent with each request: key: weather. A reader never sees it. When several authors share an internote, the one who publishes it uses their own key under that name.

#When the data is fetched

A URL is fetched when the internote is published and when its data is refreshed, never as a reader opens it, so every reader sees the same rows and the API is asked once. The columns are checked against that response. While the author is looking at the draft, the data is fetched fresh for them alone. A scene drawing URL data says when it was fetched, so a reader knows it is a fixed copy.

Warning
A fetch that fails keeps the rows fetched before, if there were any, and the publish goes ahead. The author is told which dataset failed and why.

#The whole dataset

#islands is the whole dataset, accepted where an attribute takes a dataset: table's data: and @for's n; a geo dataset in basemap:.

table(data: #islands; columns: island, area)

columns: is a list of plain names, resolved against the table's own data:, so they are written without #. Omitted, every column shows in order.

In an expression the whole dataset is applied to a row number with ->: 3 -> #islands is the third row, counted from 1, and a row number outside the dataset is index 4 is outside 1..3 of #islands. Written alone, {{#islands}} is refused — `#islands` is a table — apply it (`3 -> #islands`), reach a column (`#islands.column`) or bind it (`attr: #islands`).

#One column

#islands.area is one column.

Warning
A column is always written with its dataset's id: attribute values are unquoted, so a bare area is the word.

A column is a series: one value per row, in row order — the same thing a graph mark's x: or y: takes written out. An attribute of type series accepts either, so scatter(x: 1, 2, 3) and scatter(x: #trial.dose) are the same kind of value, and a column of complex numbers is a complex-series.

#A column as a series

Written bare in an attribute that takes a series, the column is bound — the renderer reads its cells, so the mark follows the data:

Eight Galápagos islands as points of plant species against area on a log scale, from Bartolomé, 1.24 km² and 31 species, to Santa Cruz, 903.82 km² and 444 species.Eight Galápagos islands as points of plant species against area on a log scale, from Bartolomé, 1.24 km² and 31 species, to Santa Cruz, 903.82 km² and 444 species.
@data#islands{
    island        | area   | species
    Baltra        | 25.09  | 58
    Bartolomé     | 1.24   | 31
    Española      | 58.27  | 97
    Fernandina    | 634.49 | 93
    Genovesa      | 17.35  | 40
    Pinta         | 59.56  | 104
    San Cristóbal | 551.62 | 280
    Santa Cruz    | 903.82 | 444
}

graph{
    scatter(x: #islands.area; y: #islands.species)
}(
    x scale: log
    x axis label: area, km²
    y axis label: species
)

Each attribute takes one column; two columns that belong together, such as x and y, are bound one each. A column goes where a list goes, or on the left of ->, and nowhere else.

#A column spliced into text

In a {{…}} expression, a column is its cells as written, joined with a comma and a space, unquoted — in prose, in an attribute, in a line of code:

code{
    lines{
        area = np.array([{{#islands.area}}])
    }
}(
    language: python
)

The splice happens as the document compiles, so an attachment's cells are spliced only where the compiler has the attachment. Without it, prose shows nothing and a line of code refuses the splice — … which cannot be written into a literal body.

A column is a list, so arithmetic works on it item by item, against another column of the same length: {{#islands.species / #islands.area}} is each island's species per km². A single value beside it is applied to each cell with ->, {{#islands.area -> round(_)}}, and min and max reduce it to one: {{max(#islands.species)}} is 444. Each cell is read as a number there, and a cell that is not one is refused, naming its row (Expressions).

#Rows

#Row by row with @for

@for:#islands repeats its body once per row, top to bottom. {{i}} is the row number from 1 and {{i.<column>}} is that row's cell, spliced as text and parsed by whatever position it lands in:

@data#islands{
    island     | area   | species
    Baltra     | 25.09  | 58
    Bartolomé  | 1.24   | 31
    Santa Cruz | 903.82 | 444
}

@for:#islands{
    {{i}}. {{i.island}} covers {{i.area}} km$^2$ and carries {{i.species}} species.
}

as: renames the binding: @for(n: #islands; as: row) gives {{row}} and {{row.area}}. A cell is an operand as well as text, so {{row.area * 2}} is arithmetic.

Warning
A column whose name has a hyphen is spliced as {{row.log-area}} but cannot take part in arithmetic, where the hyphen is a minus.

In a loop, rows are chosen with an @if in the body, by a cell's name or by a comparison, @if(when: row.area > 100):

@for(n: #islands; as: row){
    @if(when: row.island = Santa Cruz){
        {{row.island}} has {{row.species}} species.
    }
}

The dataset must be declared above the loop — `@for` reads its dataset in document order, so the `@data` must come first. A column is refused as n, with the fix: `#islands.area` names a column, and `@for` goes through rows — loop over `#islands` and write `{{i.area}}` in the body.

#Rows over time

Data with one state per year, month or country is written long: one row per thing per slice, with a column naming the slice. A mark names that column as its slice:, and a control names the same column as its column:; the mark draws the rows at the control's value.

Rainfall in January, February and March for one year at a time, with a year slider beneath the plot.Rainfall in January, February and March for one year at a time, with a year slider beneath the plot.
@data#rain{
    year | month | mm
    2022 | Jan   | 80
    2022 | Feb   | 62
    2022 | Mar   | 71
    2023 | Jan   | 95
    2023 | Feb   | 41
    2023 | Mar   | 88
    2024 | Jan   | 58
    2024 | Feb   | 77
    2024 | Mar   | 103
}

graph{
    bar(x: #rain.month; y: #rain.mm; slice: #rain.year)
    slider#year:t(column: #rain.year; discrete)
}(
    y domain: [0, 110]
)

Controls covers how the control takes its stops from the column, and what a mark draws between two of them.

#Maps

#Joining rows to regions

A choropleth joins rows to the regions of its region environment's boundaries: regions: is the column naming each row's region, value: the numbers it is shaded by.

@data#gdp{
    country | gdppc
    France  | 44000
    Germany | 52000
    Spain   | 33000
}

region{
    choropleth(regions: #gdp.country; value: #gdp.gdppc)
}(
    basemap: world
)
A world map with sixteen countries shaded by GDP per head, the United States reddest at the top of the scale and Australia orange just below it.A world map with sixteen countries shaded by GDP per head, the United States reddest at the top of the scale and Australia orange just below it.
region:world{
    choropleth#gdp(basemap: world; regions: #economy.country; value: #economy.gdppc)
}

#Boundaries as a dataset

An attached .geojson is a geo dataset: boundaries, for regions that are not one of the built-in basemaps. The extension decides the shape — .csv is a table, .geojson boundaries — and a geo dataset is bound whole, as a basemap::

@data#wards:sydney-wards.geojson
@data#turnout:turnout.csv

region{
    choropleth(basemap: #wards; regions: #turnout.ward; value: #turnout.pct)
}(
    projection: conic
)

It has no columns and no rows: #wards.name is `#wards` is geo data and has no columns — bind the dataset itself (`attr: #wards`), and @for:#wards is `#wards` is geo data and has no rows to go through. The feature property that names each region is given on the environment, with name-property:. Boundaries are only ever attached; an inline body is always a table.

#Datasets from packs

A pack brings datasets in too. @use makes them reachable through the pack's name, in every way above:

@use:biology

graph{
    line(x: #biology.lynx-hare.year; y: #biology.lynx-hare.hare)
}

@for:#biology.lynx-hare{
    {{i.year}}: {{i.hare}} thousand hares.
}

#Provenance and limits

#Where the rows come from

Every row a document shows is in its source: written inline, in an attachment, in a pack it imports, or at a URL it names, fetched when the internote is published. A reader cannot supply or change rows. Forking an internote copies its source and its attachments, so a fork with other data replaces the @data declaration or the attachment it names.

#What a dataset refuses

A dataset holds values as written. Its declaration has no computed columns, filters or sorts, and an expression has no sum: {{sum(#islands.area)}} writes its own text, and {{#islands.area[1]}} is unexpected `[`. A derived column belongs in the file, computed before it is attached, or in an expression over columns; a filter is an @if inside a @for. The declaration itself refuses:

  • an attachment that is not .csv or .geojson — `x.json` has extension `json`, but only csv, geojson are permitted;
  • a URL that is not https://, or one with no format:;
  • both an attachment and an inline body — declare either an inline {grid} body or `src:`, not both.
@data holds tables; a single value is a @let constant.

#Writing guidance

  • Checking a document's claims — Every other number worked out, every output quoted from a run, every dataset read and attached whole, every external fact checked and cited, or cut.

Last updated