【发布时间】:2017-11-03 11:26:33
【问题描述】:
我最近尝试使用 plotly 库在 RStudio 中绘制回归窗格并阅读了这篇文章:Add Regression Plane to 3d Scatter Plot in Plotly
我遵循了完全相同的程序,最终得到了一个回归平面,这显然是不正确的:
这是我的代码,我对每一步都进行了注释:sm 是我使用的data.frame
library(reshape2);
sm <- read.delim("Supermodel.dat", header = TRUE);
x1 <- sm$age
x2 <- sm$years
y <- sm$salary
df <- data.frame(x1, x2, y);
### Estimation of the regression plane
mod <- lm(y ~ x1+x2, data = df, na.action =
na.omit);
cf.mod <- coef(mod)
### Calculate z on a grid of x-y values
x1.seq <- seq(min(x1),max(x1),length.out=231)
x2.seq <- seq(min(x2),max(x2),length.out=231)
z.mtx <- t(outer(x1.seq, x2.seq, function(x1,x2)
cf.mod[1]+cf.mod[2]*x1+cf.mod[3]*x2))
#### Draw the plane with "plot_ly" and add points with "add_trace"
library(plotly)
# Draw plane with plotly surface plot
plane <- plot_ly(x=~x1.seq, y=~x2.seq, z=~z.mtx, colors =
c("#f5cb11", #b31d83"),type="surface") %>%
add_trace(data=df, x=x1, y=x2, z=y, mode="markers",
type="scatter3d",
marker = list(color="black", opacity=0.7, symbol=105)) %>%
layout(scene = list(aspectmode = "manual", aspectratio = list(x=1,
y=1, z=1), xaxis = list(title = "Age", range = c(12,24)), yaxis =
list(title = "Work experience (years)", range = c(0,10)), zaxis =
list(title = "Salary p.a. (k)", range = c(0,90) )))
plane
我检查了 str 函数,如果 x1.seq 和 x2.seq 具有相同数量的条目,并且它们都有 231 个数值。飞机被计算出来并显示出来,但它显然仍然是错误的。
PS:如果要运行代码,只需在 Regression 下从 Andy Fields 网站 (https://studysites.uk.sagepub.com/dsur/study/articles.htm) 下载文件 Supermodel.dat。
提前致谢, ありり
【问题讨论】:
-
如果您减小点大小,图形可能会更好看,并且更容易看到平面应该位于的位置。
-
更改了磅值,希望您现在能看得更清楚
标签: r regression plotly pane