Home > Software design >  How to change lambda of loess function in geom_smooth?
How to change lambda of loess function in geom_smooth?

Time:06-26

I have been reading this article on enter image description here

However, I'm not entirely sure how to modify the alpha and lambda. I'm assuming so far that the span argument in geom_smooth is what alters alpha, as seen below:

#### Change Alpha ####
ggplot(iris,
       aes(x=Sepal.Width,
           y=Sepal.Length)) 
  geom_point() 
  geom_smooth(span = .35)

enter image description here

From the description of alpha in the article, this seems to be correct. As alpha is lowered, fitting the line to more noise is normal. However, I didn't seem to see if lambda could be modified in the same fashion. Is there a way to change this in ggplot, or does one have to find some other manual way?

CodePudding user response:

The geom_smooth function calls the stats::loess function which has the paramters span (alpha), and degree (lambda), which defaults to 2, but can be changed with the method.args parameter:

library(tidyverse)
iris %>% 
ggplot(aes(x = Sepal.Width, y = Sepal.Length))  
  geom_point()  
  geom_smooth(method = loess, method.args = list(degree = 1))

CodePudding user response:

To start with, a side note: the linked paper is behind a paywall and anyone without access can't figure out what α and λ mean. Keep in mind that statistical terms are not necessarily universal and that's especially true for parameter names. Here is instead the Wikipedia page about LOESS.

It's often helpful to be more explicit with argument specification. Here I use the method and method.args arguments to choose "loess" as the smoother and pass along two smoothing parameters:

  • span: the proportion of observations to be used in each local regression, ie, the size of the neighborhood. This parameter is called α in the paper.
  • degree: the degree of the polynomial, one of {0, 1, 2} but the loess documentation warns to use caution with 0. This parameter is called λ in the paper.
library("tidyverse")

iris %>%
  ggplot(
    aes(
      x = Sepal.Width,
      y = Sepal.Length
    )
  )  
  geom_point()  
  geom_smooth(
    method = "loess",
    method.args = list(span = 0.35, degree = 1)
  )
#> `geom_smooth()` using formula 'y ~ x'

Created on 2022-06-26 by the reprex package (v2.0.1)

  • Related