Yi Hao
Yi Hao

Reputation: 29

Adding legend to layer qplot with two data in single histogram

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

Answers (1)

lukeA
lukeA

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

Related Questions