2
votes

I try to produce a 3D surface plot using plot_ly like this:

rm(list=ls())
set.seed(42)
x_val <- seq(-2,2,0.1)
y_val <- seq(0,1,0.1)

zz <- matrix(NA, nrow = length(x_val), ncol = length(y_val))
for(i in 1:length(x_val)){
  for(j in 1:length(y_val)){
    zz[i,j] <- rnorm(1, x_val[i], y_val[j]+0.01)
  }
}

plot_ly(x = x_val, y = y_val, z = zz, type = "surface") 

The resulting plots looks like this:

enter image description here

As you can see, the x_axis has a range between -2 and 2, but only values between -1 and -2 are plotted.

How can I plot the results for the full range of x-values?

As suggested in the comments, I tried to implement the solution from this question (plotly 3d surface - change cube to rectangular space).

However, using

plot_ly(x = x_val, y = y_val, z = zz, type = "surface")  %>% 
  layout(
    scene = list(
      xaxis = list(range = c(-2,2)),
      yaxis = list(range = c(0,1)),
      zaxis = list(range = range(zz)),
      aspectratio = list(x = 2, y = 1, z = 0.4))
  )

leads to this image with the same problem:

enter image description here

1
Hi. This thread might be a duplicate? stackoverflow.com/questions/37032687/…olorcain
There seem to have been changes to the package: 'layout' objects don't have these attributes: 'autorange', 'aspectmode'. An adjusted version does not solve the problem, I have edited the original postuser3825755

1 Answers

1
votes

The x-axis refers to the columns of the zz matrix.
The length of your x_val vector is 41 and the number of columns of zz is 11.
Thus, for a correct visualization, the zz matrix needs to be trasposed:

plot_ly(x = x_val, y = y_val, z = t(zz), type = "surface") 

enter image description here