stat-function

Sample fun at n points across x-limits and emit (x, y) rows.

x-limits defaults to (0, 1). Pass x-limits: none to fall back to the layer’s own data: the min and max of the values referenced by mapping.x are used as sampling bounds. If neither x-limits nor numeric data is available the stat panics with a helpful message.

Usage

stat-function(
  fun: x => x,
  n: 101,
  x-limits: (0, 1),
)

Parameters

Parameter Default Description
fun x => x Callable taking a numeric x and returning a numeric y.
n 101 Number of samples taken uniformly across the range.
x-limits (0, 1) Pair (lo, hi) bounding the sampling range, or none to derive from data.

Returns

Statistic object with name: "function", consumed by geom layers.

Outputs

  • x.
  • y.

Examples

Sine sampled across x-limits and rendered as a line.

#let frame = ((x: -calc.pi, y: -1), (x: calc.pi, y: 1))
#plot(
  data: frame,
  mapping: aes(x: "x", y: "y"),
  layers: (
    geom-blank(),
    geom-line(stat: stat-function(
      fun: x => calc.sin(x),
      x-limits: (-calc.pi, calc.pi),
    )),
  ),
  width: 10cm,
  height: 6cm,
)

Line chart with x on the horizontal axis from minus pi to pi and y on the vertical axis, tracing the sine function sampled across the x-limits range.

Line chart with x on the horizontal axis from minus pi to pi and y on the vertical axis, tracing the sine function sampled across the x-limits range.

The string form stat: "function" resolves to the constructor defaults (fun: x => x, n: 101, x-limits: (0, 1)). In practice the constructor form is always required because fun must be supplied.

#let frame = ((x: 0, y: 0), (x: 6.28, y: 1))
#plot(
  data: frame,
  mapping: aes(x: "x", y: "y"),
  layers: (
    geom-blank(),
    geom-point(
      size: 2pt,
      stat: stat-function(fun: x => calc.cos(x), n: 13, x-limits: (0, 6.28)),
    ),
    geom-line(stat: stat-function(fun: x => calc.cos(x), n: 201, x-limits: (0, 6.28))),
  ),
  width: 10cm,
  height: 6cm,
)

Line chart with x on the horizontal axis from zero to two pi and y on the vertical axis, plotting the cosine function as a dense line overlaid with 13 sampled points.

Line chart with x on the horizontal axis from zero to two pi and y on the vertical axis, plotting the cosine function as a dense line overlaid with 13 sampled points.

See also

geom-function, stat-smooth.

Back to top