[英]Add legend to ggplot histogram with overlayed density plots
I am drawing a histogram using ggplot2 and overlaying a density plot (in black). 我正在使用ggplot2绘制直方图并覆盖密度图(黑色)。 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. 目前,情节看起来我想要它看起来但它缺少一个解释黑色和红色密度图的图例,我无法弄清楚如何添加它们。
I am learning R and any help would be greatly appreciated. 我正在学习R,任何帮助将不胜感激。
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
. 首先,您使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.