[英]R plot confidence interval lines with a robust linear regression model (rlm)
I need to plot a Scatterplot with the confidence interval for a robust linear regression (rlm) model, all the examples I had found only work with LM.我需要为稳健的线性回归 (rlm) 模型绘制带有置信区间的散点图,我发现的所有示例仅适用于 LM。
This is my code:这是我的代码:
model1 <- rlm(weightsE$brain ~ weightsE$body)
newx <- seq(min(weightsE$body), max(weightsE$body), length.out=70)
newx<-as.data.frame(newx)
colnames(newx)<-"brain"
conf_interval <- predict(model1, newdata = data.frame(x=newx), interval = 'confidence',
level=0.95)
#create scatterplot of values with regression line
plot(weightsE$body, weightsE$body)
abline(model1)
#add dashed lines (lty=2) for the 95% confidence interval
lines(newx, conf_interval[,2], col="blue", lty=2)
lines(newx, conf_interval[,3], col="blue", lty=2)
but the results of predict don't produce a straight line for the upper and lower level, they are more like random predictions.但是predict的结果并没有为上下层产生一条直线,它们更像是随机预测。
You have a few problems to fix here.你有几个问题需要在这里解决。
rlm(weightsE$brain ~ weightsE$body)
, instead use rlm(brain ~ body, data = weightsE)
.rlm(weightsE$brain ~ weightsE$body)
,而是使用rlm(brain ~ body, data = weightsE)
。 Otherwise, the model cannot take new data for predictions.weightsE$body
values, not from the new data you pass into predict
weightsE$body
值产生,而不是由您传递给predict
的新数据产生newx
is already a data frame, but for some reason you are wrapping it inside another data frame when you do newdata = data.frame(x=newx)
. newx
已经是一个数据框,但由于某种原因,当您执行newdata = data.frame(x=newx)
时,您将其包装在另一个数据框中。 Just pass newx
.newx
。plot(weightsE$body, weightsE$body)
, when it should be plot(weightsE$body, weightsE$brain)
plot(weightsE$body, weightsE$body)
绘图,它应该是plot(weightsE$body, weightsE$brain)
Putting all this together, and using a dummy data set with the same names as your own (see below), we get:将所有这些放在一起,并使用与您自己的名称相同的虚拟数据集(见下文),我们得到:
library(MASS)
model1 <- rlm(brain ~ body, data = weightsE)
newx <- data.frame(body = seq(min(weightsE$body),
max(weightsE$body), length.out=70))
conf_interval <- predict(model1, newdata = data.frame(x=newx),
interval = 'confidence',
level=0.95)
#create scatterplot of values with regression line
plot(weightsE$body, weightsE$brain)
abline(model1)
#add dashed lines (lty=2) for the 95% confidence interval
lines(newx$body, conf_interval[, 2], col = "blue", lty = 2)
lines(newx$body, conf_interval[, 3], col = "blue", lty = 2)
Incidentally, you could do the whole thing in ggplot in much less code:顺便说一句,您可以用更少的代码在 ggplot 中完成所有工作:
library(ggplot2)
ggplot(weightsE, aes(body, brain)) +
geom_point() +
geom_smooth(method = MASS::rlm)
Reproducible dummy data可重现的虚拟数据
data(mtcars)
weightsE <- setNames(mtcars[c(1, 6)], c("brain", "body"))
weightsE$body <- 10 - weightsE$body
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.