Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding legend to a multi-histogram ggplot

Tags:

r

ggplot2

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?

like image 503
user1701545 Avatar asked Sep 04 '16 23:09

user1701545


1 Answers

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

like image 100
Psidom Avatar answered Oct 12 '22 01:10

Psidom