正常曲线图上的区域错误

时间:2017-09-19 14:06:50

标签: r ggplot2 area normal-distribution

我正在尝试从零开始学习R,我刚刚为假设测试二项分布(一个样本的比例测试)提供了大学作业,我使用R来求解和绘制。但我遇到了一些问题。

我的样本量为130,成功案例为68.

  • H0:π= 50%
  • H1:π> 50

这是我使用的代码(大量复制粘贴和试用/错误)

library(ggplot2)
library(ggthemes)
library(scales)


#data

n = 130
p = 1/2
stdev = sqrt(n*p*(1-p))
mean_binon = n*p
cases = 68
ztest = (cases-mean_binon)/stdev
pvalor = pnorm(-abs(ztest))
zcrit = qnorm(0.975)

#normal curve
xvalues <- data.frame(x = c(-4, 4))

#first plots and lines
p1 <- ggplot(xvalues, aes(x = xvalues))
p2 <- p1 + stat_function(fun = dnorm) + xlim(c(-4, 4)) +
    geom_vline(xintercept = ztest, linetype="solid", color="blue", 
               size=1) +
    geom_vline(xintercept = zcrit, linetype="solid", color="red", 
                   size=1)


#z area function
area_z <- function(x){
    norm_z <- dnorm(x)
    norm_z[x < ztest] <- NA
    return(norm_z)
}

#critical z area function
area_zc <- function(x){
    norm_zc <- dnorm(x)
    norm_zc[x < zcrit] <- NA
    return(norm_zc)
}


#area value
valor_area_z <- round(pnorm(4) - pnorm(ztest), 3)
valor_area_zc <- round(pnorm(4) - pnorm(zcrit), 3)


#final plot

p3 <- p2 + stat_function(fun = dnorm) + 
    stat_function(fun = area_z, geom = "area", fill = "blue", alpha = 0.3) +
    geom_text(x = 1.13, y = 0.1, size = 5, fontface = "bold",
              label = paste0(valor_area_z * 100, "%")) +
    stat_function(fun = area_zc, geom = "area", fill = "red", alpha = 0.5) +
    geom_text(x = 2.27, y = 0.015, size = 3, fontface = "bold",
              label = paste0(valor_area_zc * 100, "%")) +
    scale_x_continuous(breaks = c(-3:3)) + 
    labs(x = "\n z", y = "f(z) \n", title = "Distribuição Normal \n") +
    theme_fivethirtyeight()

p3

这是情节

enter image description here

我的geom_vline与阴影区域之间存在差距。我不确定我的统计数据是否采取了错误的步骤,或者这是与R相关的问题。也许两者?对不起,如果这是基本的。我不擅长这两个,但我正在努力提高。

1 个答案:

答案 0 :(得分:2)

解决方案是使用xlim内的stat_function选项来定义函数的范围。
您还可以将area_zarea_zc替换为{ {1}}。

dnorm

enter image description here