I tried to draw the intervals on the regression plot, but the lines function didn't work at all, and the matlines function just draw three lines without slope.
My dataset is from package "faraway".
y = salmonella$colonies
x = salmonella$dose
salmonella_fit = lm(y ~ x)
summary(salmonella_fit)
newdose = data.frame( x= c(20, 40, 60, 80, 120, 150, 180, 300,500))
conf_interval = predict(salmonella_fit, newdose, interval = "confidence", level = 0.95)
xval = c(20, 40, 60, 80, 120, 150, 180, 300, 500)
plot(conf_interval[ ,1] ~ xval, xlab = "newdose", ylab ="colonies", main = "Regression")
abline(salmonella_fit, col="lightblue")
lines(conf_interval[,2] ~ xval, col ="blue", type = "l")
lines(conf_interval[,3] ~ xval, col ="blue", type = "l")
matlines(conf_interval, xval, col=c("lightblue","blue","blue"))
Here is what I got:
I've looked for all the explanations on the website, but I still can't get the lines, hope you can tell me what's wrong with my code.
Thanks a lot.
lines
function works with specifying x-coordinates as the first vector and y-coordinates as the second vector.
In your case the whole plotting code might look something like this:
plot(conf_interval[ ,1] ~ xval, xlab = "newdose", ylab ="colonies", main = "Regression", ylim=range(conf_interval))
abline(salmonella_fit, col="lightblue")
lines(xval, conf_interval[,2], col="blue")
lines(xval, conf_interval[,3], col="blue")
Note that I also had to add ylim=range(conf_interval)
so that the limits of y-axis are extended. Otherwise the confidence intervals would be outside of the plotting region.