Skip to main content
A stat summarises a layer’s data before it’s drawn. Instead of plotting raw rows, the layer plots a computed result — a count, a mean, or a fitted regression line. Stats are set per layer through a geom’s stat option, and default to identity (draw the data as-is).

Available stats

count and sum group by x plus the layer’s grouping variables, so they preserve the series a reader is comparing. mean reduces the layer to one observation, which is why it pairs with geom.rule() rather than with a bar or a line. count computes y for you — mapping y alongside it is a CONFLICTING_STAT_MAPPING error. Every stat also has a string shorthand, so geom.bar({ stat: 'count' }) is the same as geom.bar({ stat: stat.count() }). The names are 'identity', 'count', 'smooth', 'mean' and 'sum'.

Trendlines with smooth

The smooth stat fits a regression through a layer’s points — the basis for trendlines. Add it to a second geom.line() layer over your raw data:
method selects the regression family:
'linear' | 'loess' | 'exponential' | 'logarithmic' | 'quadratic' | 'power' | 'polynomial'
default:"linear"
The regression method to fit. The object builder asks for it; the 'smooth' string shorthand takes the default.
number
default:"3"
Polynomial order — only used when method: 'polynomial'.
number
default:"0.3"
Smoothing bandwidth — only used when method: 'loess'.

A mean reference line

stat.mean() reduces the layer to one observation, which is exactly what a rule needs. Pair the two to draw a horizontal line at the layer’s average:

Setting a stat at runtime

Two commands reach the stat surface:

Custom stats

A plugin can contribute its own stat: a Stat subclass registered through plugins, which earns a typed builder beside the built-ins. See Extending for the registration path.

Next