【问题标题】:How to return matrix of z values along x-y coordinates to make 3D surface plot by plot_ly in R?如何沿 x-y 坐标返回 z 值矩阵以通过 R 中的 plot_ly 绘制 3D 曲面图?
【发布时间】:2020-08-16 23:49:14
【问题描述】:

我想通过plot_ly 包在R 中制作3D 曲面图。

我有三个向量,包括 x、y 和 z 值,如下所示;

x <- rep(1,times=40) # 40 values 
y <- rep(2,times=40)
z <- rep(10, times=40)

add_surface函数的使用而言,据我理解正确,我需要一个沿x-y坐标的z值矩阵。

否则会报错;

plot_ly(x = x, y = y, z = z) %>% add_surface()

Error: `z` must be a numeric matrix

如何制作 z 矩阵?

(这里,z矩阵应该有1600(40*40)个值)

添加了更多细节;我希望这些添加的行能让我的问题更清楚

我知道interp 函数的作用与r plotly how to get 3d surface with lat, long and z 中的类似。但是,我不想在我的情况下使用 interp 函数,因为它会以任何方式平滑(如果我理解正确的话)。

在我的例子中,z 值是从 GAM 模型预测的数据,如下例所示;

gam_fit <- gam(y~ s(x),data=df)
gam_pred <-  predict_gam(gamm_fit)
  x <- gam_pred$x
  y <- gam_pred$y
  z <- gam_pred$fit

【问题讨论】:

  • 我已阅读此答案。但是,我不想使用以任何方式进行平滑处理的interp 函数(如果我理解正确的话)。这是因为我从 GAMM 模型预测 z 值。
  • 只预测网格上的值而不是原始点。
  • 非常感谢您的评论。这就是我需要的。但是,最后,当我有 x、y、z 的三个向量时,如何沿 x-y 坐标制作 z 矩阵?我对在 R 中处理矩阵非常陌生。

标签: r plotly r-plotly gam


【解决方案1】:

据我所知,predict_gam 无法做到这一点,但您可以使用标准的predict 函数来做到这一点,如下所示。我将使用一些假数据,因为您没有提供可重现的示例(甚至没有提供具有两个预测变量的示例):

library(mgcv)
x <- runif(100)
y <- runif(100)
z <- x^2 + y + rnorm(100)
df <- data.frame(x, y, z)
gam_fit <- gam(z ~ s(x) + s(y), data = df)

newx <- seq(0, 1, len=20)
newy <- seq(0, 1, len=30)
newxy <- expand.grid(x = newx, y = newy)
z <- matrix(predict(gam_fit, newdata = newxy), 20, 30)
library(plotly)
plot_ly(x = newx, y = newy, z = z) %>% add_surface()

这会产生这个输出:

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多