简体   繁体   中英

R ggplot: Two histograms (based on two different column) in one graph

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM