R ggplot: two histograms (based on two different bars) on one plot

I want to put two histograms together on one graph, but each of the histograms is based on different bars. Currently I can do it like this, but position = dodge doesn't work here. And there is no legend (different colors for different columns).

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")

      

+3


source to share


1 answer


You need to format the table in long format and then use the long variable as aesthetics in ggplot. Using the aperture dataset as an 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")

      

+5


source







All Articles