Schema
Declares the types of a chart's columns. Pass a record of column types as the schema option of chart.
import { Color, Domain, Trait, Unit, chart, rect, spread, stack } from "gofish-graphics";
const LEVELS = [
"Strongly disagree",
"Disagree",
"Neutral",
"Agree",
"Strongly agree",
];
const likertColors = Color.palette({
"Strongly disagree": "#ca0020",
Disagree: "#f4a582",
Neutral: "#d9d9d9",
Agree: "#92c5de",
"Strongly agree": "#0571b0",
});
const survey = [
["The docs are clear", [12, 22, 38, 86, 42]],
["The API is easy to learn", [26, 48, 50, 54, 22]],
["Error messages are helpful", [58, 64, 36, 30, 12]],
["Charts render fast enough", [8, 18, 44, 80, 50]],
// Nobody strongly disagreed, so this question has no row for that level.
// The center is set by the order, so it does not move.
["I would recommend it", [0, 9, 27, 78, 86]],
].flatMap(([question, counts]) =>
(counts as number[]).flatMap((count, i) =>
count === 0 ? [] : [{ question, response: LEVELS[i], count }]
)
);
const container = document.getElementById("app");
chart(survey, {
schema: {
response: Unit({
domain: Domain.discrete(LEVELS),
traits: [Trait.diverging()],
}),
},
color: likertColors,
axes: { x: { title: "Respondents" }, y: true },
w: 640,
h: 300,
})
.flow(
spread({ by: "question", dir: "y" }),
stack({ by: "response", dir: "x" })
)
.mark(rect({ w: "count", fill: "response" }))
.render(container);Signature
Unit(name); // a unit
Unit(name, { domain, traits }); // a unit with a domain and traits
Unit({ domain, traits }); // a unit with no name: a type of levels
Domain.discrete(levels); // the values are `levels`: HasLevels
Trait.ordered(); // the levels are ordered, first to last (HasOrder)
Trait.diverging(); // the order has a midpoint (HasMidpoint), at n / 2; implies Trait.ordered()
Trait.diverging(midpoint); // the same, at `midpoint`
Trait.summable(); // the unit's amounts add up (CanSum)
Unit.time(); // the unit of instants (a time), read in UTC
Unit.time({ zone }); // the same, read in the time zone `zone`
Unit.duration; // the unit of a span of time, which adds up
{
(name, unit);
} // a column record: HasQuantity and the unit's traits
unit; // a Unit: the same as { unit }
("km²"); // a unit's name: the same as { unit: "km²" }A column type is a set of traits. A unit definition separates which values exist, its domain, from everything else about them, its traits: an order, a midpoint, whether they add up. Domain and Trait are families: a unit takes one domain and a list of traits. A Unit is declared once and used by every column in it, so its columns agree on what it can do:
const Likert = Unit({
domain: Domain.discrete(["SD", "D", "N", "A", "SA"]),
traits: [Trait.diverging()],
});
const Stars = Unit("stars", {
domain: Domain.discrete([1, 2, 3, 4, 5]),
traits: [Trait.ordered()],
});
const Party = Unit({ domain: Domain.discrete(["Dem", "Rep", "Ind"]) });
const USD = Unit("USD", { traits: [Trait.summable()] });
chart(survey, {
schema: {
answer: Likert,
rating: { name: "Rating", unit: Stars },
party: Party,
cost: USD,
area: "km²",
},
});A column record takes the keys name and unit. Any other key is an error. unit is a Unit or a unit's name.
| Entry | Trait | Meaning |
|---|---|---|
Domain.discrete(levels) | HasLevels | The column's values are levels, listed in this order. |
Trait.ordered() | HasOrder | The levels are ordered, first to last. |
Trait.diverging(midpoint?) | HasOrder, HasMidpoint | The order has a midpoint, a point along it. See below. |
Unit(name), { unit } | HasUnit | The column's values are amounts in the unit. |
Unit.time() | HasUnit | The column's values are instants, read on a calendar. |
Unit.duration | HasUnit, CanSum | The column's values are spans of time. |
Trait.summable() | CanSum | The unit's amounts add up. See below. |
{ unit }, a unit's name | HasUnit | The same, with no word on whether the amounts add up. |
{ name } | HasQuantity | The column's values are amounts of the quantity name. |
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Unit's name, e.g. "USD" or "mm". Two units are the same when their names are equal. A record's name is its quantity, e.g. "Pay", which titles the axis in place of the column's name. |
domain | Domain | Which values the unit has: Domain.discrete(levels). Without it, a named unit's values are amounts (numbers). |
traits | Trait[] | The traits the unit's values have, as Trait values: Trait.ordered() declares HasOrder, Trait.diverging() declares HasMidpoint and HasOrder, and Trait.summable() declares CanSum. Each appears at most once. |
levels | (string | number)[] | Every value the column takes, in the order to lay them out in. |
midpoint | number | Where the midpoint lies along the order, from 0 (before the first level) to n (after the last). Default n / 2. |
zone | string | The IANA time zone the column's instants are read in, e.g. "America/New_York". Default "UTC". |
unit | Unit | string | A record's unit: a Unit, or a unit's name. |
Behavior
Unit.
- A unit needs a name, a domain, or both. A unit with a domain and no name types its columns' levels and adds no unit to an axis title. Two such units are not compared with each other.
- A named unit with a domain is a unit whose amounts are its levels, so its levels must be numbers:
Unit("stars", { domain: Domain.discrete([1, 2, 3]) }). Text levels in a named unit are an error. domaintakes aDomainvalue. A bare list, or an interval, is an error. A domain that is an interval of numbers is not supported yet.Trait.diverging()impliesTrait.ordered(). Listing both is the same unit.- A trait listed twice is an error.
Trait.ordered()andTrait.diverging()need a domain, andTrait.summable()needs a name. Each is checked when theUnitis made.
HasLevels.
- Every
bysplit over the column (spread,stack,group,scatter, ...) lays its groups out in the order oflevels, not in order of first appearance. Afield(...).sort(...)or.reverse()on thebyreorders from there. - A categorical color scale whose values all come from the column lists its legend in the same order.
- A value that is not in
levelsis an error that names the column and the value. Add it to the levels, filter those rows out, or, if aderivechanged the values, give the column its type withderive(fn, { schema }).
HasOrder.
- The groups of a split over the column are ordered. An outer level of an ordinal axis over them starts each label at its run. Over levels without
Trait.ordered(), which are not ordered, it centers each label. - Only an ordered column can have a midpoint.
HasMidpoint.
midpointcounts levels from the start of the order. Leveli(counting from 0) spansitoi + 1, so 0 is the start of the first level,nis the end of the last, and 2.25 is a quarter of the way into the third level.- The default,
n / 2, is the middle of the middle level when the number of levels is odd, and the boundary between the two middle levels when it is even. - A
midpointthat is not a finite number, or that is below 0 or aboven, is an error fromUnit. The message names the midpoint, the range0..n, and the levels.chartchecks a column-type record passed as is (the wire form) the same way, with the same message. - A
stackwhosebycolumn hasHasMidpointputs its 0 at the midpoint instead of at its first part's start. A stack laid out in the reverse of the order keeps the same levels on each side. - The midpoint comes from the order, not from the data: a stack with no part for some level keeps the same midpoint. When the midpoint falls inside a level that a stack has no part for, the 0 is the boundary between that stack's parts on either side. So the stacks of a
spreadline up on their midpoints. - The parts of a centered stack must be nonnegative. A negative value is an error.
- An axis over a centered stack labels each tick with its distance from the midpoint (
60 40 20 0 20 40 60). - The parts must follow the column's order, or its reverse. Reordering them some other way is an error.
Unit.time().
- Each value becomes epoch milliseconds (UTC) when the chart applies its schema. A value may be an ISO 8601 string, a
Date, or epoch milliseconds. - A date alone (
"2024-03-05") is the start of that day inzone. A date-time with an offset ("2024-03-05T14:30:00Z") is that instant. A date-time without one ("2024-03-05T14:30") is that wall-clock time inzone. Any other value is an error that names the column and the value. - A column whose values are JS
Dateobjects is a time column in UTC without a schema entry. Strings and numbers are never taken as times. - An instant has no zero.
- An axis over the column is a time axis. Its ticks and labels are calendar cells in rows: by default the level that gives about 10 ticks, and below it that level's parent. Its domain is rounded outward to the cells of its first row. See
Calendarfor the rows. - An unknown
zoneis an error. Two time columns on one axis must have the same zone. - Every time column is in one unit, the instant, whatever its zone, so two time columns (a start and an end) share an axis. The zone is a parameter of the unit.
- A time column is named with a column record, as any column of amounts:
{ name: "Sold", unit: Unit.time() }. - The difference of two instants is in
Unit.duration, which adds up.
HasUnit.
- Columns in the same unit share an axis and its scale. Two columns in different units on one axis are an error that names the axis, both units, and the columns in each.
- A column with no declared unit has an unknown unit. It shares an axis with any column. When it meets a column in a declared unit, it takes that unit for the whole chart, so meeting another unit anywhere else is an error.
- A column's unit is the same everywhere in a chart: columns with the same name have the same unit.
- A
Unitand a unit's name are the same unit when their names are equal. - When x and y have the same unit, they get one scale: one data unit is the same length on both axes.
- An axis title shows a declared unit after its quantities, in parentheses:
"Production Budget (USD)". The rule does not read the names, so a column named"Flipper Length (mm)"in"mm"titles"Flipper Length (mm) (mm)". Declare its quantity ({ name: "Flipper Length", unit: Unit("mm") }) or set the axistitlefor"Flipper Length (mm)". .count()and.distinct()are in the unit"count". The cells offield(x).bin(p)are amounts ofx's quantity: apartitionover them titles its axis asxdoes and takes its unit. Counts,.normalize()shares, and times add no unit to an axis title.
CanSum.
- A
sizechannel (w,h, ...), astack, atreemapsize,field(x).sum()andfield(x).normalize()add up their values. Adding up values in a declared unit needsCanSum: without it, it is an error that names the column and the unit, and says to declare the unit withUnit(name, { traits: [Trait.summable()] }), or, for a unit whose differences add up (a time), to subtract a reference first. - A time column never has
CanSum: two instants do not add up. Its difference does (end - startis a duration), and a mark with two positions (x: "start", x2: "end") adds nothing. - A column with no declared unit adds up without
Trait.summable(), and so does a column whose unit is a name alone ("km²"), since that says nothing about whether the amounts add up. - A size channel adds up its rows whenever it reads a column, even when a group has one row. A pipeline op that folds the rows first (
field(x).mean(),.count()) adds nothing. .count(),.distinct()and.normalize()shares add up.- The difference of two amounts is in their unit (USD − USD is USD, °C − °C is °C), except the difference of two times, which is a duration (
Unit.duration). A size read from a time column is a duration too, never a time. CanSumis the unit's, not the column's. A unit is its name, so twoUnits of one name in one chart's schema, or in the columns two charts of one figure draw, must agree onTrait.summable(): a disagreement is an error that names both columns. A column whose unit is a name alone takes theCanSumof aUnitof that name in the same chart; a stack of it also takes theCanSumof aUnitof that name in another chart of the figure.- A stack checks only the columns it adds, so a
startcolumn in days may share an axis with a stacked width in days.
HasQuantity.
- An axis is titled by the quantities of its columns, joined with commas, in the order they meet. A column's quantity is its
HasQuantityname, or else the column's name. - Columns of the same quantity have the same unit, like columns with the same name.
- The cells of
field(x).bin(p)takex's quantity..sum()and.mean()keep the column's quantity..count()is the quantity"count". - An
axesoption'stitlereplaces the inferred title.
Example
const LEVELS = [
"Strongly disagree",
"Disagree",
"Neutral",
"Agree",
"Strongly agree",
];
chart(survey, {
schema: {
response: Unit({
domain: Domain.discrete(LEVELS),
traits: [Trait.diverging()],
}),
},
axes: true,
})
.flow(
spread({ by: "question", dir: "y" }),
stack({ by: "response", dir: "x" })
)
.mark(rect({ w: "count", fill: "response" }))
.render(container, { w: 640, h: 300 });A population pyramid is a two-level diverging order, with positive counts on both sides:
chart(population, {
schema: {
sex: Unit({
domain: Domain.discrete(["Women", "Men"]),
traits: [Trait.diverging()],
}),
},
})
.flow(
spread({ by: field("age").reverse(), dir: "y", spacing: 1 }),
stack({ by: "sex", dir: "x" })
)
.mark(rect({ w: "people", fill: "sex" }));Two columns in the same unit share one scale on x and y, so a circle in the data stays a circle:
chart(sunflower, {
schema: { x: "plane", y: "plane" },
})
.flow(scatter({ x: "x", y: "y" }))
.mark(circle({ r: 4, fill: "i" }));A column of date strings is a time in Unit.time():
chart(prices, { schema: { date: Unit.time() }, axes: true })
.flow(scatter({ by: "date", x: "date", y: "price" }))
.mark(line({ stroke: "steelblue", strokeWidth: 2 }))
.render(container, { w: 560, h: 200 });Five summary columns of one quantity title their axis once:
const pay = { name: "Pay", unit: Unit("USD") };
chart(boxes, {
schema: { lo: pay, q1: pay, q3: pay, hi: pay },
axes: true,
})
.flow(spread({ by: "grade", dir: "x" }))
.mark(
layer([
rect({ w: 1, y: "lo", y2: "hi" }),
rect({ w: 16, y: "q1", y2: "q3" }),
])
); // y axis: "Pay (USD)"