How do we add a new variable to a new geom?
Here is the example from the ggplot2's vignette. I intend to add weight
variable as an aesthetic with 1 as default.
Unsuccessful attempt:
StatLm <- ggproto("StatLm", Stat,
# required_aes = c("x", "y"),
required_aes = c("x", "y", "w"),
compute_group = function(data, scales) {
rng <- range(data$x, na.rm = TRUE)
grid <- data.frame(x = rng)
# mod <- lm(y ~ x, data = data)
if (w == 1) {
mod <- lm(y ~ x, data = data)
} else {
mod <- lm(y ~ x, weight = data$w, data = data)
}
grid$y <- predict(mod, newdata = grid)
grid
}
)
stat_lm <- function(mapping = NULL, data = NULL, geom = "line",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = StatLm, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
stat_lm()
This leads to error:
Error in layer(stat = StatLm, data = data, mapping = mapping, geom = geom, :
object 'w' not found