Search code examples
rtime-seriesloess

Add smoothed curves to plot using loess()


I have monthly data from this package: boston, and I did a timeserie

install.packages("fma")
library(fma)
data(package="fma")
View(boston)
timeseries<-ts(boston,start=1)
plot(timeseries)

Now I want to add to this plot two smoothed curves by using local polynomial regression fitting. I was using loess(), but something must be wrong because it gives me error. This is the code that I am using:

index<-1:nrow(boston)
loess(timeseries ~ index, data = boston, span = 0.8)

Solution

  • Do you wish something like this?

    I used {ggplot2} for the plots. geom_smooth() allows the use of loess with span argument - assuming you want to use loess.

    For the arrangement of the plots, i.e., stacked + one x-axis, I used {grid}:

    # install.packages("fma")
    library(fma)
    #> Loading required package: forecast
    #> Registered S3 method overwritten by 'quantmod':
    #>   method            from
    #>   as.zoo.data.frame zoo
    timeseries <- ts(boston, start = 1)
    # plot(timeseries)
    
    library(ggplot2)
    df <- as.data.frame(timeseries)
    df$index <- 1:35
    
    p1 <- ggplot(data = df, aes(x = index, y = nyase)) +
      geom_line() +
      geom_smooth(method = 'loess', formula = y~x, span = 0.8) +
      theme_minimal() +
      theme(axis.title.x = element_blank(), axis.text.x = element_blank())
    
    p2 <- ggplot(data = df, aes(x = index, y = bse)) +
      geom_line() +
      geom_smooth(method = 'loess', formula = y~x, span = 0.8) +
      theme_minimal()
    
    grid::grid.newpage()
    grid::grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last"))
    

    gives

    Created on 2022-05-19 by the reprex package (v2.0.1)

    You can avoid displaying confidence interval around smooth by adding the argument se = FALSE to geom_smooth().


    A short correction on your line loess(...), you need to specify the column of your timeseries object to allow regression, i. e.

    loess(timeseries[, 1] ~ index, data = boston, span = 0.8)
    # or 
    loess(timeseries[, 2] ~ index, data = boston, span = 0.8)
    

    Instead of 1 and 2 you could also use "bse" and "nyase". Then, for "bse":

    index <- 1:35
    a <- loess(timeseries[, "bse"] ~ index, data = boston, span = 0.8)
    
    plot(index, timeseries[, "bse"], type = "l")
    lines(predict(a), col = "blue")
    

    gives

    enter image description here