简体   繁体   English

如何绘制置信区间以更好地展示ggplot2的置信区间?

[英]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. 使用interval = "confidence"重复预测,并将这些线添加到绘图中。

# 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. 现在像以前一样制作您的最终剧情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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