下面的代碼顯示均值的採樣分佈圖並計算20個95%置信區間的批次。如何在直方圖上繪製置信區間,如下面的Photoshopped圖中所示?使用ggplot2在直方圖上繪製置信區間
# 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())
我的問題與任務無關,但您究竟想要展示什麼? – Dason
樣本的均值的抽樣分佈與95%的置信區間意味着 – luciano
也許您會想要包含一些垂直線以指示中間95%的抽樣分佈也是如此。這樣,更容易看到樣本意味着落在該邊界之外導致置信區間不能捕獲均值。 – Dason