我想尝试使用R再现下面的图像。目标是将单面和双面假设表示为.025和.95级别,类似于下图:
我设法使用来自其他问题的资源在分位数内创建阴影,但我希望它超出边界,而不是在内部。代码:
set.seed(1)
draws <- rnorm(1000000)
dens <- density(draws)
q025 <- quantile(draws, .025)
q975 <- quantile(draws, .975)
dd <- with(dens, data.frame(x, y))
library(ggplot2)
qplot(x, y, data = dd, geom="line") +
geom_ribbon(data = subset(dd, x > q025 & x < q975),
aes(ymax = y),
ymin = 0, fill = "red", colour = NA, alpha = 0.5)
生成:
答案 0 :(得分:1)
这有点笨重,但似乎有效;请注意填充不是很完美。
set.seed(1)
draws <- data.frame(x = rnorm(1000000))
q025 <- quantile(draws$x, .025)
q975 <- quantile(draws$x, .975)
ggplot(draws, aes(x)) +
geom_density() +
stat_function(fun = dnorm, xlim = c(min(draws$x), q025), geom = "area") +
stat_function(fun = dnorm, xlim = c(q975, max(draws$x)), geom = "area")
结果:
编辑:这是一个较慢的版本,填充更顺畅。
set.seed(1)
draws <- rnorm(1000000)
dd <- data.frame(x = draws, y = dnorm(draws))
q025 <- quantile(draws$x, .025)
q975 <- quantile(draws$x, .975)
ggplot(dd, aes(x, y)) +
geom_line() +
stat_function(fun = dnorm, xlim = c(min(draws$x), q025), geom = "area") +
stat_function(fun = dnorm, xlim = c(q975, max(draws$x)), geom = "area")
结果: