0

我正在尝试重新创建用于从 ggplot2 包中的 stat_smooth 估计平滑函数的过程。举个例子:

library(ggplot2)

n <- 100
X <- runif(n)*8
Y <- sin(3*X) + cos(X^2) + rnorm(n, 0, 0.5)

myData <- as.data.frame(cbind(X, Y))

p <- ggplot(myData, aes(y=Y, x=X)) + 
     stat_smooth(se = FALSE, size = 2) +
     geom_point(size = 1)
p
geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.

在此处输入图像描述

平滑线并不真正适合数据,但没关系。现在,让我们从头开始重新创建相同的图表。根据http://www.inside-r.org/r-doc/stats/loess我们需要使用三次加权内核和 2 次多项式(默认情况下)。我发现这篇http://www.maths.manchester.ac.uk/~peterf/MATH38011/NPR%20local%20Linear%20Estimator.pdf文章描述了如何估计光滑的黄土函数。我尝试重新创建此方法并将其用于我的数据:

Dfct <- function(t){
  if (abs(t) <= 1)
  ((1-abs(t)^3)^3) else
  0
  }

K_h <- function(x_0, x){
  f_hat <- NULL
  Dfct(abs(x - x_0)/h)
  }

m_hat_loess <- function(X, Y){
  e_1 <- c(1, 0, 0)
  m_hat <- NULL

  for(i in 1:length(X)){
  K_h_vector <- NULL

  for(j in 1:length(X)){
    K_h_vector <- c(K_h_vector, K_h(X[i], X[j]))
    }

  X_0 <- cbind(rep(1, length(X)), (X - X[i]), (X - X[i])^2)
  W <- diag(K_h_vector)

  m_hat <- c(m_hat,
  t(e_1)%*% solve(t(X_0)%*%W%*%X_0) %*% (t(X_0)%*%W%*%Y)
  )
}
m_hat
}

我不确定参数h应该使用什么,但根据一本书,我有“对于具有公制宽度的三立方内核,h是支撑区域的半径”。因此,我尝试的第一件事是:

h <- (max(X)-min(X))/2
Y_hat <- m_hat_loess(X, Y)

tempData <- as.data.frame(cbind(X, Y_hat))
ggplot(tempData , aes(x=X, y=Y_hat)) +
  geom_line(size = 2)

在此处输入图像描述

这显然不是同一个功能。我一直在使用不同的h值,但无法重新创建相同的曲线,这让我相信我在其他地方犯了错误。

4

1 回答 1

2

包中的stat_smooth(...)函数ggplot仅将您的数据(可能是子集)传递给loess(...)函数,如下所示:

library(ggplot2)
set.seed(1)
n <- 100
X <- runif(n)*8
Y <- sin(3*X) + cos(X^2) + rnorm(n, 0, 0.5)

myData <- data.frame(X,Y)
fit <- loess(Y~X,data=myData)
myData$pred <- predict(fit)

ggplot(myData, aes(X,Y))+
  geom_point()+
  stat_smooth(se=F, size=3)+
  geom_line(aes(X,pred),colour="yellow")

文档提供loess(...)了对计算方法的参考,特别是在此处

于 2014-02-26T16:37:43.623 回答