Plot 3D plane (true regression surface)

后端 未结 3 2150
天命终不由人
天命终不由人 2020-12-09 07:06

I\'m trying to simulate some data (x1 and x2 - my explanatory variables), calculate y using a specified function + random noise and plot the resulting observations AND the t

3条回答
  •  忘掉有多难
    2020-12-09 07:29

    IRTFM's somewhat imperfect answers above let me to a thread on the CRAN help pages.
    https://stat.ethz.ch/pipermail/r-help/2013-December/364037.html
    I extracted the relevant bits of code and turned them into a function like so:

    require(rgl)
    pred.surf.3d <- function(df, x.nm,y.nm,z.nm, ...){
      x <- df[,x.nm]; y <- df[,y.nm]; z<-df[,z.nm]
      fit <- lm(z ~ x + y + x*y + x^2 + y^2)
      xnew <- seq(range(x)[1],range(x)[2],len=20)
      ynew <- seq(range(y)[1],range(y)[2],len=20)
      df <- expand.grid(x=xnew, y=ynew)
      df$z <- predict(fit, newdata=df)
      with(df, surface3d(xnew, ynew, z=df$z))
    }
    

    I may end up bundling this into my CRAN utility package at some point.
    In the mean time, I hope you find it useful! (Run it on IRTFM's first code chunk like so:)

    pred.surf.3d(data.frame(x1,x2,y),'x1','x2','y')
    

提交回复
热议问题