Search code examples
rplotlyr-plotlygam

How to return matrix of z values along x-y coordinates to make 3D surface plot by plot_ly in R?


I would like to make 3D surface plot by plot_ly package in R.

I have three vectors that include x, y, and z values as below;

x <- rep(1,times=40) # 40 values 
y <- rep(2,times=40)
z <- rep(10, times=40)

In terms of the usage of add_surface function, as far as I understand correctly, I need a matrix of z values along x-y coordinates.

Otherwise it gives me error;

plot_ly(x = x, y = y, z = z) %>% add_surface()

Error: `z` must be a numeric matrix

How can I make the z matrix?

(here, the z matrix should have 1600 (40*40) values)

More details added; I hope these added lines make my question clearer

I know interp function does similar thing as in r plotly how to get 3d surface with lat, long and z. However, I do not want to use interp function in my case because it does smoothing in any way (if I understand correctly).

In my case, z values are data predicted from GAM model as below example;

gam_fit <- gam(y~ s(x),data=df)
gam_pred <-  predict_gam(gamm_fit)
  x <- gam_pred$x
  y <- gam_pred$y
  z <- gam_pred$fit

Solution

  • As far as I can see, this isn't possible with predict_gam, but you can do it with the standard predict function as follows. I'll use some fake data, since you didn't provide a reproducible example (or even one with two predictors):

    library(mgcv)
    x <- runif(100)
    y <- runif(100)
    z <- x^2 + y + rnorm(100)
    df <- data.frame(x, y, z)
    gam_fit <- gam(z ~ s(x) + s(y), data = df)
    
    newx <- seq(0, 1, len=20)
    newy <- seq(0, 1, len=30)
    newxy <- expand.grid(x = newx, y = newy)
    z <- matrix(predict(gam_fit, newdata = newxy), 20, 30)
    library(plotly)
    plot_ly(x = newx, y = newy, z = z) %>% add_surface()
    

    This produces this output:

    screenshot