Reputation: 29
I am trying to add these two sample into one histogram with one layer for a and another layer for b. After the graph, how do I add legend to the graph?
a <- rnorm(50,10,1)
b <- rnorm(100,10,2)
qplot(a,binwidth = 0.5,fill = "Red")+geom_histogram(b,fill="Blue",alpha = 0.2)
It gave the following message: Error: Mapping must be created by aes()
or aes_()
Thank you
Upvotes: 0
Views: 289
Reputation: 54287
Given
library(ggplot2)
set.seed(1)
a <- rnorm(50,10,1)
b <- rnorm(100,10,2)
you could do
qplot(a,binwidth = 0.5,fill = "Red") +
geom_histogram(aes(b), as.data.frame(b), fill="Blue",alpha = 0.2)
or
df <- stack(list(a=a, b=b))
ggplot(df, aes(x=values, fill=ind)) + geom_histogram(alpha=.5, binwidth = 0.5)
(The latter one is called long-format as @Pascal noted.)
Upvotes: 2