6

I want to put two histograms together in one graph, but each of the histogram is based on different column. Currently I can do it like this, But the position=dodge does not work here. And there is no legend (different color for different column).

p <- ggplot(data = temp2.11)
p <- p+ geom_histogram(aes(x = diff84, y=(..count..)/sum(..count..)), 
                       alpha=0.3, fill ="red",binwidth=2,position="dodge")
p <- p+ geom_histogram(aes(x = diff08, y=(..count..)/sum(..count..)), 
                       alpha=0.3,, fill ="green",binwidth=2,position="dodge")
joran
  • 169,992
  • 32
  • 429
  • 468
ToToRo
  • 373
  • 1
  • 5
  • 12
  • 2
    Please provide a [reproducible example](http://stackoverflow.com/a/5963610/1462147) so we can more effectively address your question. – tkmckenzie Aug 14 '14 at 20:27

1 Answers1

8

You have to format your table in long format, then use a long variable as aesthetics in ggplot. Using the iris data set as example...

data(iris)

# your method
library(ggplot2)
ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length, y=(..count..)/sum(..count..)), 
                       alpha=0.3, fill ="red",binwidth=2,position="dodge") +
  geom_histogram(aes(x = Sepal.Width, y=(..count..)/sum(..count..)), 
                       alpha=0.3,, fill ="green",binwidth=2,position="dodge")

# long-format method
library(reshape2)
iris2 = melt(iris[,1:2])
ggplot(data = iris2) +
  geom_histogram(aes(x = value, y=(..count..)/sum(..count..), fill=variable), 
                 alpha=0.3, binwidth=2, position="identity")
essicolo
  • 803
  • 7
  • 13