Skip to content
Prev 274647 / 398502 Next

Histogram for each ID value

Like others have suggested, I think ggplot2 is probably the best way
to go about this, but if you'd rather use base graphics (and you never
indicated how you felt about ggplot2), you could do something like
this with tapply:

fcts <- letters[sample(9,1500,T)]
vals <- rnorm(1500)
df <- data.frame(category = factor(fcts),values = vals)

n <- length(levels(df$category))
n <- (ceiling(sqrt(n)))
layout(matrix(1:n^2,n))
tapply(df$values, df$category, hist, n=15,simplify=F)

One of the unattractive features of this solution is that the
histogram titles aren't particularly helpful: something like this can
force a solution,

tapply(df$values, df$category, function(x){
    mn = deparse(substitute(x))
    mn = levels(df$category)[as.integer(substr(mn,4,regexpr("L",mn)-1))]
    hist(x, n = 15, main = mn)
    },simplify=F)

but it's evidently not the prettiest (especially when compared to ggplot2).

Anyways, another vote for the methods already suggested with this as
an alternative if needed.

Cheers,

Michael Weylandt
On Mon, Oct 17, 2011 at 9:58 AM, Ben Bolker <bbolker at gmail.com> wrote: