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:

What's missing?
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"))

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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With