I'm trying to draw two black lines around a red regression line. But the lines()
command draws something more like a polygon()
than a simple line (see picture below code).
I'm wondering is there a fix to simply draw two lines around the regression line (i.e., uncertainty intervals), or I'm missing something?
library(rstanarm)
data(kidiq)
d <- kidiq
fit <- stan_glm(kid_score ~ mom_iq,
data = d,
prior = normal(0, 2.5),
prior_intercept = normal(0, 10),
prior_aux = cauchy(0, 100))
plot(kid_score ~ mom_iq, data = d, type = "n")
abline(fit, col = 2)
pred_lin <- posterior_linpred(fit)
loop <- length(d$mom_iq)
I <- matrix(NA, loop, 2)
for(i in 1:loop){
I[i,] = quantile(pred_lin[,i], c(.025, .975))
}
lines(d$mom_iq, I[,1], lty = 2)
lines(d$mom_iq, I[,2])
Try the ordered data.frame like:
a <- cbind(d$mom_iq, I[,1])
a <- a[order(a[,1]),]
lines(a)
So you can also write:
lines(sort(d$mom_iq), I[,2][order(d$mom_iq)])
or simply:
apply(I, 2, function(x) lines(sort(d$mom_iq), x[order(d$mom_iq)]))