R – Add legend to ggplot histogram with overlayed density plots

density-plotggplot2legendplotr

I am drawing a histogram using ggplot2 and overlaying a density plot (in black). I then overlay a normal density plot (in red).

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)), rating = c(rnorm(200),rnorm(200, mean=.8)))
plot <- ggplot(dat, aes(x = rating)) 
plot <- plot + geom_histogram(aes(y=..density..), color="black", fill = "steelblue", binwidth = 0.5, alpha = 0.2)
plot <- plot + geom_density()
plot <- plot + stat_function(fun = dnorm, colour = "red", args = list(mean = 0.3, sd = 1))
plot

Currently, the plot looks like I want it to look but it is missing a legend explaining the black and red density plots and I have not been able to figure out how to add them.

enter image description here

I am learning R and any help would be greatly appreciated.

Best Answer

An option is this. First you include the legend labels with aes(color = "Name you want") and then add the colours using scale_colour_manual.

plot <- ggplot(dat, aes(x = rating))
plot <- plot + geom_histogram(aes(y = ..density..), color = "black", fill = "steelblue", binwidth = 0.5, alpha = 0.2)
plot <- plot + geom_density(aes(color = "Density"))
plot <- plot + stat_function(aes(colour = "Normal"), fun = dnorm, args = list(mean = 0.3, sd = 1)) + 
  scale_colour_manual("Legend title", values = c("black", "red"))
plot 

enter image description here