[R] Histogram for each ID value

R. Michael Weylandt michael.weylandt at gmail.com
Mon Oct 17 16:17:30 CEST 2011


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:
> Paul Hiemstra <paul.hiemstra <at> knmi.nl> writes:
>
>>
>> Hi,
>>
>> When using ggplot, take a look at facet_wrap and geom_histogram.
>>
>> regards,
>
>  More specifically, try something along the lines of
>
> d <- data.frame(f=factor(paste("chr",rep(c(1,2,3,7,9,22),each=50),sep="")),
>     v=runif(300))
> library(ggplot2)
> ggplot(d,aes(x=v))+geom_histogram()+facet_wrap(~f)
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list