R中使用plotly绘制3D表面图

3

我想使用R的plotly库创建一个三维表面图,显示x、y和z坐标数据,类似于下面链接中所示的内容:

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

从链接的示例中可以看出,plot_ly函数需要将z坐标放在一个维度为x * y的矩阵中,就像在datasets::volcano中看到的那样。我希望得到一些关于如何构建这个矩阵的指导。下面是我的样本x,y坐标数据:

## 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)

通过一个公式从x,y对中计算z坐标(这里使用的示例公式是x + y)。我尝试过类似于以下的东西:

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

但这并不能实现我想要达到的配对组合。

1
z <- outer(xSeq, ySeq, "+") - Stéphane Laurent
1个回答

0

Plotly表面需要一个矩阵,因此您可以直接使用以下代码:

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

不要使用列表。因此,通过运行以下代码:

## 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

得到以下图形: 3D Plot

您可能需要点击并旋转一下才能看到平面。希望对您有所帮助,祝好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接