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

R语言scatterplot3d包绘制3D散点图回归平面不显示问题求助

问题原因

你代码的核心错误是散点图的坐标轴顺序和线性回归模型的自变量顺序不匹配,导致回归平面被渲染到了可视化范围外,因此看不到。

你调用scatterplot3d()时传入的三个参数顺序是height(x轴)、weight(y轴)、age(z轴),但拟合的线性模型lm(age ~ weight + height)里,排在前面的自变量是weight、第二位是height,plane3d()默认会把模型的第一个自变量对应x轴、第二个对应y轴,顺序错位就导致平面不在可视区域内。


解决方法

任选一种修改方案即可:

  1. 调整线性模型的自变量顺序,和散点图的x、y轴顺序保持一致
# 把原模型的weight和height换顺序即可
model_1 <- lm(age ~ height + weight, data = my_data)
  1. 调用plane3d()时手动指定系数对应的坐标轴,不需要修改模型
s3d$plane3d(Intercept = coef(model_1)[1],
            x.coef = coef(model_1)["height"],
            y.coef = coef(model_1)["weight"],
            draw_polygon = TRUE, draw_lines = TRUE, 
            polygon_args = list(col = rgb(.1, .2, .7, .5)))

完整可运行代码

library(scatterplot3d)

# 示例数据
my_data <- data.frame(read.table(header=TRUE,
row.names = 1,
text="
                         weight   height age
                      1  2998.958 15.26611  53
                      2  3002.208 18.08711  52
                      3  3008.171 16.70896  49
                      4  3002.374 17.37032  55
                      5  3000.658 18.04860  50
                      6  3002.688 17.24797  45
                      7  3004.923 16.45360  47
                      8  2987.264 16.71712  47
                      9  3011.332 17.76626  50
                      10 2983.783 18.10337  42
                      11 3007.167 18.18355  50
                      12 3007.049 18.11375  53
                      13 3002.656 15.49990  42
                      14 2986.710 16.73089  47
                      15 2998.286 17.12075  52
"))

# 调整自变量顺序和坐标轴匹配
model_1 <- lm(age ~ height + weight, data = my_data)

# 绘制散点图
s3d <- scatterplot3d(my_data$height, my_data$weight, my_data$age, pch = 19, type = "p", color = "darkgrey",
                     main = "Regression Plane", grid = TRUE, box = FALSE,  
                     mar = c(2.5, 2.5, 2, 1.5), angle = 55)

# 绘制回归平面
s3d$plane3d(model_1, draw_polygon = TRUE, draw_lines = TRUE, 
            polygon_args = list(col = rgb(.1, .2, .7, .5)))

# 只叠加正残差的点(原代码没有加筛选条件,会重复绘制所有点)
wh <- resid(model_1) > 0
s3d$points3d(my_data$height[wh], my_data$weight[wh], my_data$age[wh], pch = 19)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:54:03