如何沿 x-y 坐标返回 z 值的矩阵以通过 R 中的 plot_ly 绘制 3D 曲面图? [英] How to return matrix of z values along x-y coordinates to make 3D surface plot by plot_ly in R?

查看:61
本文介绍了如何沿 x-y 坐标返回 z 值的矩阵以通过 R 中的 plot_ly 绘制 3D 曲面图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 R 中的 plot_ly 包制作 3D 曲面图.

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

x <- rep(1,times=40) # 40 个值y <- rep(2,times=40)z <- 代表(10,次= 40)

add_surface函数的使用而言,据我所知,我需要一个沿x-y坐标的z值矩阵.

否则它会给我错误;

plot_ly(x = x, y = y, z = z) %>% add_surface()错误:`z` 必须是数字矩阵

如何制作 z 矩阵?

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

<块引用>

添加了更多详细信息;我希望这些添加的行使我的问题更清楚

我知道 interp 函数的作用与

I would like to make 3D surface plot by plot_ly package in R.

I have three vectors that include x, y, and z values as below;

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

In terms of the usage of add_surface function, as far as I understand correctly, I need a matrix of z values along x-y coordinates.

Otherwise it gives me error;

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

Error: `z` must be a numeric matrix

How can I make the z matrix?

(here, the z matrix should have 1600 (40*40) values)

More details added; I hope these added lines make my question clearer

I know interp function does similar thing as in r plotly how to get 3d surface with lat, long and z. However, I do not want to use interp function in my case because it does smoothing in any way (if I understand correctly).

In my case, z values are data predicted from GAM model as below example;

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

解决方案

As far as I can see, this isn't possible with predict_gam, but you can do it with the standard predict function as follows. I'll use some fake data, since you didn't provide a reproducible example (or even one with two predictors):

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

This produces this output:

这篇关于如何沿 x-y 坐标返回 z 值的矩阵以通过 R 中的 plot_ly 绘制 3D 曲面图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆