I have for example monthly data from this package:
install.packages("fma")
library(fma)
plot(boston)
Now I want to try and add to this plot two smoothed curves in different color by using local polynomial regression fitting. I thought I can do that by using the command loess(), I also want to select a small respectively bigger value for the parameter span. However, it's not working really. I can't apply loess(). I don't know what I'm doing wrong?
CodePudding user response:
A loess regression requires both x and y variables, but a ts
object only has a y variable, with the time variable being implicit, so we need to extract the time variable as a numeric variable and regress on it.
You can do this automatically using geom_smooth
in ggplot
, with the added benefits of a fully customizable plot and a standard error ribbon.
library(tidyverse)
library(fma)
as.data.frame(boston) %>%
mutate(date = time(boston)) %>%
pivot_longer(-date, names_to = "series") %>%
ggplot(aes(date, value))
geom_line()
geom_smooth(method = loess, formula = y~x, fill = "lightblue", lty = 2,
method.args = list(span = 0.5))
facet_grid(series~., scales = "free_y")
theme_bw(base_size = 16)
Created on 2022-05-15 by the reprex package (v2.0.1)