无法将正态曲线拟合到分组直方图

Can't fit a normal curve to a grouped histogram

我正在努力完成分配给我的任务。 我们必须制作一个叠加了正常拟合的分组直方图。 现在,我已经设法在 Basic R graph、Lattice 和 Ggplot 中获得了去分组直方图。在 Basic R graph 中,我也能够在其中获得一条正态曲线,但在 Lattice 和 Ggplot 中我似乎无法这样做。

这是我来自 Lattice 和 Ggplot 的 R 脚本:

#Lattice:
library(lattice)
histogram(~SBP, data= DataSBP, breaks=10,
          type=c("density"), 
          groups = User, panel = function(...)panel.superpose(...,panel.groups=panel.histogram, col=c("navy","maroon3"),alpha=0.4),
          auto.key=list(columns=2,rectangles=FALSE, col=c("navy","maroon3")))
panel.mathdensity(dmath=dnorm, col="black", args=list(mean=mean(x, na.rm = TRUE), sd=sd(x, na.rm = TRUE)))

当我尝试命令 "panel.mathdensity" 时没有任何反应。

# Ggplot
library(ggplot2)
ggplot(DataSBP, aes(x=SBP)) + geom_histogram(aes(y=..density.., x=SBP, colour=User, fill=User),alpha=0.5, binwidth = 5, position="identity")
+ stat_function(fun = dnorm, args = list(mean = SBP.mean, sd = SBP.sd))

如果我尝试 stat_function 命令,我总是得到错误 "SBP.mean" 无法找到,这可能意味着我必须定义 SBP.mean,但是如何?

我的数据是这样的:

User SBP    
No 102    
No 116    
No 106    
...    
Yes 117    
Yes 127    
Yes 111    
...

我的图表是这样的:

您正在寻找这样的东西吗?我无权访问您的数据集,所以我使用了 iris 数据集

library(dplyr); library(ggplot2)

meanSe <- iris %>% 
  filter(Species == "setosa") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
meanVe <- iris %>% 
  filter(Species == "versicolor") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
meanVi <- iris %>% 
  filter(Species == "virginica") %>% 
  summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
#
ggplot(iris, aes(x=Sepal.Length, color=Species, fill=Species)) +
  geom_histogram(aes(y=..density..), position="identity", binwidth=.5) + 
  stat_function(fun = dnorm, color="red", args=list(mean=meanSe$means, sd=meanSe$sd)) + 
  stat_function(fun = dnorm, color="green", args=list(mean=meanVe$means, sd=meanVe$sd)) + 
  stat_function(fun = dnorm, color="blue", args=list(mean=meanVi$means, sd=meanVi$sd)) + 
  theme_bw()

给这个