【发布时间】:2016-01-26 14:02:15
【问题描述】:
我已经用各自的 beta 模拟了一些 x 和 y 变量,我已经完成了引导并尝试使用 facet 绘制每个 beta 的直方图。但我想在每个方面分别覆盖每个 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)
我显然不想得到,我想在每个方面都得到一个正常的情节。 谁能帮帮我。谢谢!
【问题讨论】:
标签: r plot ggplot2 facet-wrap