6

I'm trying to add a legend to a ggplot of two histograms, that may overlap and therefore would like to have them slightly transparent:

library(ggplot2)
set.seed(1)
plot.df <- data.frame(x=c(rnorm(1000,30,1),rnorm(10000,40,5)),
                      group=c(rep("a",1000),rep("b",10000)))

using:

ggplot(plot.df,aes(x=x,fill=factor(group)))+ 
  geom_histogram(data=subset(plot.df,group=='a'),fill="red",alpha=0.5)+
  geom_histogram(data=subset(plot.df,group=='b'),fill="darkgray",alpha=0.5)+
  scale_colour_manual(name="group",values=c("red","darkgray"),labels=c("a","b"))+scale_fill_manual(name="group",values=c("red","darkgray"),labels=c("a","b"))

but all I get is:

enter image description here

What's missing?

user1701545
  • 5,706
  • 14
  • 49
  • 80

1 Answers1

7

Instead of plotting the two hisgrams separately, you can specify the fill parameter in the mapping as the group variable, in which case the legend will be automatically generated.

ggplot(plot.df, aes(x=x, fill = group)) + 
  geom_histogram(alpha = 0.5) + 
  scale_fill_manual(name="group",values=c("red","darkgray"),labels=c("a","b"))

enter image description here

Borrowed from here, the trick lies in setting up the fill parameter in the mapping(i.e aes here) of each of the histogram plot and then you can use scale_fill_manual normally:

ggplot(plot.df,aes(x=x))+ 
    geom_histogram(data=subset(plot.df,group=='a'),aes(fill=group),alpha=0.5)+
    geom_histogram(data=subset(plot.df,group=='b'),aes(fill=group),alpha=0.5)+
    scale_fill_manual(name="group", values=c("red","darkgray"),labels=c("a","b"))

enter image description here

Community
  • 1
  • 1
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Thanks for the suggestion. However, that ggplot code doesn't make the histograms transparent. I updated my question to make this point clearer. – user1701545 Sep 04 '16 at 23:39
  • Updated the answer. You need to wrap the `fill` parameter in the `aes` in order for `ggplot` to recognize and generate the legend for you. – Psidom Sep 04 '16 at 23:58