Home > database >  Add smoothed curves to plot using loess()
Add smoothed curves to plot using loess()

Time:05-20

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)

CodePudding user response:

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 enter image description here

  • Related