使用ggplot绘制列表对象 [英] plotting list object using ggplot
本文介绍了使用ggplot绘制列表对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在运行一些模拟,我想知道在一个漂亮的ggplot中绘制结果,但似乎ggplot无法处理列表对象。
N < - 8619170
nn < - c (1000,1200,3000)
p < - .27
nsim < - 100
phat < - list()
for(i in 1: (nn)){
n <-nn [i]
x < - rhyper(nsim,N * p,N *(1-p),n)
phat [[i ]] <-x / n
}
丑陋的解决方案:
names(phat)< - paste(n =,nn)
stripchart(phat,method =stack)
abline(v = p,lty = 2,col =red)
解决方案
ggplot2需要一个data.frame作为源数据。因此,您需要:
- 用reshape2(或plyr或许多其他工具)转换数据
-
使用qplot或ggplot进行绘图
eg
# #变换数据
require(reshape2)
h< - do.call(cbind,phat)
h.melt< - melt(h)
##重命名变量,使它们在图上看起来更美观
名称(h.melt)< -c(test,N,value)
##带状图(未示出)
qplot(data = h.melt,x = value,y = N,color = N)+ geom_point()
##直方图(未显示)
ggplot(h .melt,aes(x = value,fill = N))+ geom_histogram()+ facet_grid(N〜。)
##地毯点图(未显示)
ggplot(h。 (如下所示)
(a)(x = value,fill = N))+ geom_dotplot()+ facet_grid(N〜。)+ geom_rug()
## ggplot(h.melt,aes(x = value,fill = N))+ geom_density()+ facet_grid(N〜。)+ geom_rug()
I'm running some simulations that I was wondering to plot the outcomes in a beautiful ggplot, but it seems that ggplot can't deal with list objects. Does anyone knows how to paste the results into ggplot chart?
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
}
Ugly solution:
names(phat) <- paste("n=", nn)
stripchart(phat, method="stack")
abline(v=p, lty=2, col="red")
解决方案
ggplot2 need a data.frame as a source data. So you need to :
- transform the data with reshape2 (or plyr or many other tools)
plot using qplot or ggplot
e.g
## 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()
这篇关于使用ggplot绘制列表对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文