R/stat_lm.R
2618b749
 StatLm <- ggplot2::ggproto("StatLm", Stat,
e1903364
     required_aes = c("x", "y"),
 
     compute_group = function(data, scales, params, n = 20) {
da667eb9
         data <- data[!duplicated(data$x), ]
 
e1903364
         if (nrow(data) <= 1) {
             return(data.frame(x = NULL, y = NULL))
         }
 
fde85e7d
         poly_deg <- min(6, nrow(data) - 1)
e1903364
         rng <- range(data$x, na.rm = TRUE)
         grid <- data.frame(x = seq(rng[1], rng[2], length = n))
 
cae649fd
         mod <- tryCatch(
             lm(y ~ poly(x, poly_deg), data = data),
da667eb9
             error = function(e) numeric(0)
cae649fd
         )
 
5fa46290
         if (length(mod) == 0) {
da667eb9
             return(data.frame(x = NULL, y = NULL))
cae649fd
         }
 
e1903364
         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, n = 50,
     ...
 ) {
2618b749
     ggplot2::layer(
e1903364
         stat = StatLm, data = data, mapping = mapping, geom = geom,
         position = position, show.legend = show.legend, inherit.aes = inherit.aes,
         params = list(n = n, na.rm = na.rm, ...)
     )
 }