ggplot2:根据dnorm函数突出显示区域

时间:2017-10-21 08:01:08

标签: r ggplot2

我想突出显示垂直线和普通分布函数之间的区域。我知道它如何与离散值一起使用,但stat_function让我感到困惑。代码看起来像这样:

library(ggplot2)

n1 <- 5

ggplot(data.frame(x = c(-2, 2)), aes(x)) + 
  stat_function(fun = dnorm, args = list(sd = 1/sqrt(n1))) + 
  geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
  geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) + 
  ylim(c(0, 1.5)) + 
  theme_light() + 
  geom_rect(aes(xmin = 0.5, xmax = Inf, ymax = Inf, ymin = 0), fill = "grey", alpha = .3)   

我知道我需要将ymax更改为x>的值。 0.5。问题是如何?

编辑: 我调查了应该和我一样的问题。当我按照他们的方式重写代码时,突出显示有效,但它不再给我一个正确的正态分布,正如你在这里看到的那样:

library(dplyr)

set.seed(123)
range <- seq(from = -2, to = 2, by = .01)
norm <- rnorm(range, sd = 1 / sqrt(n1))
df <- data_frame(x = density(norm)$x, y = density(norm)$y)

ggplot(data_frame(values = norm)) + 
  stat_density(aes(x = values), geom = "line") + 
  geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
  geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) + 
  ylim(c(0, 1.5)) + 
  theme_light() + 
  geom_ribbon(data = filter(df, x > 0.5), 
          aes(x = x, ymax = y), ymin = 0, fill = "red", alpha = .5) 

当我坚持使用stat_function并使用geom_ribbon和同一问题中提出的子集时,它会突出显示错误,正如您在此处所见:

ggplot(data_frame(x = c(-2, 2)), aes(x)) + 
  stat_function(fun = dnorm, args = list(sd = 1/sqrt(n1))) + 
  geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
  geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) + 
  ylim(c(0, 1.5)) + 
  theme_light() + 
  geom_ribbon(data = filter(df, x > 0.5), 
      aes(x = x, ymax = y), ymin = 0, fill = "red", alpha = .5) 

还不满意。

1 个答案:

答案 0 :(得分:1)

这是一种方法:

library(ggplot2)
n1 <- 5
ggplot(data.frame(x = c(-2, 2)), aes(x)) + 
  stat_function(fun = dnorm, geom = "area",  fill = "grey", alpha = 0.3, args = list(sd = 1/sqrt(n1)), xlim = c(-0.5,0.5)) +
  stat_function(fun = dnorm, args = list(sd = 1/sqrt(n1))) + 
  geom_vline(xintercept = 0.5, linetype = "dashed", color = "red", size = 1) +
  geom_vline(xintercept = -0.5, linetype = "dashed", color = "red", size = 1) + 
  ylim(c(0, 1.5)) + 
  theme_light() 
stat_function

可以定义不同的geom,只需选择适合您需求的geom。

enter image description here