Black Lives Matter. Please consider donating to Black Girls Code today.

3d Surface plot in R


I’m trying to plot my dataframe as a 3D surface in R.
I have 3 columns, but I don’t know what the syntax is like, as the example only shows:
plot_ly(z = volcanoes, type=“surface”)

The documentation says there are x/y/z and xsrc/ysrc/zsrc parameters, but how do I use these?
I always end up with an empty plot when I try:

plot_ly(df, xsrc=df$a, ysrc=df$b, zsrc=df$c)
plot_ly(x=df$a, y=df$b, z=df$c)


I’m able to generate a plot if I just pass in my matrix version of the df as the z value, but it doesn’t know the correct axes to place each variable on. How do I fix that?

Hi !
Here’s s simple example. What you’ll need is a list with x, y and z variables.


  • x is a vector
  • y is a vector
  • z is a matrix with dimensions length(x) and length(y)

df.list <- list(x = 1:100,
           y = 500:599,
           z = matrix(rnorm(10000), nrow = 100))

df.dataframe <- data.frame(x = 1:100,
                           y = 500:599,
                           z = sample(1:200, size = 100))

# Works fine
plot_ly(df.list, x = x, y = y, z = z, type = "surface")

# Doesn't work
# dimension of the z parameter != dim(x) x dim(y)
plot_ly(df.dataframe, x = x, y = y, z = z, type = "surface")

@royr2 do you know the interpretation of the matrix z[i,j] relative to x and y?