Search code examples
rsurfaceplot3d

"...argument 4 matches multiple formal arguments" - 3D surface plot with plot3D


I can't get the scatter3D() function to work in R. I would like to plot a surface but am unable to get the code to run although it is very simple to some I found online. I have tried reading the CRAN code documentation but I can't get anywhere. I would like my code to run.

Essentially there is a problem with some variable I am putting in but I can't see where. I think it might be hidden inside a function and the error message is not actually for me.

Any help would be appreciated.

Code:

library("plot3D")

w <- 1:100
sigma <- 5
x <- w + rnorm(w, w, 2*sigma)
y <- w + rnorm(w, w, sigma)
z<- w + rnorm(w, w, 3*sigma)

a <- c()
for (i in 1:10){
  a <- c(a, rep(10*i, times = 10))
}
b <- rep(seq(10, 100, 10), times = 10)
ratio = 0.4
d = ratio*a + (1 - ratio)*b + rnorm(100, 0, 10)

fit <- lm(d ~ a + b)
grid.lines = 26
a.pred <- seq(min(a), max(a), length.out = grid.lines)
b.pred <- seq(min(b), max(b), length.out = grid.lines)
ab <- expand.grid(a = a.pred, b = b.pred)
d.pred <- matrix(predict(fit, newdata = ab), 
                 nrow = grid.lines, ncol = grid.lines)
fitpoints <- predict(fit)
scatter plot with regression plane
scatter3D(a,b,d, pch = 18, cex = 2, 
          theta = 20, phi = 20,
          surf = list(a=a.pred, b=b.pred, d=d.pred,  
                      facets = F, fit = fitpoints))

Error message:

Error in addimg(poly = NULL, plist = plist, a = c(10, 13.6, 17.2, 20.8, : argument 4 matches multiple formal arguments


Solution

  • I think you need to call x, y, and z-axis:

    # scatter plot with regression plane
    scatter3D(a,b,d, pch = 18, cex = 2, 
              theta = 20, phi = 20,
              surf = list(x=a.pred, y=b.pred, z=d.pred,
                          facets = F, fit = fitpoints))
    

    This worked in my case.

    Comment concerning bugfixing:

    • Run your code line by line (RStudio Ctrl + Enter). Then you realize that your scatter3D is the problem.
    • Remove arguments until the command works. In your case this suggested that surf = list(...) was the problem.