You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将R语言predict()输出转为可用于plot_ly的数值矩阵

问题:将线性回归预测结果转为矩阵适配plotly的add_surface

现有R代码如下,通过线性回归拟合后对网格数据做预测,得到的terrain_lm是100个元素的一维数组,但需要将其转为数值矩阵才能用plot_ly的add_surface绘制曲面:

fit_lm=lm(z~x+y)

mix <- 2
max <- 12
miy <- 2
may <- 12

griddf <- expand.grid(x = seq(mix,max, length.out = 10),
                      y = seq( miy,may,length.out = 10))

Prediction_data <- data.frame(griddf)
colnames(Prediction_data) <- c("x", "y")
coordinates(Prediction_data ) <- ~ x + y

terrain_lm <- predict(fit_lm, Prediction_data)

期望用以下代码绘制曲面:

fig <- plot_ly()
fig <- fig %>%  add_surface(terrain_lm)

解决方案

核心修改:将一维预测结果转为矩阵

expand.grid生成的网格数据,是先固定x的每个值,遍历所有y值,因此预测结果的顺序是x1-y1, x1-y2,...,x1-y10, x2-y1,...,x10-y10。直接用matrix()函数将一维数组转为10×10的矩阵,指定按列填充(byrow=FALSE为默认值,可省略),就能匹配add_surface要求的矩阵结构:

fit_lm=lm(z~x+y)

mix <- 2
max <- 12
miy <- 2
may <- 12

# 生成网格数据,无需转成空间对象
griddf <- expand.grid(x = seq(mix,max, length.out = 10),
                      y = seq(miy,may,length.out = 10))

# 直接用griddf做预测,无需额外转成Prediction_data
terrain_lm <- predict(fit_lm, griddf)
# 将一维数组转为10行10列的矩阵
terrain_lm <- matrix(terrain_lm, nrow=10, ncol=10)

# 绘制曲面
fig <- plot_ly()
fig <- fig %>%  add_surface(terrain_lm)

额外优化:简化冗余代码

原代码中Prediction_data的定义和coordinates()转换是多余的,predict()可以直接接收expand.grid生成的data.frame,去掉这些步骤能简化代码逻辑。

内容的提问来源于stack exchange,提问作者Thomas Severin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:45:20