2017-10-21 52 views
0

我想突出显示垂直线和正常分布函数之间的区域。我知道它是如何与离散值一起工作的,但stat_function让我感到困惑。代码看起来像这样:ggplot2:高亮区域取决于dnorm函数

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

看到此https://stackoverflow.com/questions/20355849/ggplot2-shade-area-under-density-curve-by-group [GGPLOT2遮阳面积 – Alice

+2

可能的复制密度曲线下通过组](https://stackoverflow.com/questions/20355849/ggplot2-shade-area-under-density-curve-by-group) – Alice

+0

https://github.com/Andryas/distShiny/blob/master/global.R <=看到这个。 –

回答

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,只需选择适合自己需要的人。

enter image description here