Reputation: 3057
I try to plot confidence interval of a linear regression line, but the lines()
function doesn't work. What should I do to fix this issue?
Jahr<-Jahr[2:26]
Menge<-Menge[1:25]
plot(Jahr,Menge,xlim=c(1991,2016),ylim=c(25000000,550000000))
coef<-lm(Menge~Jahr)
abline(coef,col="blue")
PredictPoint<-predict(coef,data.frame(Jahr=c(2016)),interval="none")
points.default(x=2016,y=PredictPoint,type="p",col="red",pch=1)
conf<-predict(coef, data.frame(Jahr=c(2016)), interval = "confidence")
lines(data.frame(Jahr=c(2016)),conf[,2],col="red")
lines(data.frame(Jahr=c(2016)),conf[,3],col="red")
Upvotes: 1
Views: 161
Reputation: 73295
The problem is, you only predict one data point at year 2016:
conf<-predict(coef, data.frame(Jahr=c(2016)), interval = "confidence")
how could lines
line up a single point to produce a line? By default, lines
has type = "l"
. If you set type = "b"
, it will display both points and lines. In case you only have one datum, it will display points.
Another problem is that you pass a data frame rather than a vector to the first argument of lines
.
Altogether, do:
lines(2016, conf[,2], col="red", type = "b")
lines(2016, conf[,3], col="red", type = "b")
If you only want confidence interval for this single point, maybe this is better:
segments(2016, conf[,2], 2016, conf[,3], lty = 2, col = "red")
Upvotes: 1