【问题标题】:ggplot2: Highlight area depending on dnorm functionggplot2:根据 dnorm 功能突出显示区域
【发布时间】:2017-10-21 08:01:08
【问题描述】:

我想突出显示垂直线和正态分布函数之间的区域。我知道它如何处理离散值,但 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) 

还不满意。

【问题讨论】:

标签: r ggplot2


【解决方案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 中可以定义不同的几何图形,只需选择适合您需要的几何图形即可。

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 2011-04-06
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多