简体   繁体   中英

How to draw confidence bounds to better demonstrate the confidence interval on ggplot2?

This code draws the regression line, the confidence interval and the prediction interval. The confidence interval is colored in gray. I need to add a code to draw the confidence bounds to better demonstrate the confidence interval.

library(ggplot2)
x<-Allele<- c(4,4,5,5,5,7,9,11,11,11,13,14,15,15,16,17,17,19,19,19)
y<-SR<- c(5.5,5.6,5.7,6,6.1,8,8,12,12.1,13,14,14,16,16.5,17,17,
17.1,18,19,20)
D3S = data.frame(Allele, SR)
Mod <- lm(SR ~ Allele) 
pred.int <- predict(Mod, interval = "prediction")
mydata <- cbind(D3S, pred.int)
# Regression line + confidence interval
p <- ggplot(mydata, aes(Allele, SR)) +
geom_point(size=3) +
stat_smooth(method = lm, color="black")
# Add prediction intervals
myplot= p + geom_line(aes(y = lwr), color = "black", 
linetype = "dashed", size=0.8)+
geom_line(aes(y = upr), color = "black", 
linetype = "dashed", size=0.8)
myplot + theme_bw() + theme(panel.border = element_blank(), 
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), 
axis.line = element_line(colour = "black"))

像这样

You almost had it in your original code. Repeat the prediction with interval = "confidence" and add those lines to your plot.

# Right after you get the prediction intervals:
conf.int <- predict(Mod, interval = "confidence")

# Change the cbind line to this:
mydata <- data.frame(D3S, pred.int, conf.int) # checks names and adds .1 to dupes

# Right after you added prediction interval, do this:
myplot <- myplot + 
  geom_line(aes(y = lwr.1), color="red") + 
  geom_line(aes(y = upr.1), color="red")

Now produce your final plot as you did before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM