What exactly is the z argument in plot_ly?

你离开我真会死。 提交于 2021-02-08 13:48:38

问题


I have three variables: x,y, and z and I want to produce a surface plot.

z<-runif(50,0,1) 
y<-runif(50,1,2)
x<-runif(50,3,6)
plot_ly(x = ~x, y = ~y, z= ~z) %>% add_surface()

I get the following error

Error: `z` must be a numeric matrix

What exactly does z represent if not the variable corresponding to the vertical axis? I have seen the Volcano example where they use the matrix to generate that plot, but I still am not sure what that z matrix represents in that example either.

What I would like is for someone to plot an easy to understand 3D function like z=f(x,y) = x^2 + y^2 using the surface functionality in plot_ly just so I can understand how to generate a plot based on three variables.


回答1:


The problem with your above code is, that you haven't specified the trace type - and what you need to pass to the z argument depends on this specification.

Passing the arguments x, y ,z suggests you want to display a scatter3d plot - you can test this by dropping add_surface():

z <- runif(50,0,1) 
y <- runif(50,1,2)
x <- runif(50,3,6)
plot_ly(x = x, y = y, z = z)

Which gives the warning:

No trace type specified: Based on info supplied, a 'scatter3d' trace seems appropriate. Read more about this trace type -> https://plot.ly/r/reference/#scatter3d No scatter3d mode specifed:
Setting the mode to markers Read more about this attribute -> https://plot.ly/r/reference/#scatter-mode

add_surface() on the other hand suggests you want to display a 3D Surface Plot. You already mentioned the volcano example. This kind of plot only needs a single numeric matrix to create the plot (argument z).

Accordingly with your example code you mixed up both plot types which leads to the error message.

How to avoid this confusion?

If you have a look at ?plot_ly there is a description for arguments "..." passed to the according trace type (z is one of them):

Arguments (i.e., attributes) passed along to the trace type. See schema() for a list of acceptable attributes for a given trace type (by going to traces -> type -> attributes).

schema() is a very useful hint to orient oneself in the plotly library. Execute the following code to browse through the different plotly trace types and their available attributes in a very convenient way:

# install.packages("listviewer")

library(plotly)
library(listviewer)
schema(jsonedit = interactive())

I guess this is what you were after in the first place:

z <- runif(50,0,1) 
y <- runif(50,1,2)
x <- runif(50,3,6)
plot_ly(x = x, y = y, z = z, type = 'mesh3d')


来源:https://stackoverflow.com/questions/54435463/what-exactly-is-the-z-argument-in-plot-ly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!