Q:

Two data series overlayed on the same bar chart/histogram

I'm using ggplot2 and I need to display two sets of data on the same histogram and need to distinguish between them. At the moment, I'm just setting the colour of each series to be 50% opacity so that I can see bars that are hidden behind each other but this is far from ideal, looks really ugly and is quite confusing to read off of.
Is there a way that R can intelligently overlay bars so that I can use completely opaque bars and there is never a bar hidden from view? Here's my code at the moment:
library(ggplot2)
dat <- data.frame(a=sample(10, size=100, replace=T),
                  b=sample(10, size=100, replace=T))
ggplot(dat, aes(x=a), fill=rgb(1,0,0,0.5)) + geom_histogram()
                           + geom_histogram(aes(x=b), fill=rgb(0,0,1,0.5))

Any pointers are much appreciated.

A:

work in long format, and then use position_dodge to dodge the overlapping bins. If you want them still overlapping, then you could set alpha as well
eg
library(reshape2)
ldat <- melt(dat)

 # slight overlap
 ggplot(ldat, aes(x=value, colour = variable, fill = variable)) + 
    geom_histogram(position = position_dodge(width = 0.5), binwidth = 1, alpha =0.5)

# or the default value
ggplot(ldat, aes(x=value, colour = variable, fill = variable)) + 
  geom_histogram(position = 'dodge', binwidth = 1)

Or you could use faceting, which will mean your problem disappears, as you aren't overplotting anymore
ggplot(ldat, aes(x=value)) + 
  geom_histogram(binwidth=1,fill = 'grey', colour = 'black') +
  facet_grid(~variable)

