First look at numeric only x creation… We produce almost the same plot, but x var values are 0 and 1
compute_group_rel_to_mean <- function(data, scales){
data |>
mutate(x = as.numeric(x > mean(x))) |>
# mutate(x = factor(ifelse(x, "greater", " less"))) |>
count(x) |>
mutate(y = n)
}
mtcars |>
rename(x = mpg) |>
compute_group_rel_to_mean()
## x n y
## 1 0 18 18
## 2 1 14 14
StatReltomean <- ggproto(`_class` = "StatReltomean",
`_inherit` = ggplot2::Stat,
compute_group = compute_group_rel_to_mean)
stat_rel_to_mean <- function(geom = ggplot2::GeomCol,
mapping = NULL,
data = NULL,
position = "identity",
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE, ...) {
ggplot2::layer(
stat = StatReltomean, # proto object from step 2
geom = geom, # inherit other behavior
data = data,
mapping = mapping,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
ggplot(mtcars) +
aes(x = mpg) +
stat_rel_to_mean()