3d Surface Plot in R with plotly

Viewed 1126

I am looking to use the R plotly library to create a 3d surface plot of x,y,z coordinate data, similar to what is shown at the link below:

https://plot.ly/r/3d-surface-plots/

It appears that the plot_ly function requires the z coordinates to be in a matrix of dimensions x * y, as seen in datasets::volcano, used in the linked example. I'd appreciate some guidance on how to construct this matrix. Here is my sample x,y coordinate data:

## x coordinates
xSeq = seq(0, 1, .01)
## y coordinates
ySeq = seq(0, 1, .01)
## list with x, y coordinates
exmplList = list(x = xSeq, y = ySeq)

The z coordinates would be calculated via a formula from the x,y pairs (example formula used here is x + y). I've played around with something like:

exmplList = within(exmplList, z <- matrix(x + y, nrow = length(xSeq), ncol = length(ySeq)))

But that doesn't accomplish the pair combinations that I am trying to achieve.

1 Answers

Plotly surface needs a matrix so you could simply use this bit directly:

z = matrix(xSeq + ySeq, nrow = length(xSeq), ncol = length(ySeq))

Instead of doing a list. So, by running the following code:

## x coordinates
xSeq = seq(0, 1, 0.01)
## y coordinates
ySeq = seq(0, 1, 0.01)
## list with x, y coordinates
z = matrix(xSeq + ySeq, nrow = length(xSeq), ncol = length(ySeq))

fig = plot_ly(z = ~z) %>% add_surface()
fig

One obtains the following plot: 3D Plot

You might need to click and rotate a bit to see the plane. Hope it helps, cheers.

Related