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

时间:2019-11-14 22:07:12

标签: r linear-regression

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

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用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,但我只是更喜欢这样做。