[英]Can't fit a normal curve to a grouped histogram
我正在为分配的任务而苦苦挣扎。 我们必须制作一个叠加了正常拟合的分组直方图。 现在,我已经设法在Basic R图,Lattice和Ggplot中获得了分组的直方图。 在Basic R图中,我也可以在其中得到一条法线,但是在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
...
我的图看起来像这样:
您在寻找这样的东西吗? 我无权访问您的数据集,所以我使用了虹膜数据集
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.