gpt4 book ai didi

r - 散点图3d : regression plane with residuals

转载 作者:行者123 更新时间:2023-12-02 03:37:46 30 4
gpt4 key购买 nike

使用scatterplot3d在 R 中,我试图从观察到回归平面绘制红线:

wh <- iris$Species != "setosa"
x <- iris$Sepal.Width[wh]
y <- iris$Sepal.Length[wh]
z <- iris$Petal.Width[wh]
df <- data.frame(x, y, z)

LM <- lm(y ~ x + z, df)
library(scatterplot3d)
G <- scatterplot3d(x, z, y, highlight.3d = FALSE, type = "p")
G$plane3d(LM, draw_polygon = TRUE, draw_lines = FALSE)

Regression Plane

要获取以下图片的 3D 等效内容:

enter image description here

在 2D 中,我可以使用 segments :

pred  <- predict(model) 
segments(x, y, x, pred, col = 2)

但是在 3D 中我对坐标感到困惑。

最佳答案

我决定也包含我自己的实现,以防其他人想要使用它。

回归平面

require("scatterplot3d")

# Data, linear regression with two explanatory variables
wh <- iris$Species != "setosa"
x <- iris$Sepal.Width[wh]
y <- iris$Sepal.Length[wh]
z <- iris$Petal.Width[wh]
df <- data.frame(x, y, z)
LM <- lm(y ~ x + z, df)

# scatterplot
s3d <- scatterplot3d(x, z, y, pch = 19, type = "p", color = "darkgrey",
main = "Regression Plane", grid = TRUE, box = FALSE,
mar = c(2.5, 2.5, 2, 1.5), angle = 55)

# regression plane
s3d$plane3d(LM, draw_polygon = TRUE, draw_lines = TRUE,
polygon_args = list(col = rgb(.1, .2, .7, .5)))

# overlay positive residuals
wh <- resid(LM) > 0
s3d$points3d(x[wh], z[wh], y[wh], pch = 19)

regression plane

残差

# scatterplot
s3d <- scatterplot3d(x, z, y, pch = 19, type = "p", color = "darkgrey",
main = "Regression Plane", grid = TRUE, box = FALSE,
mar = c(2.5, 2.5, 2, 1.5), angle = 55)

# compute locations of segments
orig <- s3d$xyz.convert(x, z, y)
plane <- s3d$xyz.convert(x, z, fitted(LM))
i.negpos <- 1 + (resid(LM) > 0) # which residuals are above the plane?

# draw residual distances to regression plane
segments(orig$x, orig$y, plane$x, plane$y, col = "red", lty = c(2, 1)[i.negpos],
lwd = 1.5)

# draw the regression plane
s3d$plane3d(LM, draw_polygon = TRUE, draw_lines = TRUE,
polygon_args = list(col = rgb(0.8, 0.8, 0.8, 0.8)))

# redraw positive residuals and segments above the plane
wh <- resid(LM) > 0
segments(orig$x[wh], orig$y[wh], plane$x[wh], plane$y[wh], col = "red", lty = 1, lwd = 1.5)
s3d$points3d(x[wh], z[wh], y[wh], pch = 19)

residuals

<小时/>

最终结果:

虽然我非常欣赏 scatterplot3d 函数的便利性,但最终我得到了 copying the entire function from github ,因为基 plot 中的几个参数要么被 scatterplot3d 强制,要么没有正确传递给 scatterplot3d(例如,使用 las 进行轴旋转,使用 las 进行字符扩展) cexcex.main 等)。我不确定这么长而困惑的代码块放在这里是否合适,所以我在上面添加了 MWE。

无论如何,这就是我最终在我的书中包含的内容:

end result

(是的,这实际上只是虹膜数据集,不要告诉任何人。)

关于r - 散点图3d : regression plane with residuals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47344850/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com