我正在运行一些模拟,我想知道在一个漂亮的ggplot中绘制结果,但似乎ggplot无法处理列表对象.有谁知道如何将结果粘贴到ggplot图表中?
N <- 8619170
nn <- c(1000, 1200, 3000)
p <- .27
nsim <- 100
phat <- list()
for (i in 1:length(nn)) {
n <- nn[i]
x <- rhyper(nsim, N * p, N * (1 - p), n)
phat[[i]] <- x / n
}
Run Code Online (Sandbox Code Playgroud)
names(phat) <- paste("n=", nn)
stripchart(phat, method="stack")
abline(v=p, lty=2, col="red")
Run Code Online (Sandbox Code Playgroud)
ggplot2需要data.frame作为源数据.所以你需要:
使用qplot或ggplot绘图
例如
## transform data
require(reshape2)
h <- do.call(cbind, phat)
h.melt <- melt(h)
## rename variables so they look nicer on plots
names(h.melt) <- c("test","N","value")
## stripchart (not shown)
qplot(data = h.melt, x = value,y = N,color=N)+geom_point()
## histogram (not shown)
ggplot(h.melt,aes(x=value,fill=N))+geom_histogram()+facet_grid(N~.)
## dotplot with rug (not shown)
ggplot(h.melt,aes(x=value,fill=N))+geom_dotplot()+facet_grid(N~.)+geom_rug()
##density plot with rug (shown below)
ggplot(h.melt,aes(x=value,fill=N))+geom_density()+facet_grid(N~.)+geom_rug()
Run Code Online (Sandbox Code Playgroud)
