使用ggplot绘制列表对象

dan*_*iel 8 r ggplot2

我正在运行一些模拟,我想知道在一个漂亮的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)

ags*_*udy 8

ggplot2需要data.frame作为源数据.所以你需要:

  1. 使用reshape2(或plyr或许多其他工具)转换数据
  2. 使用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)

    在此输入图像描述

  • 只是稍微改掉这个答案,我们可能会将列命名为使它们在绘图中看起来更好,并尝试直方图,密度图,点图,并可能添加地毯.例如:`names(h.melt)< - c("test","N","value")ggplot(h.melt,aes(x = value,fill = N))+ geom_histogram()+ facet_grid( N~.)+ geom_rug()ggplot(h.melt,aes(x = value,fill = N))+ geom_dotplot()+ facet_grid(N~.)+ geom_rug()ggplot(h.melt,aes(x =值,填补= N))+ geom_density()+ facet_grid(N〜)+ geom_rug()` (2认同)