Plotting 3 Dimensional Graphs in R

I am trying to make a 3 Dimensional Graph between variables "x, y and w", and color this graph according to values of "z" :

X <- seq(0,3.1,0.1)
Y <- seq(0,3.1,0.1)
W <- seq(0,3.1,0.1)
DF <- expand.grid(X,Y, W)

#Compute variable for colors
DF$Z <- sin(DF$Var1) + cos(DF$Var2) + sin(DF$Var3)

#make a matrix of color values
Mat <- matrix(DF$Z,nrow = 32)

#make a matrix for z values
#had real data.
Mat2 <- matrix(rep(c(1:16,16:1),32),nrow=32)

plot_ly(y=~Y,x=X,  z=~W) %>%  

But this produces an error:

Error: `z` must be a numeric matrix

Can anyone please show me how to fix this problem?


Maybe this example will be clearer than my last example. The idea is to calculate or assign a z value and color value at each point on an x,y grid. Since I'm inventing data, I calculate both the z and the color values. These values then must be passed as matrices to the plotly functions. The matrices have as many rows as there are x values and as many columns as there are y values.
In your example, you make a grid of the x, y, and z values. Instead of doing that, make a grid of only the x and y values and then provide z and color values for each x,y grid point.

#Make a grid of X & y values
X <- seq(0,3.1,0.1)
Y <- seq(10,13.1,0.1)
DF <- expand.grid(X,Y)

#Compute z values at each grid point
DF$Z <- sin(DF$Var1) + cos(DF$Var2)

#Compute values for color at each grid point
DF$C <- 3.2*DF$Var1 + 1.4*DF$Var2 - DF$Var1*DF$Var2*0.9

#make a matrix of Z values
Mat <- matrix(DF$Z,nrow = 32)

#make a matrix for color values
Mat2 <- matrix(DF$C,nrow = 32)

plot_ly(y=~Y,x=X,  z=~Mat) %>%  
1 Like

thank you so much for your reply!

Can you please explain how you came up with this line of code?

DF$C <- 3.2*DF$Var1 + 1.4*DF$Var2 - DF$Var1*DF$Var2*0.9

Thank you so much!

Why do you need both "mat" and "mat2"?

The calculation of the C column in DF is just an arbitrary transformation of the x and y values. I needed to produce some numbers to determine the color scale and I typed out that formula. It does not have any meaning.

Mat stores the z values of the plot. Mat2 stores the variable that determines the color of the surface. If you use Mat in both places, then the z position and the color will represent the same information, the value of the Z column in DF. That might be a useful thing to do but it is not what you want to do, at least as I understand it.

1 Like

Thank you so much for your answer! I will post another question that relates to this one - thank you so much for your help!

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.