Re: plotting list object using ggplot

16 views
Skip to first unread message

Dennis Murphy

unread,
Nov 25, 2012, 7:18:57 PM11/25/12
to Daniel Marcelino, ggp...@googlegroups.com
Hi:

Here's one attempt; note that the ggplot() function generally takes
data frames as input, so the data manipulation game is to produce a
data frame out of the vectors of simulated success proportions. It is
then 'melted' using the reshape2 package and the melted data frame is
passed to ggplot(). The purpose of melting is to create a factor
variable whose levels are the sample size strings, since they are the
labels you want for the facets in facet_wrap() below.

N <- 8619170
nn <- c(1000, 1200, 3000)
p <- .27
nsim <- 100

# This works because a data frame is a special case of a list object
DF <- data.frame(lapply(nn, function(n) rhyper(nsim, N * p, N * (1 - p), n)/n))
names(DF) <- paste("n =", nn)

library(reshape2)
library(ggplot2)
DFm <- melt(DF)

ggplot(DFm, aes(x = value)) +
geom_histogram(binwidth = 0.001) +
theme_bw() +
geom_vline(xintercept = 0.27, color = "red", linetype = "longdash") +
facet_wrap(~ variable, ncol = 1) +
labs(x = "Success proportion", y = "Frequency")

Dennis

On Sun, Nov 25, 2012 at 10:13 AM, Daniel Marcelino <dmsil...@gmail.com> wrote:
> 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

Daniel Marcelino

unread,
Nov 25, 2012, 7:58:40 PM11/25/12
to Dennis Murphy, ggp...@googlegroups.com
Thanks Dennis.

Daniel
--
"Small steps toward a much better world"

\begin{signature}
Daniel Marcelino
Land Phone 1+514 343 6111 #3799
3200 Jean Brillant, Office C5071
Montreal, QC; H3T 1N8
Canada
\end{signature}
Reply all
Reply to author
Forward
0 new messages