How to plot two histograms together in R?

David B picture David B · Aug 22, 2010 · Viewed 439.8k times · Source

I am using R and I have two data frames: carrots and cucumbers. Each data frame has a single numeric column which lists the length of all measured carrots (total: 100k carrots) and cucumbers (total: 50k cucumbers).

I wish to plot two histogram - carrot length and cucumbers lengths - on the same plot. They overlap, so I guess I also need some transparency. I also need to use relative frequencies not absolute numbers since the number of instances in each group is different.

something like this would be nice but I don't understand how to create it from my two tables:

overlapped density

Answer

Dirk Eddelbuettel picture Dirk Eddelbuettel · Aug 24, 2010

Here is an even simpler solution using base graphics and alpha-blending (which does not work on all graphics devices):

set.seed(42)
p1 <- hist(rnorm(500,4))                     # centered at 4
p2 <- hist(rnorm(500,6))                     # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10))  # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T)  # second

The key is that the colours are semi-transparent.

Edit, more than two years later: As this just got an upvote, I figure I may as well add a visual of what the code produces as alpha-blending is so darn useful:

enter image description here