inst/examples/ex-stat-referent.r

# simplify the Motor Trends data to two predictors legible at aspect ratio 1
mtcars %>%
  transform(hp00 = hp/100) %>%
  subset(select = c(mpg, hp00, wt)) ->
  subcars
# compute the gradient of `mpg` against these two predictors
lm(mpg ~ hp00 + wt, subcars) %>%
  coefficients() %>%
  as.list() %>% as.data.frame() ->
  grad
# use the gradient as a reference (to no effect in this basic ggproto)
ggplot(subcars, aes(x = hp00, y = wt)) +
  coord_equal() +
  geom_point() +
  stat_referent(referent = grad)
ggplot(subcars, aes(x = hp00, y = wt)) +
  coord_equal() +
  stat_referent(geom = "point", referent = grad)

# passing a function yields a transformation of the primary data
p <- ggplot(subcars, aes(x = hp00, y = wt)) +
  stat_referent(
    data = head,
    referent = function(d) as.data.frame(lapply(d, mean))
  )
b <- ggplot_build(p)
# original data
b@plot@data
# head of original data
b@data[[1]]
# means of original data
b@plot@layers$stat_referent$stat_params$referent
# means of head of original data
as.data.frame(lapply(layer_data(p, 1), mean))

Try the gggda package in your browser

Any scripts or data that you put into this service are public.

gggda documentation built on July 18, 2026, 5:07 p.m.