library(plyr)
set.seed(204)
dat <- data.frame(val = rnorm(30), g = sample(letters[1:3], 30, replace=T))
# This generates a data frame of counts for a histogram
myhist <- function(df, colname, breaks) {
h <- hist(df[[colname]], breaks = breaks, plot = F)
xmin <- h$breaks[-length(h$breaks)] # Min value for each bin
xmax <- h$breaks[-1] # Max value for each bin
data.frame(xmin, xmax, count = h$counts, total = sum(h$counts))
}
# Demostration of myhist: this returns a data frame of the counts for
# the whole data frame
myhist(dat, "val", seq(min(dat$val), max(dat$val), length.out=5))
# xmin xmax count total
# -3.3133854 -1.9180915 2 30
# -1.9180915 -0.5227977 9 30
# -0.5227977 0.8724962 17 30
# 0.8724962 2.2677900 2 30
# Now do the same thing, but split by group
hdat <- ddply(dat, .(g), myhist, "val", breaks = seq(min(dat$val), max(dat$val),
length.out=5))
# g xmin xmax count total
# a -3.3133854 -1.9180915 1 6
# a -1.9180915 -0.5227977 1 6
# a -0.5227977 0.8724962 3 6
# a 0.8724962 2.2677900 1 6
# b -3.3133854 -1.9180915 0 10
# b -1.9180915 -0.5227977 4 10
# b -0.5227977 0.8724962 6 10
# b 0.8724962 2.2677900 0 10
# c -3.3133854 -1.9180915 1 14
# c -1.9180915 -0.5227977 4 14
# c -0.5227977 0.8724962 8 14
# c 0.8724962 2.2677900 1 14
hdat$countscaled <- hdat$count / hdat$total
# g xmin xmax count total countscaled
# a -3.3133854 -1.9180915 1 6 0.16666667
# a -1.9180915 -0.5227977 1 6 0.16666667
# a -0.5227977 0.8724962 3 6 0.50000000
# a 0.8724962 2.2677900 1 6 0.16666667
# b -3.3133854 -1.9180915 0 10 0.00000000
# b -1.9180915 -0.5227977 4 10 0.40000000
# b -0.5227977 0.8724962 6 10 0.60000000
# b 0.8724962 2.2677900 0 10 0.00000000
# c -3.3133854 -1.9180915 1 14 0.07142857
# c -1.9180915 -0.5227977 4 14 0.28571429
# c -0.5227977 0.8724962 8 14 0.57142857
# c 0.8724962 2.2677900 1 14 0.07142857
ggplot(hdat) +
geom_rect(aes(xmin=xmin, xmax=xmax, ymin=0, ymax=countscaled * 100),
colour="black", fill="white") +
facet_grid(g ~ .)