[R] Two datasets on one histogram

Earl F. Glynn efg at stowers-institute.org
Wed Apr 2 20:30:54 CEST 2008

"Charlotte Wright" <queenb1 at ntlworld.com> wrote in message 
news:000801c894cb$2ff5d0d0$0301a8c0 at charlottcwe5f3...
>I have two .txt files with lists of generated data I want to plot them on 
>the same histogram. I'm aware of the histbackback function, but that is not 
>really what I am looking for, I just want them on the same histogram but so 
>they are still grouped separately (different colours, different norm curves 
>etc). Does anyone know how to do this? Thank you.

Consider these two tips from old postings:

# Adapted from Michael Watson, R-Help, 2 Feb 2005
a <- rnorm(15000, mean=1.0)
b <- rnorm(20000, mean=1.5)
ah <- hist(a,breaks= seq(-5,6,by=0.2),plot=FALSE)
bh <- hist(b,breaks= seq(-5,6,by=0.2),plot=FALSE)
data <- t(cbind(ah$counts,bh$counts))
barplot(data,beside=TRUE, space=rep(0,2*ncol(data)), col=c("red", "black"))

# Alternative to using multiple histograms to compare many variables:
# Adapted from Adaikalavan Ramasamy, R-Help, 2 Feb 2005
# simulate data
x1 <- rnorm(1000, 0.4, 0.8)
x2 <- rnorm(1000, 0.0, 1.0)
x3 <- rnorm(1000, -1.0, 1.0)

# density plots
plot( density(x1), xlim=range( c(x1, x2, x3) ), main="", xlab="" )
lines(density(x2), col=2)
lines(density(x3), col=3)

# rug plots for displaying actual data points
# you can add jitter() to rug() but with 1000 obs not much difference
rug(x1, col=1, ticksize=0.01, line=2.5)
rug(x2, col=2, ticksize=0.01, line=3.0)
rug(x3, col=3, ticksize=0.01, line=3.5)

Earl F. Glynn
Stowers Institute for Medical Research

More information about the R-help mailing list