Reputation: 243
I am trying to plot confidence bands for a regression, using a function but the lines for my upper and lower prediction bands look weird and blurry. Can anyone spot the issue, because I can't seem to find anything wrong?
Here is the code:
drawPrediction <- function(x, y) {
lm.model <- lm(y ~ x)
ci <- predict(lm.model, interval = "prediction")
plot(x,y)
abline(lm.model, col = "red")
lines(x, ci[,2], lty = 2, col = 'blue')
lines(x,ci[,3], lty = 2, col = 'blue' )
}
Gives this result for some test data (the R state.x77 data, regressing Income on Illiteracy):
This is the code I used for the test above:
> test <- as.data.frame(state.x77)
> drawPrediction(test$Illiteracy, test$Income)
Upvotes: 1
Views: 1290
Reputation: 37641
The problem is that the x's are not sorted so you are drawing lines all over the place, not just between consecutive x's. Instead, use
lm.model <- lm(Income ~ Illiteracy, data=as.data.frame(state.x77))
ci <- predict(lm.model, interval = "prediction")
plot(x,y)
abline(lm.model, col = "red")
lines(sort(x), ci[order(x),2], lty = 2, col = 'blue')
lines(sort(x), ci[order(x),3], lty = 2, col = 'blue' )
Upvotes: 3