R. ggplot2。从stat_smooth方法重新创建平滑曲线

时间:2014-02-26 15:07:44

标签: r ggplot2 loess

我正在尝试重新创建用于从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.

enter image description here

平滑线并不真正适合数据,但无关紧要。现在,让我们从头开始重新创建相同的图形。根据{{​​3}},我们需要使用tricubic加权内核和2阶多项式(默认情况下)。我发现这篇http://www.inside-r.org/r-doc/stats/loess文章描述了如何估算平滑的黄土函数。我尝试重新创建此方法并将其用于我的数据:

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)

enter image description here

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

1 个答案:

答案 0 :(得分: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(...)的{​​{3}}提供了对计算方法的引用,特别是documentation