geom-density-2d

2D density layer: contour lines of the estimated (x, y) density.

Mapping must provide x and y; the layer accepts raw observations, no pre-computed grid is needed. Map colour to after-stat("_level") to shade the lines by density level.

Usage

geom-density-2d(
  mapping: none,
  data: none,
  bw: auto,
  adjust: 1,
  n: 25,
  bins: 10,
  binwidth: none,
  breaks: auto,
  stroke: auto,
  colour: auto,
  alpha: auto,
  linetype: auto,
  stat: auto,
  position: "identity",
  key: auto,
  inherit-aes: true,
)

Parameters

Parameter Default Description
mapping none Layer-specific aesthetic mapping built with aes. Must map x and y.
data none Layer-specific dataset, or a function applied to the plot data returning the layer frame. Falls back to the plot data when none.
bw auto Kernel standard deviation per axis. auto derives it per axis from R’s bw.nrd / 4; pass a number for both axes or an (x, y) tuple.
adjust 1 Bandwidth multiplier: adjust: 0.5 halves the smoothing.
n 25 Density grid resolution per axis: a number or an (x, y) tuple.
bins 10 Target contour-level count when breaks and binwidth are unset.
binwidth none Fixed step between levels. Overrides bins.
breaks auto Explicit array of contour levels. Overrides bins and binwidth.
stroke auto Line thickness (a Typst length).
colour auto Fixed line colour. auto resolves via the colour scale.
alpha auto Line opacity in [0, 1].
linetype auto Dash keyword. auto honours the linetype scale.
stat auto Statistical transform. auto builds stat-density-2d from the parameters above; pass a stat name or stat object to override.
position "identity" Position adjustment name. Usually "identity".
key auto Legend glyph override built with a draw-key-* helper. auto picks the default for the geom.
inherit-aes true Whether to merge the plot-level mapping into this layer’s mapping.

Returns

Layer dictionary consumed by plot.

Examples

Density contours around two point clouds.

#let d = range(0, 60).map(i => {
  let lobe = calc.rem(i, 2)
  (
    x: 2 + lobe * 4 + calc.sin(i * 1.7) * 0.8,
    y: 2 + lobe * 3 + calc.cos(i * 2.3) * 0.8,
  )
})
#plot(
  data: d,
  mapping: aes(x: "x", y: "y"),
  layers: (
    geom-point(size: 1.5pt, alpha: 0.5),
    geom-density-2d(),
  ),
  width: 10cm,
  height: 6cm,
)

Scatter of two point clouds centred near (2, 2) and (6, 5) overlaid with concentric density contour lines around each cloud.

Scatter of two point clouds centred near (2, 2) and (6, 5) overlaid with concentric density contour lines around each cloud.

See also

stat-density-2d, geom-density-2d-filled, geom-contour.

Back to top