如何在一幅图中绘制拟合值,观测值以及置信区间和预测区间

问题描述 投票:0回答:1

到目前为止,我一直负责绘制标题中说明的图表,这是我的代码:

model<-lm(y~.,data=data)
pred <- prediction(model,data=data,interval = 'confidence')
lwr<-pred[76:150]
upr<-pred[151:225]
interval<-cbind(lwr,upr)

我不确定之后该去哪里,因为我不知道如何绘制间隔。

r linear-regression
1个回答
0
投票

您可以使用ggplot2执行此操作

library(tidyverse)

data(mtcars)


mylm <- lm(mpg ~ wt, data = mtcars)
summary(mylm)

myc <- predict(mylm, newdata = mtcars$wt, interval = "confidence")

fit <- myc[,1]
low <- myc[,2]
high <- myc[,3]


myp <- predict(mylm, newdata = mtcars, interval = "predict")



mtcars %>% 
  ggplot() +
  geom_point(aes(x = wt, y = mpg)) +
  geom_point(aes(x = wt, y = fit), color = "green") +
  geom_line(aes(x = wt, y = fit), color = "green") +
  geom_point(aes(x = wt, y = low), color = "red") +
  geom_line(aes(x = wt, y = low), color = "red") +
  geom_point(aes(x = wt, y = high), color = "red") +
  geom_line(aes(x = wt, y = high), color = "red") +
  geom_point(aes(x = wt, y = myp[,1]), color = "blue") +
  geom_line(aes(x = wt, y = myp[,1]), color = "blue") +
  geom_point(aes(x = wt, y = myp[,2]), color = "darksalmon") +
  geom_line(aes(x = wt, y = myp[,2]), color = "darksalmon") +
  geom_point(aes(x = wt, y = myp[,3]), color = "darksalmon") +
  geom_line(aes(x = wt, y = myp[,3]), color = "darksalmon") 

enter image description here

合适的是蓝色,置信度是红色,而预测的深三文鱼是黑色。

通过我知道的方式,您可以将wt和mpg放入ggplot(),并使其影响所有geom,但我只是更喜欢这样做。

© www.soinside.com 2019 - 2024. All rights reserved.