将传奇添加到具有重叠密度的ggplot直方图中

时间:2021-01-28 14:58:16

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

我用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

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.

目前,这个情节看起来像是我想要的,但它缺少一个解释黑色和红色密度图的图例,我还没能想出如何添加它们。

将传奇添加到具有重叠密度的ggplot直方图中

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

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

1 个解决方案

#1


2  

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_color_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 

将传奇添加到具有重叠密度的ggplot直方图中

#1


2  

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_color_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 

将传奇添加到具有重叠密度的ggplot直方图中