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

时间:2015-12-24 09:22:13

标签: r histogram

我正在努力完成我的任务。 我们必须叠加正态拟合的分组直方图。 现在,我已经设法在Basic R图,Lattice和Ggplot中得到degroup histogram。在Basic R graph中,我也能够获得正常的曲线,但是在Lattice和Ggplot中我似乎没有这样做。

这是来自莱迪思和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    
...

我的图表看起来像这样:

Graph from Lattice

Graph form Ggplot

1 个答案:

答案 0 :(得分:4)

你在找这样的东西吗?我无法访问您的数据集,所以我使用了虹膜数据集

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()

给这个 enter image description here