作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面的代码绘制了均值的抽样分布图,并计算了 20 个批处理的 95% 置信区间。如何在直方图上绘制置信区间,如下面的 Photoshop 图像所示?
# plot sampling distribution of mean -----------------------------------------------------------
set.seed(1)
population <- rnorm(10000, 3, 3)
population_mean <- mean(population)
my_sample <- sample(population, 100, replace = FALSE)
standard_error <- sqrt(var(my_sample)/length(my_sample))
sampling_distribution_of_mean <- rnorm(10000, mean = population_mean, sd = standard_error)
library(ggplot2)
ggplot(data.frame(x = sampling_distribution_of_mean), aes(x)) + geom_histogram() + geom_vline(xintercept = population_mean, color = "red")
# calculate 20 lots of 95% confidence intervals -----------------------------------------------------------
my_confidence_intervals <- function(){
my_sample <- sample(population, 100, replace = FALSE)
sample_mean <- mean(my_sample)
standard_error <- sqrt(var(my_sample)/length(my_sample))
margin_of_error <- 1.96*standard_error
mean_minus_margin_of_error <- sample_mean - margin_of_error
mean_plus_margin_of_error <- sample_mean + margin_of_error
c(mean_minus_margin_of_error, mean_plus_margin_of_error)
}
library(plyr)
llply(1:20, function(x) my_confidence_intervals())
最佳答案
您可能希望构建一个包含间隔的 data.frame,然后添加一层水平误差条来绘制它们。首先,我将您的范围转换为 data.frame
xx<-llply(1:20, function(x) my_confidence_intervals())
xx<-data.frame(y=1:20*50, x=do.call(rbind, xx))
现在我将它们添加到绘图中
ggplot(data.frame(x = sampling_distribution_of_mean), aes(x)) +
geom_histogram() +
geom_vline(xintercept = population_mean, color = "red") +
geom_errorbarh(aes(y=y, x=x.1, xmin=x.1, xmax=x.2), data=xx, col="#0094EA", size=1.2)
给出
请注意,我在创建 data.frame 时为每个范围明确设置了 y 值。
关于r - 使用ggplot2在直方图上绘制置信区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31191167/
我是一名优秀的程序员,十分优秀!