20

This should actually be really simple but I'm having a really hard time finding a solution to this problem.

I have two very simple numeric vectors in R. I am simply trying to plot a histogram with them. However I would like them to be on the same graph. The tricky part is R overlaps these two histograms by default. I would like the bins to be simply side by side so I can get a better visual representation of the data.

Basically this is what I want to do

enter image description here

I am fairly new to R and statistical computing languages in general so I would appreciate it if you would answer my frustrating problem.

Marc in the box
  • 11,769
  • 4
  • 47
  • 97
user2331197
  • 213
  • 1
  • 2
  • 8

2 Answers2

18

The example comes from using the plotrixpackage. Code was found here. You will first need to install that package before you can access the multihist function:

#install.packages("plotrix")
require(plotrix)

l <- list(rnorm(50),rnorm(50,sd=2),rnorm(50,mean=3))
multhist(l)

enter image description here

Marc in the box
  • 11,769
  • 4
  • 47
  • 97
13

Here is the ggplot version of this graph.

require(ggplot2)
require(reshape2)

set.seed(1)
df <- data.frame(x = rnorm(n = 1000, mean = 5, sd = 2),
                 y = rnorm(n = 1000, mean = 2),
                 z = rnorm(n = 1000, mean = 10))



ggplot(melt(df), aes(value, fill = variable)) + geom_histogram(position = "dodge")

enter image description here

dickoa
  • 18,217
  • 3
  • 36
  • 50
  • This another way to do it, but it's not exactly what the OP is looking for. – Jilber Urbina Apr 29 '13 at 08:44
  • 2
    @Jiber You are right, thanks. But the OP said "I would like the bins to be simply side by side so I can get a better visual representation of the data" so there's room for proposing similar visualization. – dickoa Apr 29 '13 at 08:47
  • I think switching to `geom_freqpoly` might be even more effective. – hadley Oct 16 '13 at 15:08