R ggplot:一个图中的两个直方图(基于两个不同的列)

ToT*_*oRo 3 r ggplot2

我想在一个图中将两个直方图放在一起,但每个直方图都基于不同的列.目前我可以这样做,但position = dodge在这里不起作用.并且没有传说(不同列的颜色不同).

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")
Run Code Online (Sandbox Code Playgroud)

ess*_*olo 5

你必须以长格式格式化表格,然后在ggplot中使用长变量作为美学.以虹膜数据集为例......

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")
Run Code Online (Sandbox Code Playgroud)