似乎确实不能使用 geom_histogram 而是我们必须手动计算计数(条形高度)和置信区间限制。首先,计算计数:
library(plyr)
mtcars_counts <- ddply(mtcars, .(carb), function(x) data.frame(count=nrow(x)))
剩下的问题是计算二项式比例的置信区间,这里是计数除以数据集中的案例总数。文献中提出了多种公式。在这里,我们将使用在 PropCIs 库中实现的 Agresti & Coull (1998) 方法。
library(PropCIs)
numTotTrials <- sum(mtcars_counts$count)
# Create a CI function for use with ddply and based on our total number of cases.
makeAdd4CIforThisHist <- function(totNumCases,conf.int) {
add4CIforThisHist <- function(df) {
CIstuff<- add4ci(df$count,totNumCases,conf.int)
data.frame( ymin= totNumCases*CIstuff$conf.int[1], ymax = totNumCases*CIstuff$conf.int[2] )
}
return (add4CIforThisHist)
}
calcCI <- makeAdd4CIforThisHist(numTotTrials,.95)
limits<- ddply(mtcars_counts,.(carb),calcCI) #calculate the CI min,max for each bar
mtcars_counts <- merge(mtcars_counts,limits) #combine the counts dataframe with the CIs
g<-ggplot(data =mtcars_counts, aes(x=carb,y=count,ymin=ymin,ymax=ymax)) + geom_bar(stat="identity",fill="grey")
g+geom_errorbar()