簡體   English   中英

使用ggplot2在直方圖上繪制置信區間

[英]Draw confidence interval on histogram with ggplot2

下面的代碼繪制了平均值的采樣分布,並計算了20個95%置信區間。 如何在直方圖上繪制置信區間,如下面的Photoshopped圖像所示?

# 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值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM