使用叠加密度图将图例添加到 ggplot 直方图

Add legend to ggplot histogram with overlayed density plots

我正在使用 ggplot2 绘制直方图并覆盖密度图(黑色)。然后我覆盖一个正常的密度图(红色)。

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

目前,该图看起来像我想要的样子,但缺少解释黑色和红色密度图的图例,我无法弄清楚如何添加它们。

我正在学习 R,非常感谢任何帮助。

一个选项是这个。首先,您使用 aes(color = "Name you want") 包含图例标签,然后使用 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