Stacking Plotly Graphs on Top Of Each Other

I am trying to stack several 3D surfaces on top of each other in plotly, something like this:

#functional code copied from the official plotly R website 
library(plotly)
z <- c(
  c(8.83,8.89,8.81,8.87,8.9,8.87),
  c(8.89,8.94,8.85,8.94,8.96,8.92),
  c(8.84,8.9,8.82,8.92,8.93,8.91),
  c(8.79,8.85,8.79,8.9,8.94,8.92),
  c(8.79,8.88,8.81,8.9,8.95,8.92),
  c(8.8,8.82,8.78,8.91,8.94,8.92),
  c(8.75,8.78,8.77,8.91,8.95,8.92),
  c(8.8,8.8,8.77,8.91,8.95,8.94),
  c(8.74,8.81,8.76,8.93,8.98,8.99),
  c(8.89,8.99,8.92,9.1,9.13,9.11),
  c(8.97,8.97,8.91,9.09,9.11,9.11),
  c(9.04,9.08,9.05,9.25,9.28,9.27),
  c(9,9.01,9,9.2,9.23,9.2),
  c(8.99,8.99,8.98,9.18,9.2,9.19),
  c(8.93,8.97,8.97,9.18,9.2,9.18)
)
dim(z) <- c(15,6)
z2 <- z + 1
z3 <- z - 1

fig <- plot_ly(showscale = FALSE)
fig <- fig %>% add_surface(z = ~z)
fig <- fig %>% add_surface(z = ~z2, opacity = 0.98)
fig <- fig %>% add_surface(z = ~z3, opacity = 0.98)

fig

I tried to replicate this example with my own data - I was able to plot each surface separately, but I was not able to figure out how to stack these surfaces on top of each other. For example:

library(plotly)

#plot1
X1 <- seq(0,100,1)
Y1 <- seq(0,100,1)
DF <- expand.grid(X1,Y1)
DF$Z1 <- sin(DF$Var1) + cos(DF$Var2)
Z1 <- matrix(DF$Z1, nrow = 100)
plot_ly(y = ~Y1, x = ~X1, z=~Z1) %>% add_surface() 

#plot2
X2 <- seq(0,100,1)
Y2 <- seq(0,100,1)
DF2 <- expand.grid(X2,Y2)
DF2$Z2 <- -sin(DF2$Var1) + 0.5*cos(DF2$Var2)
Z2 <- matrix(DF2$Z2, nrow = 100)
plot_ly(y = ~Y2, x = ~X2, z=~Z2) %>% add_surface() 


#plot3
X3 <- seq(0,100,1)
Y3 <- seq(0,100,1)
DF3 <- expand.grid(X3,Y3)
DF$Z3 <- DF3$Var2^2  + DF3$Var1^2
Z3 <- matrix(DF3$Z3, nrow = 100)
plot_ly(y = ~Y3, x = ~X3, z=~Z3) %>% add_surface()

But this does not work when I stack them on top of each other:

#### Stack on Top

fig <- plot_ly(y = ~DF$Y, x = ~DF$X, z=~DF$Z1) %>% add_surface() 
fig <- fig %>% add_surface(z = ~Z2, opacity = 0.98)
fig <- fig %>% add_surface(z = ~Z3, opacity = 0.98)

This produces the following error:

Error: z must be a numeric matrix

Can someone please show me what I am doing wrong?

Thanks

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.