The loess technique applies smoothing to the data, using equations instead of the mean value of the span. We will first apply degree 1, which fits the estimates as local lines. The distribution curve applied by loess is the Tukey tri-weight density.
The span used is 3 weeks.
total_days <- diff(range(polls_2008$day))
span <- 21/total_days
fit_loess <- loess(margin ~ day, degree = 1, span = span, data=polls_2008)
polls_2008 %>% mutate(smooth = fit_loess$fitted) %>%
ggplot(aes(day, margin)) +
geom_point(size = 2, alpha = .5) +
geom_line(aes(day, smooth), color="red")
The ggplot has the geom_smooth function, which applies loess regression. This function also plots the 95% confidence interval.
span <- 21/total_days
polls_2008 %>% ggplot(aes(day, margin)) +
geom_point() +
geom_smooth(formula = y ~ x,
color="red",
span = span,
method = "loess",
method.args = list(degree=1))
We can change the loess degree parameter to two. The estimates will be local parabolas instead of lines.
The span used here is 4 weeks.
span <- 28/total_days
polls_2008 %>% ggplot(aes(day, margin)) +
geom_point() +
geom_smooth(formula = y ~ x,
color="red",
span = span,
method = "loess",
method.args = list(degree=2))