# `Giggly.Mapping`
[🔗](https://github.com/giggleton/giggly/blob/v0.2.0/lib/giggly/mapping.ex#L1)

What a mapping maps each aesthetic to: a column, an expression computed from columns in each
row, a constant, or a list of values, one for each row. A mapping is a map from aesthetic to
value:

    %{x: :displ, y: {&Kernel.//2, [:hwy, :cty]}, colour: {:constant, "smooth"}}

## Values

  * **A column** is named by an atom or a string, compared with the table's column names as a
    string, so `:hwy` and `"hwy"` name the same column. `true`, `false` and `nil` name none.
  * **An expression**, `{function, [value, ...]}`, is the function applied in each row to what
    its arguments are in that row, so `{&Kernel.//2, [:hwy, :cty]}` divides each row's `hwy` by
    its `cty`. Each argument is a value, so it may be a column, a constant or another expression,
    and the function takes as many arguments as it is given.
  * **A series**, `{:series, function, [value, ...]}`, is the function applied once to whole
    columns: each argument is a list of what it is in every row of the table it is evaluated
    against, in row order, every panel and group together, so `{:series, &Enum.max/1, [:hwy]}`
    is the greatest `hwy`, and inside an after_stat it sees the stat's whole output; a constant
    is handed as itself, so `{:series, &Enum.take/2, [:hwy, 3]}` takes three. The function
    returns a list of one value for each row, or one value, alone or in a list, which every row
    takes; a list of another length is refused when the plot is run. Its arguments are what an
    expression's are, and it goes where an expression goes, an expression's arguments
    included, but never in what the engine holding the table computes: a function by name, a
    reordering or a cut.
  * **A function by name**, `{:log10, [value]}`, is a common function Elixir lacks, computed by
    the engine holding the table: `log10` is the base-10 logarithm, minus infinity for 0, NaN
    for a negative number and missing for a missing value. Its value is a column, a constant
    or another function by name, never a capture or a closure, which the engine cannot run, so
    the logarithm of what a capture computes is a capture too, `{&:math.log10/1, [value]}`.
    Any other function is written as a capture.
  * **A constant**, `{:constant, term}`, is the term in every row. A number, a boolean, a date or
    a time is a constant written alone; a string or an atom would name a column, so a constant
    one is written `{:constant, "smooth"}`.
  * **A list**, `[-0.1, 0.1, -0.1, 0.1]`, gives one value to each row of the table, in row
    order, whichever panel the row is drawn in: one or more values a column can hold, of one
    type, `nil` among them missing, as many as the table has rows, or one, which every row takes.
    A layer whose table has no rows draws as many as its longest list holds. It goes where a
    column goes, an expression's argument and a factor's value included, `{:factor, [list]}`
    reading it as discrete, and a facet too, but never inside an after_stat, whose rows are its
    stat's, or in what the engine holding the table computes: a function by name, a reordering
    or a cut. Its guide is titled by the list as Elixir writes it, its values after 60
    characters left out and `...` written in their place.
  * **A factor**, `{:factor, [value]}`, is the value read as discrete, so a column of numbers
    maps as levels: a discrete scale whatever the values, its levels in order of value (dates by
    date) with a missing one last, each written as text (a whole number without a decimal
    point, `4`; a boolean as `TRUE` or `FALSE`), and the rows grouped by them.
    `{:factor, [value], levels: [level, ...]}` gives the levels and their order, each named as
    the value holds it (`[8, 4, 6]` for numbers), a value not among them missing, so the axis,
    the legend, the groups and stacking follow that order; `ordered: true` marks the factor's
    levels as ordered. A factor reads a whole column, so it is the whole of a mapping value, a
    factor's own or an after_stat's, never an expression's argument.
  * **A reordering**, `{:reorder, [value, by]}`, is `value` read as discrete, as a factor reads
    it, its levels ordered by the mean of `by` over each one's rows, the lowest first: levels
    whose means tie keep the order the factor of `value` gives them (its own levels where the
    table's column is a factor), and a level whose mean is missing, since its rows hold a
    missing or NaN `by` or there are none, goes last. The mean is R's `mean()`, worked out as
    R works it out, digit for digit. Each of `value` and `by` is a column or a function by
    name, which the engine holding the table computes, as it computes the means, and `by` is
    numbers; the levels are ordered, as `ordered: true` marks a factor's, where `value` is an
    ordered factor. A reordering reads whole columns, as a factor does, so it goes where a
    factor goes.
  * **A cut**, `{:cut_width, [value], width: width}`, is R's `cut_width()`: `value` cut into
    intervals `width` wide and read as discrete, each interval a level, empty ones too, in
    order, labelled as R's `cut()` labels them, `(0.375,0.625]`, the first closed at both ends,
    `[0.125,0.375]`, each break in 3 significant digits, more where two would read alike. The
    intervals meet half a width from 0, or at `boundary:`, or half a width either side of
    `center:`; `closed: :left` closes each on its left, `[0.5,1.5)`; `labels:` gives the levels'
    labels, one for each interval, or `false` its intervals' numbers, from 1, as numbers;
    `dig_lab:` the digits the labels start from; `ordered_result: true` marks the levels
    ordered. The value is a column, a constant or a function by name, of numbers, which the
    engine holding the table cuts, over all of the table's rows; a missing value or NaN falls
    in none. Values on one break, a column of one value on it among them, are cut as R's
    `cut()` reads one break: as a count of intervals, whole, evenly spaced over their range
    widened a thousandth each way, or a thousandth of the value either side of one value.
    `{:cut_interval, [value], n: n}` is R's `cut_interval()`, `n` intervals of equal range over
    the value's finite range, or with `length:` in place of `n:`, intervals that long from a
    multiple of it, an infinite value in none; `{:cut_number, [value], n: n}` is R's
    `cut_number()`, `n` intervals holding about as many values each, their breaks the value's
    quantiles, an infinity among them, written `Inf`. Both take `right: false` where a
    cut_width takes `closed: :left`, and `labels:`, `dig_lab:` and `ordered_result:` as it
    does. A cut reads a whole column, so it goes where a factor goes.
  * **An after_stat**, `{:after_stat, [value]}`, is the value computed from what the layer's stat
    computes: its names are the stat's computed variables (counting's are `count` and `prop`)
    and `group`, each row's group's number, which every stat's output holds, and it is evaluated once the stat has run, so it takes no part in grouping or in what the
    stat computes. Its value is put through its aesthetic's scale. It is the whole of a mapping
    value, never inside another, so the share as a percentage is written
    `{:after_stat, [{&Kernel.*/2, [:prop, 100]}]}`.
  * **An after_scale**, `{:after_scale, [value]}`, is the value computed from the layer's
    aesthetics once every scale has mapped them and the geom's defaults are in, before the values
    the layer sets: its names are those aesthetics, spelt as a mapping spells them (`colour` is
    `color`), and the columns the stat computed, so
    `{:after_scale, [{&Scales.ColorOperations.alpha/2, [:colour, 0.4]}]}` fills with each mark's
    own colour made translucent, a colour the layer sets left unread. It takes no part in
    grouping and gets no scale; its values are drawn as they stand, a colour, an opacity, a size,
    a width, a shape or a line type checked as the option setting that aesthetic checks one, a
    position a number. A legend's keys are changed alike, but where it reads a name a key lacks,
    such as a stat's column. It is the whole of a mapping value, never inside another.
  * **A staged value**, `{:stage, start: value, after_stat: value, after_scale: value}`, maps
    one aesthetic at more than one stage, any of them: its start as a value evaluated from the
    layer's data, which its stat reads and its scale trains on, its after_stat in its place once
    the stat has run, and its after_scale in its place once the scales have mapped. It is the
    whole of a mapping value, never inside another.

A constant is a value a column can hold: `nil` and a value with no column type of its own (a
map, a tuple, a struct other than a date or a time) are refused, and so are a list of no values,
of values no column holds, of two types, or of another length than the table's rows, a function
alone, a tuple that is neither an expression nor a constant, and a function given a number of
arguments it does not take. A function by name is refused where the table's engine cannot run
it, and `log10` where its value is a column or a constant that is not numbers, a factor's
column among them. A factor's levels are refused unless they are a list of one or more
values a column can hold, of one type, none of them `nil` and none given twice (`4` and `4.0`
are one); levels of another type than the value's are refused when the plot is run. A
reordering is refused where either of its values is a constant, a capture or a closure, a factor
or another reordering, or where `by` is a column that is not numbers. A cut_width is refused
without a width above 0, given both `center:` and `boundary:`, or `right:`, which R's
`cut_width()` says with `closed:`; a cut_interval without exactly one of `n:`, a whole number
from 1, and `length:`, a number above 0; a cut_number without `n:`; either of those two given
`closed:`, which R ignores, or `labels:` not one for each of `n:`'s intervals; and a cut where
its value is a capture or a closure, a factor, a reordering or a cut, or a column or a constant
that is not numbers. When the plot is run a cut is refused as R fails: where its value has no
finite number, a cut_width's an infinite one, where a cut_width's one break counts fewer than 2
intervals, where a cut_interval cuts one number into `n`, where a cut_number's breaks repeat,
too few values telling them apart, and where `labels:` are not one for each interval; and past
a million counted intervals, which R cuts. A layer
whose stat computes nothing, and so documents no variables, refuses every after_stat but one
reading `group`.

    iex> plot =
    ...>   %{"hwy" => [29, 24], "cty" => [18, 16]}
    ...>   |> Giggly.Plot.new(%{x: :cty, y: {&Kernel.//2, [:hwy, :cty]}})
    ...>   |> Giggly.Plot.geom_point(%{colour: {:constant, "smooth"}})
    iex> frame = Giggly.layer_data(plot)
    iex> Giggly.DataFrame.pull(frame, :y)
    [1.6111111111111112, 1.5]
    iex> Giggly.DataFrame.pull(frame, :color)
    ["#F8766D", "#F8766D"]

Each class's share of all the rows, counted as one group:

    iex> plot =
    ...>   %{"class" => ["suv", "compact", "suv", "midsize"]}
    ...>   |> Giggly.Plot.new(%{x: :class, y: {:after_stat, [:prop]}, group: 1})
    ...>   |> Giggly.Plot.geom_bar()
    iex> frame = Giggly.layer_data(plot)
    iex> Giggly.DataFrame.pull(frame, :y)
    [0.25, 0.25, 0.5]

Each label nudged its own way by a list, one value for each row:

    iex> plot =
    ...>   %{"x" => [1, 2, 3, 4], "y" => [1, 2, 3, 4]}
    ...>   |> Giggly.Plot.new(%{x: :x, y: :y})
    ...>   |> Giggly.Plot.geom_text(%{label: :y, nudge_y: [-0.1, 0.1, -0.1, 0.1]})
    iex> Giggly.DataFrame.pull(Giggly.layer_data(plot), :y)
    [0.9, 2.1, 2.9, 4.1]

Each bar's count as a share of the tallest bar's, the function handed every bar's count at
once:

    iex> tallest_share = fn counts ->
    ...>   tallest = Enum.max(counts)
    ...>   Enum.map(counts, fn count -> count / tallest end)
    ...> end
    iex> plot =
    ...>   %{"class" => ["suv", "compact", "suv", "suv"]}
    ...>   |> Giggly.Plot.new(%{x: :class})
    ...>   |> Giggly.Plot.geom_bar(%{y: {:after_stat, [{:series, tallest_share, [:count]}]}})
    iex> Giggly.DataFrame.pull(Giggly.layer_data(plot), :y)
    [0.3333333333333333, 1.0]

Each box filled with the colour its class's scale gives, made translucent after the scale:

    iex> plot =
    ...>   %{"class" => ["a", "a", "b", "b"], "hwy" => [1, 2, 3, 4]}
    ...>   |> Giggly.Plot.new(%{x: :class, y: :hwy})
    ...>   |> Giggly.Plot.geom_boxplot(%{
    ...>     fill: {:stage, start: :class, after_scale: {&Scales.ColorOperations.alpha/2, [:fill, 0.4]}}
    ...>   })
    iex> Giggly.DataFrame.pull(Giggly.layer_data(plot), :fill)
    ["#F8766D66", "#00BFC466"]

The cylinders in the order given, so the axis reads 8, 4, 6:

    iex> plot =
    ...>   %{"cyl" => [4, 6, 8, 4], "mpg" => [26.0, 19.7, 15.0, 30.4]}
    ...>   |> Giggly.Plot.new(%{x: {:factor, [:cyl], levels: [8, 4, 6]}, y: :mpg})
    ...>   |> Giggly.Plot.geom_point()
    iex> Giggly.panel_scales(plot, 1).x.levels
    [8, 4, 6]

The classes in order of their mean highway mileage, 19 for the SUVs, 27 and 28:

    iex> plot =
    ...>   %{"class" => ["suv", "compact", "suv", "midsize"], "hwy" => [18, 28, 20, 27]}
    ...>   |> Giggly.Plot.new(%{x: {:reorder, [:class, :hwy]}, y: :hwy})
    ...>   |> Giggly.Plot.geom_point()
    iex> Giggly.panel_scales(plot, 1).x.levels
    ["suv", "midsize", "compact"]

The carats cut into quarters, each interval holding a row a level:

    iex> plot =
    ...>   %{"carat" => [0.23, 0.31, 0.7, 1.01], "price" => [326, 335, 2757, 2759]}
    ...>   |> Giggly.Plot.new(%{x: {:cut_width, [:carat], width: 0.25}, y: :price})
    ...>   |> Giggly.Plot.geom_point()
    iex> Giggly.panel_scales(plot, 1).x.levels
    ["[0.125,0.375]", "(0.625,0.875]", "(0.875,1.12]"]

The carats cut in two at their median, half the rows in each:

    iex> plot =
    ...>   %{"carat" => [0.23, 0.31, 0.7, 1.01], "price" => [326, 335, 2757, 2759]}
    ...>   |> Giggly.Plot.new(%{x: {:cut_number, [:carat], n: 2}, y: :price})
    ...>   |> Giggly.Plot.geom_point()
    iex> Giggly.panel_scales(plot, 1).x.levels
    ["[0.23,0.505]", "(0.505,1.01]"]

## Titles

A guide is titled by what its aesthetic is mapped to:

  * a column by its name, `cty`;
  * an expression by its text, as Elixir writes the call: a capture of one of `Kernel`'s
    operators as the operator, `hwy / cty`, and any other capture as a call to the function it
    names, `:math.log10(carat)`, as `inspect/1` names it;
  * a function by name as a call to it, `log10(carat)`;
  * a series as its function's call, as an expression is, `Enum.max(hwy)`;
  * an expression or a series whose function is a closure, such as `fn hwy -> hwy * 2 end`,
    has no text, so its guide has no title until `Giggly.Plot.labs/2` gives it one;
  * a factor by its value's text inside `factor()`, `factor(cyl)`, and its options as R writes
    them, `factor(cyl, levels = c(8, 4, 6), ordered = TRUE)`;
  * a reordering as a call to R's `reorder()`, `reorder(class, hwy)`;
  * a cut as a call to R's function, a cut_width's width or another's `n` beside its value and
    its other options as R names them, `cut_width(carat, 0.25, boundary = 0, dig.lab = 4)`,
    `cut_number(displ, 3)`, `cut_interval(displ, length = 1)`;
  * an after_stat or an after_scale by its value's text, `prop`;
  * a staged value by its after_stat's text, else its start's, else its after_scale's;
  * a constant by its aesthetic's name, `color`, unless another layer maps the aesthetic to a
    column or an expression, whose title wins.

So a capture is the form to write where the title should say what was computed, and a closure
the form to write inline, with a title from `labs/2`.

    iex> svg =
    ...>   %{"carat" => [0.23, 1.5], "price" => [326, 18823]}
    ...>   |> Giggly.Plot.new(%{x: {:log10, [:carat]}, y: {:log10, [:price]}})
    ...>   |> Giggly.Plot.geom_point()
    ...>   |> Giggly.to_svg()
    ...>   |> IO.iodata_to_binary()
    iex> svg =~ ">log10(carat)</text>" and svg =~ ">log10(price)</text>"
    true

    iex> svg =
    ...>   %{"hwy" => [29, 24], "cty" => [18, 16]}
    ...>   |> Giggly.Plot.new(%{x: :cty, y: {&Kernel.//2, [:hwy, :cty]}})
    ...>   |> Giggly.Plot.geom_point()
    ...>   |> Giggly.to_svg()
    ...>   |> IO.iodata_to_binary()
    iex> svg =~ ">hwy / cty</text>"
    true

# `after_scale`

```elixir
@type after_scale() :: {:after_scale, [value()]}
```

An after_scale: a value computed from the layer's aesthetics once they are scaled.

# `after_stat`

```elixir
@type after_stat() :: {:after_stat, [value()]}
```

An after_stat: a value computed from the stat's computed variables.

# `column`

```elixir
@type column() :: atom() | String.t()
```

A column, named by an atom or a string.

# `constant`

```elixir
@type constant() ::
  {:constant, term()}
  | number()
  | boolean()
  | Date.t()
  | Time.t()
  | NaiveDateTime.t()
  | DateTime.t()
```

A constant: `{:constant, term}`, or a number, a boolean, a date or a time written alone.

# `cut`

```elixir
@type cut() ::
  {:cut_width, [column() | constant() | expression()],
   width: number(),
   center: number(),
   boundary: number(),
   closed: :right | :left,
   labels: false | [String.t()],
   dig_lab: pos_integer(),
   ordered_result: boolean()}
  | {:cut_interval, [column() | constant() | expression()],
     n: pos_integer(),
     length: number(),
     labels: false | [String.t()],
     right: boolean(),
     dig_lab: pos_integer(),
     ordered_result: boolean()}
  | {:cut_number, [column() | constant() | expression()],
     n: pos_integer(),
     labels: false | [String.t()],
     right: boolean(),
     dig_lab: pos_integer(),
     ordered_result: boolean()}
```

A cut: a value cut into intervals, of a width, a count of equal ranges or a count of equal
numbers of values, each read as a level.

# `expression`

```elixir
@type expression() :: {function(), [value()]} | {:log10, [value()]}
```

An expression: a function and the values it is applied to in each row, or a function by name
and the value it is computed from.

# `factor`

```elixir
@type factor() ::
  {:factor, [value()]}
  | {:factor, [value()], levels: [term()], ordered: boolean()}
```

A factor: a value read as discrete, with the levels it holds and their order.

# `reordering`

```elixir
@type reordering() :: {:reorder, [column() | expression()]}
```

A reordering: a value read as discrete, its levels ordered by another's means.

# `resolved`

```elixir
@type resolved() ::
  String.t()
  | {:constant, term()}
  | {:factor, [resolved()]}
  | {:factor, [resolved()], levels: [term()], ordered: boolean()}
  | {:reorder, [resolved()]}
  | {:cut_width | :cut_interval | :cut_number, [resolved()], keyword()}
  | {:after_stat, [resolved()]}
  | {:after_scale, [resolved()]}
  | {:stage, start: resolved(), after_stat: resolved(), after_scale: resolved()}
  | [term(), ...]
  | {function(), [resolved()]}
  | {:series, function(), [resolved()]}
  | {:log10, [resolved()]}
```

A value as a plot holds it: a column by its name as a string, a constant as `{:constant, term}`,
and an expression as its function and its arguments, each held so.

# `series`

```elixir
@type series() :: {:series, function(), [value()]}
```

A series: a function and the values it is applied to once, as whole columns.

# `staged`

```elixir
@type staged() :: {:stage, start: value(), after_stat: value(), after_scale: value()}
```

A staged value: what an aesthetic is mapped to at the start, after the stat and after the
scales, any of them.

# `t`

```elixir
@type t() :: %{optional(atom()) =&gt; resolved()}
```

A mapping as a plot holds it: aesthetic to resolved value.

# `value`

```elixir
@type value() ::
  column()
  | expression()
  | series()
  | constant()
  | factor()
  | reordering()
  | cut()
  | after_stat()
  | after_scale()
  | staged()
```

A value as written: a column, an expression, a series, a constant, a factor, a reordering, a
cut, an after_stat, an after_scale or a staged value.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
