使用 loess() 添加平滑曲线以绘制

Add smoothed curves to plot using loess()

我有这个包的每月数据:波士顿,我做了一个时间序列

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

现在我想通过使用局部多项式回归拟合向该图中添加两条平滑曲线。我使用的是 loess(),但一定有什么地方不对,因为它给我错误。这是我正在使用的代码:

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

你想要这样的东西吗?

我使用了 {ggplot2} 的情节。 geom_smooth() 允许将 loessspan 参数一起使用 - 假设您要使用 loess.

为了地块的排列,即堆叠+一个x-axis,我使用了{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"))

给予

reprex package (v2.0.1)

创建于 2022-05-19

您可以通过以下方式避免显示平滑附近的置信区间 将参数 se = FALSE 添加到 geom_smooth().


loess(...) 上的一个简短修正,您需要指定 timeseries 对象的列以允许回归,即。 e.

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

除了 1 和 2,您还可以使用 "bse""nyase"。然后,对于 "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")

给予