0

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
imtaiky
  • 191
  • 1
  • 12
  • Does this answer your question? [r plotly how to get 3d surface with lat, long and z](https://stackoverflow.com/questions/45405167/r-plotly-how-to-get-3d-surface-with-lat-long-and-z) – user2554330 May 02 '20 at 14:16
  • I have read this answer. However, I do not want to use `interp` function that does smoothing in any way (if I understand correctly). This is because I predict z values from GAMM model. – imtaiky May 02 '20 at 14:39
  • Just predict values on the grid instead of at the original points. – user2554330 May 02 '20 at 14:56
  • Thank you very much for the comment. That is what I need. But, finally, how can I make matrix of z along x-y coordinates when I have three vectors of x, y, z? I am very new to handle matrix in R. – imtaiky May 04 '20 at 12:27

1 Answers1

0

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

user2554330
  • 37,248
  • 4
  • 43
  • 90