我在R中有一个散点图,我想为每个值添加90%的置信区间。我已经拥有了所有间隔的值。我只需要指导如何在图片中绘制它们。
例如,我有一个坐标为(1, 2)
的点,其置信区间为[1.9,2.1
](垂直)。如何为此点绘制此间隔?
答案 0 :(得分:2)
这是一个可能对您有帮助的实现。
data <- structure(list(growth = c(12L, 10L, 8L, 11L, 6L, 7L, 2L, 3L,
3L), tannin = 0:8), .Names = c("growth", "tannin"), class = "data.frame", row.names = c(NA,
-9L))
attach(data)
names(data)
plot(tannin,growth,pch=16,ylim=c(0,12))
model<-lm(growth ~ tannin)
abline(model)
ci.lines<-function(model,conf= .95 ,interval = "confidence"){
x <- model[[12]][[2]]
y <- model[[12]][[1]]
xm<-mean(x)
n<-length(x)
ssx<- sum((x - mean(x))^2)
s.t<- qt(1-(1-conf)/2,(n-2))
xv<-seq(min(x),max(x),(max(x) - min(x))/100)
yv<- coef(model)[1]+coef(model)[2]*xv
se <- switch(interval,
confidence = summary(model)[[6]] * sqrt(1/n+(xv-xm)^2/ssx),
prediction = summary(model)[[6]] * sqrt(1+1/n+(xv-xm)^2/ssx)
)
# summary(model)[[6]] = 'sigma'
ci<-s.t*se
uyv<-yv+ci
lyv<-yv-ci
limits1 <- min(c(x,y))
limits2 <- max(c(x,y))
predictions <- predict(model, level = conf, interval = interval)
insideCI <- predictions[,'lwr'] < y & y < predictions[,'upr']
x_name <- rownames(attr(model[[11]],"factors"))[2]
y_name <- rownames(attr(model[[11]],"factors"))[1]
points(x[!insideCI],y[!insideCI], pch = 16, col = 'red')
lines(xv,uyv,lty=2,col=ifelse(interval=="confidence",3,4))
lines(xv,lyv,lty=2,col=ifelse(interval=="confidence",3,4))
}
ci.lines(model, conf= .95 , interval = "confidence")
答案 1 :(得分:0)
例如,我有一个坐标为(1,2)的点,其置信区间为[1.9,2.1](垂直)
segments(0.9, 1.9, 1.1, 1.9, col="red") # lower bound
segments(0.9, 2.1, 1.1, 2.1, col="red") # upper
segments(1 , 1.9, 1, 2.1, col="red", type=3) # vertical dashed line connecting
工作示例:
plot(rnorm(20, 1), rnorm(20,2))
points( 1,2, col="blue", cex=2)
segments(0.9, 1.9, 1.1, 1.9, col="red") # lower limit
segments(0.9, 2.1, 1.1, 2.1, col="red") # upper
segments(1 , 1.9, 1, 2.1, col="red", lty=3) # dashed vertical line connecting