在刻面情况下覆盖直方图的正常曲线

时间:2016-01-26 14:02:16

标签: r plot ggplot2 facet-wrap

我已经用相应的beta模拟了一些x和y变量,我已经完成了自举并尝试使用facet绘制每个beta的直方图。但是我希望在每个方面分别覆盖每个β的均值和标准差的正态分布图。您可以将数据模拟为,

require(simrel)
require(ggplot2)
require(reshape2)

sim <- simrel(n=50, p=10, m=2, q=5, relpos=c(1,3), gamma=0.25, R2=0.75, ntest = 50)
boot <- 200
b.boot <- matrix(nrow = boot, ncol = sim$p + 1)
r2.boot <- c()
for (i in 1:boot) {
  idx <- sample(1:nrow(sim$X), nrow(sim$X), replace = TRUE)
  dt <- data.frame(y = I(sim$Y), x = I(sim$X))[idx, ]
  lm.mdl <- lm(y ~ x, data = dt)
  b.boot[i, ] <- coef(lm.mdl)
  r2.boot[i] <- summary(lm.mdl)$r.squared
}
colnames(b.boot) <- paste("beta", 0:sim$p)
rownames(b.boot) <- 1:boot
sumry.beta <- as.data.frame(sapply(c("mean", "sd"), function(x){apply(b.boot, 2, match.fun(x))}))

我正在尝试使用ggplot,代码是

b.boot.mlt <- data.frame(melt(b.boot))

ggplot(b.boot.mlt[b.boot.mlt$Var2 != "beta 0",], aes(value)) + 
  geom_histogram(aes(y = ..density.., fill = Var2), bins = 30) + 
  facet_wrap(~Var2, nrow = 2) + geom_density(color = "gray") + 
  stat_function(fun = dnorm, 
                args = list(mean = sumry.beta$mean, sd = sumry.beta$sd), 
                color = "red", alpha = 0.5)

我得到的输出是, enter image description here

我显然不想得到,我想在每个方面得到一个正常的情节。 有谁可以帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

我遵循了Axeman的建议,并能够在Hadley的指导下生成所需的情节。我使用了以下代码,与帖子类似,

b.boot.mlt <- b.boot.mlt[b.boot.mlt$Var2 != "beta 0", ]
grid <- with(b.boot.mlt, seq(min(value), max(value), length.out = 150))
dens <- plyr::ddply(b.boot.mlt, "Var2", function(x){
  data.frame(
    value = grid,
    density = dnorm(grid, mean(x$value), sd(x$value))
  )
})

ggplot(b.boot.mlt, aes(value)) + 
  geom_histogram(aes(y = ..density.., fill = Var2), bins = 30) + 
  facet_wrap(~Var2, nrow = 2) + geom_density(color = "gray") + 
  geom_line(data = dens, aes(y = density), color = "red", alpha = 0.5) +
  theme_bw()

谢谢!