在ggplot2中将正态曲线叠加到直方图

Overlay normal curve to histogram in ggplot2

我想为一个名为 "Dist" 的向量绘制直方图,它具有正态分布,并用总体参数覆盖正态曲线。我在 Whosebug 中发现了几篇关于同一主题的帖子,但 none 我收到的错误消息。

plot1 <-ggplot(data = dist) + 
  geom_histogram(mapping = aes(x = dist), fill="steelblue", colour="black", binwidth = 1) +
  ggtitle("Frequences")

我尝试了几种方法来将正态曲线添加到之前的图中:

首先,将函数添加到具有所需值的直方图块代码中:

stat_function(fun = dnorm, args = list(mean = mu2, sd = sd2))

但是这段代码并没有给情节增加任何东西。结果是一样的,只是直方图。

此外,创建一条曲线并将其添加到图中。

#Create the curve data
x <- seq(8, 24, length.out=100)
y <- with(dist, data.frame(x = x, y = dnorm(x, mean(mu2), sd(sd2))))

#add the curve to the base plot
plot1 + geom_line(data = y, aes(x = x, y = y), color = "red")

这给了我下一条错误消息:

删除了 100 行包含缺失值 (geom_path)。

但我实际上没有在向量中找到任何已删除的值或空值,所以我不确定如何解决这个问题。

我也可以在没有 ggplot2 的情况下以非常简单的方式做到这一点,尽管我有兴趣在 ggplot2 中做到这一点:

hist(dist$dist, freq =FALSE, main="histogram")
curve(dnorm(x, mean = mu2, sd = sd2), from = 8, to = 24, add = TRUE)

我怀疑 stat_function 确实增加了正态分布的密度。但是 y 轴范围让它在图的底部一直消失。如果使用 aes(x = dist, y=..density..) 而不是绝对计数将直方图缩放到密度,则 dnorm 的曲线应该可见。

(顺便说一句,我觉得你的分布不正常。你可能想检查一下,例如 qqplot

library(ggplot2)

dist = data.frame(dist = rnorm(100))

plot1 <-ggplot(data = dist) + 
  geom_histogram(mapping = aes(x = dist, y=..density..), fill="steelblue", colour="black", binwidth = 1) +
  ggtitle("Frequences") +
  stat_function(fun = dnorm, args = list(mean = mean(dist$dist), sd = sd(dist$dist)))