无法将正态曲线拟合到分组的直方图 [英] Can't fit a normal curve to a grouped histogram

查看:104
本文介绍了无法将正态曲线拟合到分组的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为分配的任务而苦苦挣扎. 我们必须制作一个叠加了正常拟合的分组直方图. 现在,我已经设法在Basic R图,Lattice和Ggplot中获得了分组的直方图.在Basic R图中,我还可以在其中获得一条法线,但是在Lattice和Ggplot中,我似乎这样做失败.

I'm struggling with an assignment I was given. We have to make a grouped histogram with normal fit superimposed. Now, I already managed to get de grouped histogram in Basic R graph, Lattice and Ggplot. In Basic R graph, I was also able to get an normal curve in it, but in Lattice and Ggplot I seem to fail in doing so.

这是我的Lattice和Ggplot中的R脚本:

Here is my R script from Lattice and Ggplot:

#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"时,什么都没有发生.

When I try the command "panel.mathdensity" nothing happens.

# 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,但是如何定义?

If I try the stat_function command, I always get the error "SBP.mean" can't be found, which probably means I have to define SBP.mean, but how?

我的数据是这样的:

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

我的图看起来像这样:

推荐答案

您是否正在寻找类似的东西?我无权访问您的数据集,所以我使用了虹膜数据集

Were you looking for something like this? I don't have access to your dataset so I used the iris dataset

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

给这个

这篇关于无法将正态曲线拟合到分组的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆