How to create a plot with 2 overlapping histograms?

Suppose I have the following data from 2 distinct groups.

set.seed(1)
grupo1<-rnorm(400,6,2)
grupo2<-rnorm(200,8,2)

How do I make a histogram of the two groups on the same screen, identifying each of the groups with a distinct color and seeing the overlap of the 2 histograms?

Author: Carlos Cinelli, 2014-02-21

1 answers

You can do with the base functions by placing semi-transparent colors:

 h1<-hist(grupo1)
h2<- hist(grupo2)
plot(h1, col=rgb(0,0,1,1/4),
     main = "Histogramas",
     xlab = "x",
     ylim =c(min(min(h1$counts), min(h2$counts)), max(max(h1$counts, max(h2$counts)))),
     xlim=c(min(min(h1$breaks), min(h2$breaks)), max(max(h1$breaks, max(h2$breaks)))))
plot(h2, col=rgb(1,0,0,1/4), add=T) 

Note that care must be taken to place the boundaries xlim and ylim so that the second and first graph fit together on the screen.

insert the description of the image here

To do with ggplot2 you need your data to be in the format data.frame:

set.seed(1)
grupo1<-data.frame(valor=rnorm(400,6,2), grupo="grupo1")
grupo2<-data.frame(valor=rnorm(200,8,2), grupo="grupo2")

Note that to reproduce the same graph we did with the base, the binwidth of each group has to be different (but not necessarily this is better, since in command hist this was chosen automatically, I'm doing for illustration):

ggplot(grupo1,aes(valor, fill=grupo)) + 
  geom_histogram(alpha = 0.5, position = 'identity',binwidth = 1)+
  geom_histogram(data=grupo2,alpha = 0.5, position = 'identity',binwidth = 2)

insert the description of the image here

 4
Author: Carlos Cinelli, 2014-02-21 15:28:58